Tuesday, May 20, 2014

Ram disk creation on Linux

Ramdisks are very useful in the case of web servers for some heavily accessing contents.

The steps for crating Ramdisk is as follows,
Step 1: 

Edit the file /boot/grub/grub.cfg and add the entry "ramdisk_size={size in  KB}". For example if you need to crate 4GB of RAM disk, the entry should look like,


 ### BEGIN /etc/grub.d/10_linux ###
menuentry 'Ubuntu, with Linux 2.6.32-21-server' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod ext2
    set root='(hd0,1)'
    search --no-floppy --fs-uuid --set ab3827ac-8003-4bed-81c0-9248d64362b0
    linux    /vmlinuz-2.6.32-21-server root=UUID=bbfccfa9-f878-4c42-83c1-0d82c3b2f44b ro quiet  ramdisk_size=4194304
    initrd    /initrd.img-2.6.32-21-server


Make sure the above entry made is in end of the linux kernel entry and it should be in a single line.

Once you done this, do a reboot and make the kernel read the parameter while next boot.

Step 2:

You can create the ramdisk using the following command,
      mkfs -q /dev/ram1 {size of ramdisk to me created in KB}
Create a folder to act as the mount point for above created ramdisk.
      mkdir -p /ramcache 
Mount the ramdisk to /ramcache
      mount /dev/ram1 /ramcache 
Following command will display the mounted partitions including the ramdisk.
      df -H 

Grub 2 Boot Order in Debian and Ubuntu servers

Grub2 is entirely different than the older version in terms of configuration and file system hierarchy. In the version 1 of Grub, changing the boot order can be accomplished by a single file editing. But in Grub2 which need to be done in another way, we are going to describe that here.

Here are the steps to follow:

1- To edit the grub file open terminal and type the following command :
 
    sudo gedit /etc/default/grub

You will got something like this :

GRUB_DEFAULT=0
#GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT=”quiet splash”
GRUB_CMDLINE_LINUX=””
# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console
# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo’
#GRUB_GFXMODE=640×480
# Uncomment if you don’t want GRUB to pass “root=UUID=xxx” parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true
# Uncomment to disable generation of recovery mode menu entrys
#GRUB_DISABLE_LINUX_RECOVERY=”true”
 
Now to change the boot order, you need to change the GRUB_DEFAULT Entry, for example you have  windows7 in the 3rd position and you want to set it as default,  edit the entry as below

       GRUB_DEFAULT=3

2- Now update Grub using the command:
 
       sudo update-grub 

Once you run the above command, the grub configuration files will get regenerated and in the file /boot/grub/grub.cfg, you can find an entry as set default = "3"

Thursday, February 20, 2014

How to reset a lost Admin Password on Fortigate Firewall

There are scenarios where you probably have lost the admin password to enter in to a Fortigate firewall box. The following procedure will help to reset the admin password on Fortigate firewall.

1. Connect to the firewall via the Console port using a console cable, with the following parameter.

Baud 9600
Data Bits: 8
Stop Bits: 1
Parity: None
Flow Control: Off

2. Start you preferred terminal emulator (Hyper terminal, Putty or minicom on linux)
3. You should be able to see the firewall CLI login screen.
4. Reboot your device and wait until the boot process is complete.
5. Type in the username: maintainer and password is the combination of the word bcpb + serial number of the firewall (remember all serial number charachters in capital letters).

Example: bcpbFGT60B7612104239 (NO, it’s not the real S/N)

Note: you will have only 14 seconds to login as user “maintainer” after the boot process.
So it will be better if you type the password on a text editor and copy and paste it on the terminal console.

6. Now you have full access to your Fortinet box, so you can proceed to change the password with the following commands:

config system admin
edit admin
set password 
set accprofile super_admin
end

This above method worked on my Fortigate 60B and hope the same will work on other models also.

Tuesday, March 12, 2013

Basic MySQL Commands

Here I am going to explain the basic commands to deal with the most using opensouce database, MySQL. I suppose we have a working mysql database in a system already.

Login to MySQL as root user

[root@client ~]# mysql -u root@localhost -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 5.1.66 Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

List the databases

mysql> show databases;

Create a database

 mysql> create database [database_name];

 Switch to a database

mysql> use [database_name];

To see all the tables in the db

mysql> show tables;

To see the table formats

mysql> describe [table_name];

To delete a db.

mysql> drop database [database name];

To delete a table.

mysql> drop table [table name];

Show all data in a table.

mysql> SELECT * FROM [table name];

Returns the columns and column information pertaining to the designated table.

mysql> show columns from [table name];

Show certain selected rows with the value "whatever".

mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";

Show all records containing the name "Bob" AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';

Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.

mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;

Show all records starting with the letters 'bob' AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';

Show all records starting with the letters 'bob' AND the phone number '3444444' limit to records 1 through 5.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;

Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.

mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";

Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];

Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;

Return number of rows.

mysql> SELECT COUNT(*) FROM [table name];

Sum column.

mysql> SELECT SUM(*) FROM [table name];

Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;

Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;

Change a users password from unix shell.

# mysqladmin -u username -h hostname.blah.org -p password 'new-password'

Change a users password from MySQL prompt. Login as root. Set the password. Update privs.

# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;

Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.

# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Set a root password if there is on root password.

# mysqladmin -u root password newpassword

Update a root password.

# mysqladmin -u root -p oldpassword newpassword

Allow the user "bob" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges; 

Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

To update info already in a table.

mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';

Delete a row(s) from a table.

mysql> DELETE from [table name] where [field name] = 'whatever';

Update database permissions/privilages.

mysql> flush privileges;

Delete a column.

mysql> alter table [table name] drop column [column name];

Add a new column to db.

mysql> alter table [table name] add column [new column name] varchar (20);

Change column name.

mysql> alter table [table name] change [old column name] [new column name] varchar (50);

Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);

Make a column bigger.

mysql> alter table [table name] modify [column name] VARCHAR(3);

Delete unique from table.

mysql> alter table [table name] drop index [colmn name];

Load a CSV file into a table.

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Dump all databases for backup. Backup file is sql commands to recreate all db's.

# mysqldump -u root -ppassword --all-databases >/tmp/alldatabases.sql

Dump one database for backup.

# mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql

Dump a table from a database.

# mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql

Restore database (or database table) from backup.

# mysql -u username -ppassword databasename < /tmp/databasename.sql

Restore a single database from the dump of all databases.

mysql -u root -ppassword --one-database db_name

Create Table Example 1.

mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));

Create Table Example 2.

mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');




Wednesday, October 31, 2012

VLAN Trunk Between Cisco and HP Procurve switch

With a small example we are going to see how we can use Cisco and HP switches together for Vlan trunking. Before we going to discuss that in detail, let me describe the difference in 'terms' using both in Cisco and HP.

Description                                                                   Cisco                    ProCurve
A port that belongs to a unique VLAN                               Access mode        Untagged
A port carries multiple VLANs using 802.1q tags               Trunk mode           Tagged

Wednesday, October 3, 2012

Custom Destinations in Asterisk

Custom Destination feature in asterisk is a very useful functionality where we can have lot of options to make the asterisk to work in different environments. Upon using this functionality we can use a single inbound number to access all internal conference bridges, route the call to one asterisk box to another one through the trunks etc. We will describe these one by one,

  • Accessing internal conference bridges using single inbound number.

In our example, we already have a working asterisk pbx with lot of conference bridges working inside the office through VoIP phones.

We are going to make accessing all these conference bridges from the local mobile/land phones through a single inbound number. So will start as mentioned below,

1) Install "Custom Destination module" through FreePBX admin interface.
2) Create a new custom destination "conferences,s,1" with whatever description you like (ie "ConferenceIVR")
3) Add to /etc/asterisk/extensions_custom.conf the following script


[conferences]
include => ext-meetme; in [ext-meetme] contest are stored all the conferences created in FreePBX
exten => s,1,Answer
exten => s,n,Wait(1)
exten => s,n,Playback(enter-conf-call-number); Insert you welcome message
exten => s,n,Goto(w,1)
exten => w,1,Wait(1)
exten => w,n,Playback(beep)
exten => w,n(begin),Set(TIMEOUT(digit)=3)
exten => w,n,Set(TIMEOUT(response)=10)
exten => w,n,WaitExten(,)
exten => w,n,Playback(invalid)
exten => w,n,Goto(w,1)

This script asks for the conference number to join to and enters the context managing the conferences.
If the conference doesn't exists, it loops and ask again for a valid conference number.


4) Reload the Asterisk
5) Create a new Inbound Route and route it to the Custom Destination    "ConferencesIVR"
6)  Now try from local/mobile phones using the inbound number, you will be asked the conference call number to be joined and the PIN for the same.
7) Enjoy !!!


  • Pass one DID from one asterisk to another.
I have two asterisk boxes (box A & box B) in two different countries and both are inter connected through SIP trunk and able to communicate between the extensions registered on both the boxes. In one of my requirement, I have to route my company's support calls coming to one location to be routed to the support team located in the other country after the end of Office hours on first country.

What I did to achieve this are,
  • Set up a DID on box A and it's destination set to the registered extension on box A. For example, +918xxxxx1010 which rings to the local extension 1010, which finally I need to route to extension 2020 on the box B through my SIP trunk.
  • Create a custom destination on Box A as, 
custom-did-to-BoxB,${EXTEN},1
  • Then I have to go and add the following line in the /etc/asterisk/extensions_custom.conf file,  
[custom-did-to-BoxB]
exten => _X.,1,Dial(SIP/2020@IP-Of- the- BoxB,30,r)

If you are using IAX trunk the above line should look like,
[custom-did-to-BoxB]exten => _X.,1,Dial(IAX2/IP-of-the-BoxB/$2020,30,r)
  • Go to the extension 1010 on Box A and select custom destination and set the value as  custom-did-to-BoxB which we created above.
  • Reload asterisk to get it effect.
Now if you call to the local number +918xxxxx1010 and let the phone ring completely, it will route the call to the exension 2020 which is actually registered on BoxB which is in another country.

Tuesday, March 13, 2012

Configure Cisco 1841 router as an Edge Router with NAT and IOS firewall

In small Offices or branch Offices, instead of buying separate devices for edge router and Firewall we can configure the edge router as a firewall and NAT device also. This will reduce the cost of overall IT budget and which will ease the management also.

Here is a step by step configuration example to configure a Cisco 1841 integrated service router as an Edge router with NAT and a basic IOS firewall.

All the router comes with or able to install Cisco SDM, a graphical tool to make the configuration which is very helpful to make the configuration and monitor the device. But in this tutorial we will go through the CLI configuration method.

Topology

We are going to discuss is a very simple topology consists of,
  • One Internet connection ends in the WAN interface of the router (FastEthernet0/0).
  • One LAN interface (FastEthernet0/1) connects to the internal LAN L3/L2 switch.
  • LAN IP address: 10.2.2.1/24
  • WAN IP address: 2.3.3.2/30
Internet <==> Router <==> LAN


Starting the basic configuration

We will start configure the router through the console port of the router using a console cable, which normally provided with the router itself.

First make sure the router should be clean from older configurations, you can assure this by clearing the existing configurations. If you are sure with your router configuration, you can skip this stage.

router#configure terminal

router(config)#config-register 0x2102 < This register value can be found from sh version command

router(config)#end

router#write erase

router#reload

System configuration has been modified. Save? [yes/no]: n

Proceed with reload? [confirm]

When the router comes up, which will prompt you for doing the initial configuration through the configuration assistant, you can skip this because we will be doing it manually.

Configure the hostname for the router, I am going to put as Edge-01

router>en

router#conf t

router(config)#hostname Edge-01

Configure the external interface of the router with the ip address of 2.3.3.2

Edge-01(config)#interface FastEthernet0/0

Edge-01(config-if)#ip address 2.3.3.2 255.255.255.252

Edge-01(config-if)#speed 100

Edge-01(config-if)#duplex full

Edge-01(config-if)#speed 100

Edge-01(config-if)#no shut

Now configure the internal interface of the router.

Edge-01(config-if)#interface FastEthernet0/1

Edge-01(config-if)#ip address 10.2.2.1 255.255.255.0

Edge-01(config-if)#speed 100

Edge-01(config-if)#duplex full

Edge-01(config-if)#speed 100

Edge-01(config-if)#no shut

Configure the default gateway as 2.3.3.1 (change it accordingly)

Edge-01(config)#ip route 0.0.0.0 0.0.0.0 2.3.3.1

Enabling SSH:

For securely accessing this router, we will be using ssh as a remote access mechanism instead of telnet, so we need to enable ssh now.


Edge-01(config)#aaa new-model

Edge-01(config)#ip domain-name my.domain.com < This need to change with your domain-name

Edge-01(config)#crypto key generate rsa

Edge-01(config)#ip ssh time-out 60

Edge-01(config)#ip ssh authentication-retries 2

Edge-01(config)#ip ssh version 2

Enabling NAT:

For the internal clients to access the internet the router should be configured with NAT especially NAT with overload (PAT). The following commands will enable PAT and all the internal clients will be able to access the internet through this router.

Create an access-list which will be used to include the LAN addresses, the clients will be trying from

Edge-01(config)#access-list 1 permit 10.2.2.0 0.0.0.255

Now we need to tell which is internal and which is external interfaces for doing the nat.

Edge-01(config)#interface FastEthernet0/1

Edge-01(config-if)#ip nat inside

Edge-01(config-if)#interface FastEthernet0/0

Edge-01(config-if)#ip nat outside

Now we have to define the external IP address pool, which will be used by the internal clients to access the internet. Here I have only one public ip address, even if we need to define the pool, but we will use starting and ending as a single address.

Edge-01(config)#ip nat pool MYPOOL 2.3.3.2 2.3.3.2 netmast 255.255.255.252

Now define the nat with overload or PAT (Port Address Translation) as,

Edge-01(config)#ip nat inside source list 1 pool MYPOOL overload

At this point, we have a router which can be acted as the edge router and do the NAT(PAT) for the internal clients to access Internet. But it lacks a firewall so we cannot put this router in production until we configure a firewall on it.


Configure IOS Firewall

Now we are going to explore the zone based firewall functionality of Cisco IOS. Here we can create multiple security zones with various security levels which we can define. And finally we will add our router interfaces in to these security zones as zone members to avail the defined security levels.

Creating Zones and assigning interfaces

In this example we are going to create only two security zones (TRUSTED & INTERNET) and will assign each interfaces in to each of these security zones as zone members. But it is possible to create multiple security zones and also possible to add multiple interfaces (real or virtual) in to same security zones.

TRUSTED: Internal LAN connection

INTERNET: Internet connection

Create the security zones as follows,

Edge-01(config)#zone security Trusted

Edge-01(config-sec-zone)#zone security Internet

There is also a special default zone named "self". This zone applies to traffic which originates from or is destined for the control plane of router itself (e.g. routing protocols, SSH, SNMP, etc.). By default, all traffic is allowed into the self zone.

The interfaces now need to assign to security zones with the command zone-member security

Edge-01(config)#interface FastEthernet0/0

Edge-01(config-if)#zone-member security Internet

Edge-01(config-if)#interface FastEthernet0/1

Edge-01(config-if)#zone-member security Trusted

Edge-01#show zone security


Creating Zone Pairs

Zone pairs apply policy enforcement to traffic flowing from one security zone to another. A zone pair must be defined for each direction in which traffic is allowed to be initiated. For example, a common simple policy is that the internal network can initiate any sort of traffic to the Internet, but no traffic may be initiated from the Internet to the internal network. This policy requires only a single zone pair, from the internal zone to the Internet zone.

We'll create only one zone pair to meet our requirements:

  • Trusted to Internet - Allows Internet access from the internal network

The command to configure a zone pair uses the following syntax:

zone-pair security NAME source FROM-ZONE destination TO-ZONE

Here is our zone pair definition:

Edge-01(config)#zone-pair security Trusted->Internet source Trusted destination Internet

Edge-01(config-sec-zone-pair)#

Creating and Applying Security Policies

Finally, we'll define and apply our security policies to the zone pairs. Policies are defined as inspection policy maps, which are very similar in construct to policy maps used for quality of service (QoS) classification and marking. Policy maps reference class maps, which in turn reference access lists or NBAR definitions to classify traffic.

One of three security actions can be taken on traffic matched by a class map:

  • Drop - The traffic is dropped.

  • Pass - The traffic is permitted.

  • Inspect - The traffic is permitted and inspected statefully so that return traffic in the opposite direction is also permitted.

First, we'll create a class map to match all of the traffic we want to allow from the Trusted zone out to the Internet. We want to inspect all traffic outbound to the Internet so that return traffic is allowed statefully. Unfortunately, we can't use the inspect action with the default class map, so we'll need to create a custom class map to match the base protocols TCP, UDP, and ICMP. (This doesn't allow non-TCP/UDP protocols such as IPsec, but meets our needs.)

Edge-01(config)# class-map type inspect match-any All_Protocols
Edge-01(config-cmap)# match protocol tcp
Edge-01
(config-cmap)# match protocol udp
Edge-01
(config-cmap)# match protocol icmp

Our class maps need to be wrapped into service policies so that they can be associated with security actions. We do this by creating inspection policy maps.

Edge-01(config)#policy-map type inspect Trusted_to_Internet
Edge-01(config-pmap)#class type inspect All_Protocols
Edge-01(config-pmap-c)#inspect

Lastly, we'll apply the policy maps to their appropriate zone pairs.
Edge-01(config)#zone-pair security Trusted->Internet
Edge-01(config-sec-zone-pair)# service-policy type inspect Trusted_to_Internet
We can verify our configuration using the command show zone-pair security:
Edge-01# show zone-pair security
Zone-pair name Trusted->Internet
Source-Zone Trusted Destination-Zone Internet
service-policy Trusted_to_Internet

More detail regarding the entire firewall policy hierarchy can be achieved with the command
Edge-01#show policy-map type inspect zone-pair
Our Zone based firewall configuration is now completed, so its time to test the configuration. If you have lab with separated Internet connection, you can easily do the testing. Otherwise do simulate the scenario by connecting at least two machines in which one will act as LAN machine and other one will act as an Internet server.