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.

Tuesday, December 20, 2011

OpenVPN Access Server

I am currently evaluating the OpenVPN Access Server for our environment. We are using the opensource version of OpenVPN from last one year and working good without any issues. The good thing with the Access Server is, it is highly self explanatory for the users for the client configuration. Also the management of the same can be done through a nice gui.

As I said the client configuration is self explanatory for the users, but it is good for only Windows and Mac users. Because they are giving client applications only for Mac and Windows clients. For linux users, they are telling to use the native "openvpn" command.

But there is a big caveat for linux users when using it with the openvpn native command, "The server will not be able to push the dhcp-options to clients". The main issue is the clients will not get the "dns server addresses", "default domain name" & "domain search values".

As a result the users connects to the Access server on linux, will not be able to resolve the FQDNs of internal servers or URLs of internal sites.

Also, the client configuration giving from the server "client.ovpn" is the only file which carries the certificates and keys within the configuration file itself. This is preventing to use other openvpn client applications like KVPNC or NetworkManager gui applet.

How to overcome this limitations?

It is easy to make a configuration compatible with the other openvpn clients like NetworkManager or Kvpnc.

Basically we need to split the given configuration "client.ovpn" to five files; "ca.crt", "client.crt", "client.key", "ta.key" and "new-client.ovpn".

We can do all this manually using a text editor, but I have made a simple shell script which will do this for us.

#!/bin/bash
#
sed -n '//,/<\/ca>/ p' client.ovpn |grep -v "" |grep -v "" >ca.crt

sed -n '//,/<\/cert>/ p' client.ovpn |grep -v "" |grep -v "" >client.crt

sed -n '//,/<\/key>/ p' client.ovpn |grep -v "" |grep -v "" >client.key

sed -n '//,/<\/tls-auth>/ p' client.ovpn |grep -v "" |grep -v "" >ta.key

grep -v "#" client.ovpn > client1.ovpn

sed '//,/<\/tls-auth>/ d' client1.ovpn >new-client.ovpn

echo "ca ca.crt" >>new-client.ovpn

echo "cert client.crt" >>new-client.ovpn

echo "key client.key" >>new-client.ovpn

echo "tls-auth ta.key 1" >>new-client.ovpn

rm client.ovpn client1.ovpn

  • Copy the above script and save it as "ovpn-split.sh" into your directory holding the "client.ovpn" file.
  • Run $ chmod +x ovpn-split.sh
  • Run the script as $ sh ovpn-split.sh
  • Now you have all the needed files to use with kvpnc or NetworkManager cleints.


How to Backup the Access Server 

The main difference between the AS and opensource version is that, all the configuration in AS is stored in Sqlite database. So there are chances to have corrupt the DB when you archive the entire folder of /usr/local/openvpn_as when the server is running. If the access server is not running a full archive of the /usr/local/openvpn_as directory is good enough for restoring in case of any disaster.

In this case we have a utility "sqlite3" comes with the AS installation. It is easy to create the db backup using the sqlite3 command, which is actually allow the user to store the db files as text files. But for the ease of regular use I have written a script which can be run regularly under cron, so you will have backups of all the DB files in text file format.

#!/bin/bash
#
# This script is to backup the SQLITE db using the sqlite3 utility comes with the OpenVPN AS server.
#Set the script directory
COMMAND=/usr/local/openvpn_as/scripts
#Set the DB directory
DB_DIR=/usr/local/openvpn_as/etc/db
#Set the destination backup directory as it is.
BACKUP_DIR=/root/backup_db
#
    for i in certs.db config.db log.db userprop.db
    do
    $COMMAND/sqlite3 $DB_DIR/$i .dump >$BACKUP_DIR/$i.txt
    done
#Innorder to restore Sqlite DB from text, use the following command syntax:
#
#./sqlite3 <[TEXT_FILE] [DB_FILE]
#
#While the DBs can be dumped while the Access Server is running, you should stop the Access Server before you restore the DBs.

Wednesday, June 29, 2011

Install (Free) g729 codec on Trixbox CE (asterisk)

g729 is a low bandwidth codec, which can operates at a lower bandwidth of 8Kb/s. This tutorial describes how to install the g729 free codec on trixbox CE.

Download the Codec

Free version of the g729 codecs are available on http://asterisk.hosting.lv/#bin .

Depending on the architecture and the version of asterisk on your machine, download the correct package from the above site.
For finding the asterisk version and system processor architecture we can use the following commands.

astersik -V
uname -a
I have downloaded the following package which worked fine for my Xeon dual core processor and asterisk version 1.4.
[trixbox ~]# wget http://asterisk.hosting.lv/bin/codec_g729-ast14-gcc4-glibc-core2-sse4.so

Rename the codec file

Rename the downloaded file and copy it to /usr/lib/asterisk/modules directory as follows,
[trixbox ~]# cp codec_g729-ast14-gcc4-glibc-core2-sse4.so /usr/lib/asterisk/modules/codec_g729.so

Reload Asterisk

Load the above copied module, by issuing the following command on asterisk console,
[trixbox ~]# asterisk -r
trixbox*CLI> codec load codec_g729

Check the work

Verify the codec has been loaded correctly by the following command on console,
trixbox*CLI> show translation
you will see a line as below for g729,

g729 - 2 2 2 2 2 1 3 - 9 10 2 -

If everything went well as mentioned above, we can test the codec functionality by enabling it in an extension as below,

Test the codec working

Login to the web interface and go to PBX-> PBX Settings-> Extensions, choose one extension you wish to enable the codec for, ensure disallow is set to “all” and allow is set to “g729”.

Once the extension is set up to allow g729, you can test whether it’s working properly by having a test call connected and running the command sip show channels:

trixbox*CLI> sip show channels
It will list the output as below,

192.168.113.35 3245 eefbd3ee-b5 00101/00001 0x100 (g729) No Rx: ACK
We are done.

Troubleshooting

If you didn’t see the codec translation as mentioned above then probably you downloaded the wrong codec, please check again the points mentioned during downloading the codec

Thursday, May 26, 2011

Setting Time on Cisco & HP switches

Setting correct time on the network devices is a very important step, when you configure new equipments. But most of the people don't care this in case of switches and other devices.

But be aware, the correct time on the devices will help you a lot when you refer logs to find out the details of any issues or access related items etc.

Here I am putting some simple commands to configure time on Cisco and HP Procurve switches.

Adding NTP server names in these devices is the easier and safer way, but if you don't have an NTP server in house and no interest of using public NTP servers, then you may need to set the time locally.

Cisco

On a Cisco device (switch or router), use the following commands to add an NTP server

switch01(config)# ntp server 131.107.1.10
switch01(config)# ntp server 202.152.74.200 prefer

prefer means this is the preferred one.

And if you want to set it manually on the machine, use the following commands.

switch01(config)#clock timezone IST +5

The above command will set the timezone, my time zone is IST and the +5 denotes it is 5 hour ahead from GMT.

For setting date and time, need to run the command on privileged execution mode (enable#). The following is the syntax of setting the same.

clock set hh:mm:ss <1-31> MONTH <1993-2035>

So we can run the command as follows,

switch01#clock set 18:30:01 26 May 2011

We can check the current time on the switch by show clock command and the output will be similar as below,

switch01#show clock
18:31:19.738 IST Thu May 26 2011

HP Procurve

To setup Procurve to use external NTP servers for time synchronization, use the following commands.

switch02(config)#sntp server 192.43.244.18
switch02(config)#sntp unicast
switch02(config)#timesync sntp

If you prefer to set the time manually, you can use any of the following pair of commands.

time MM/DD[/[YY]YY]
time HH:MM[:SS]
(OR)
clock set MM/DD[/[YY]YY]
clock set HH:MM[:SS]

switch02(config)# clock set 05/26/2011
switch02(config)# clock set 18:35:01

We can use show time command to display the current time on the system and the output will be similar as follows,

switch02(config)#show time
Thu May 26 18:58:12 2011

Hope this will help somebody like me, who need to google several times a day to find valuable informations.

Thursday, May 19, 2011

Find dormant accounts on a Linux server

In busy production systems, there will be lot of accounts which may not be using from longer intervals. Finding them we have standard linux utilities like "last" and "lastlog".

The "last" command display the audit details of the users who were logged in the system with time frame. On the other hand "lastlog" display all the user's last logged in details with time frame.

last command uses the log file /var/log/wtmp for getting the user data. As in the modern linux systems, the wtmp file is rotating monthly basis the last command gives only the current month's statistics.

If we want to have the last command output with an yearly statistics, we need to change the rotation configuration in /etc/logrotate.conf as below,

/var/log/wtmp {
missingok
monthly <= change it to "yearly"
create 0664 root utmp
rotate 1
}

The following script will display the users who are not logged in the last 3 calendar months including the current month. I am sure this will be usefull for people like me to get a clear idea of who are not active on the system.

#!/bin/bash
#
#
# Gives a list of users who have not logged in the last 3 calendar months including the current one.
#
umask 077

THIS_MONTH=`date +%h`
LAST_MONTH=`date --date="1 month ago" +%h`
LLAST_MONTH=`date --date="2 months ago" +%h`

last | grep "$THIS_MONTH \|\ $LAST_MONTH \|\ $LLAST_MONTH" | awk '{print $1}' | sort -u > /tmp/users1$$
cat /etc/passwd | awk -F: '{print $1}' | sort -u > /tmp/users2$$
comm -13 /tmp/users[12]$$
rm -f /tmp/users[12]$$


The above script assumes the last command can show the user statistics of more than 3 months.

Using "lastlog"

The simple and dirty way to find the dormant accounts on a linux system is using the"lastlog" command. The following script will do the trick.

#!/bin/bash
#
#
# Gives a list of users who have not logged in the last 90 days.
#
PATH=/bin:/usr/bin;export PATH
umask 077
lastlog -b 90 |grep -iv Never | awk '{print $1}' | sort -u > /tmp/users1$$
lastlog |grep -iv Never | awk '{print $1}' | sort -u > /tmp/users2$$
comm -2 /tmp/users[12]$$ | grep -v Username
rm -f /tmp/users[12]$$

Friday, July 23, 2010

Mediawiki Migration

This is again I have done as part of our datacenter movement from India to US. We are on the recent release of mediawiki (1.15.2), I just need to make the ditto box in US before shutting down the old one in India. There are plenty of help articles on internet which helped me to do the same, again I am detailing here because of my future reference and ofcourse may help somebody like you.

The following are the details of the software versions installed on both the boxes.

MediaWiki 1.15.2
PHP 5.1.6 (apache2handler)
MySQL 5.0.77

Lets start the detailed step of the upgrade as follows,

On Old Server:-
  1. Shutdown apache server for stoping further updates to the wiki (#service httpd stop)
  2. Backed up all the content of the web folder of apache (mediawiki files) (#tar -zcvf wiki.tar.gz /var/www/html/wiki)
  3. Copy the tar file to the new server
  4. Dump the MySQL database (#mysqldump -u (username) -p (password) wikidb >backup-wikidb.sql )
  5. Copy the dump file to the new server
On the New Server:-
  • Restore the database from the backup-wikidb.sql file (sql>mysql -u (username) -p (password) wikidb )
  • Untar the copied wiki.tar.gz file and copy it in to the documentroot of apache (#tar -zxvf wiki.tar.gz; cp -R wiki /var/www/html)
  • Edit the Localsettings.php and Adminsettings.php files to match the wikidb and wiki user credentials
  • Restart apache server (#service httpd restart)
  • If everything went well go and browse the wiki with existing user credentials.
Yes we have finished the movement of mediawiki from old server to new server...!!!

Thursday, July 22, 2010

Bugzilla Migration

As part of datacenter movement from India to US, I had to migrate my Bugzilla installation to a new server in US.

After certain googling I found the steps to do the same, but then also I had to face some issues, thats the reason for this blog.

My current Bugzilla installation (ver. 3.0) is more customized for our company purpose so I had to stick on the same version for now. Following are the steps I followed on both servers.

On new Server:-
  1. Download the bugzilla-3.0.tar.gz from bugzilla.org (I had this on my old server, so I just copied from old to new server)
  2. Untar the software (#tar -xvf bugzilla-3.2.2.tar.gz )
  3. Rename it to bugzilla (#mv bugzilla-3.2.2.tar.gz bugzilla)
  4. Copy bugzilla to apache webroot directory (#cp -R bugzilla /var/www/html )
  5. Change the permission of bugzilla folder (#chmod -R 655 bugzilla)
  6. Change the ownership to apache web user (#chown -R apache bugzilla)

Now login in mysql & create database & username.

mysql> CREATE DATABASE bugs;

mysql>grant all on bugs.* to bugs@localhost identified by 'Your Password';

mysql>commit;

mysql>quit;

Now go to the bugzilla folder and run the checksetup.pl perl script, which will tell what are the prerequisites need to install and how. Here you may need to install lot of perl modules which you can manually download from CPAN and install (perl MakeFile.PL ; make ; make install) or you can use MCPAN shell commands.

#./checksetup.pl

Old Server:-

  1. Copy the data folder (/var/www/html/bugzilla/data) to the new server and replace the existing data folder with the same.
  2. Copy localconfig file from (/var/www/html/bugzilla) folder to the new server and replace the existing file with the same.
  3. Use mysqldump to make a backup of the bugs database. For a typical Bugzilla setup, such a command might look like this:
    mysqldump -u(username) -p(password) bugs > bugzilla-backup.sql
  4. Copy the bugzilla-backup.sql file to the new server.
New Server:-
  1. Restore the mysql data backup from the bugzilla-backup.sql file with the following command.
    mysql -u (username) -p(password) bugs < /path/to/bugzilla-backup.sql
If you get an error about "packet too large" or "mysql server has gone away", you need to adjust the max_allowed_packet setting in your my.cnf (usually in /etc/my.cnf) file to be larger than the largest attachment ever added to your Bugzilla.

If everything went well, run that "./checksetup.pl" file again and double confirm everything smooth.

Now go to web url & try to login with ur existing username password.

Yes now we all done the migration from old server to new.


Cheers !!!!!


Saturday, May 9, 2009

Apache authentication against Active Directory

Apache is the world's most wanted and #1 web server on internet. Almost 50 percent of total web servers in internet running on Apache in various flavors of Operating systems.

For protecting the contents, apache support various types of authentication, which includes basic htpasswd, MySql, NTLM, LDAP, AD etc. Here I am mentioning how we can use Active Directory as a user/password database for Apache server.

Assuming we have an existing Active Directory Domain which holds the company's user informations. As part of Single Sign on, we want to use AD as the source of User credentials for accessing corporate wiki running on Apache server. Also assumes the Wiki and apache server running on GNU/Linux for documentation purpose.

The following are the steps needed to complete the integration of Apache with AD.
  • Create one user in AD which we can use as the LDAP bind user for accessing the AD database as read only. Go to Active Directory Users and Computers in the DC and create a domain user say "apache" with a strong password "xxxxxxxxx".
  • If we want to use ldaps (ldap+ssl) we need to export the certificate from AD and import it in to the web server machine. This export and import can be done in a single step using the openssl command as follows from webserver.
openssl s_client -connect dc.mydomain.com:636

Save the certificate as "domain.cer" in web server machine in /etc/httpd/conf.d directory.
  • Go to the Linux Server and create a file namely "authz_ldap.conf" under the directory /etc/httpd/conf.d with the following parameters.
LDAPTrustedGlobalCert CA_BASE64 /etc/httpd/conf.d/domain.cer
LDAPTrustedMode SSL
<"Location "/" ">
order deny,allow
Allow from all
AuthBasicProvider ldap
AuthzLDAPAuthoritative off
AuthLDAPURL "ldaps://dc.mydomain.com:636/DC=mydomain,DC=com?sAMAccountName?sub?(objectClass=*)" NONE
AuthLDAPBindDN apache@mydomain.com
AuthLDAPBindPassword xxxxxxxx
AuthType Basic
AuthName "Only for trusted users"
require valid-user
<"/Location">

Here all the AD users will get access to the website as we using the option as "require valid-user". If you want to give access to only a specific group of users, you need to use the following option instead of "valid-user".

require ldap-group CN=mygroup,OU=groups,DC=mydomain,DC=com


Note: Ignore the quotes used within Angle brackets <> for specifying "Location" and "/Location".
  • Also make sure the following modules are loaded in the apache's configuration file httpd.conf
LoadModule ldap_module modules/mod_ldap.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_host_module modules/mod_authz_host.so
  • Add the following line in /etc/openldap/ldap.conf, this is very important for the working configuration.
REFERRALS off
  • Finally restart apache server by issueing the following command.
/etc/init.d/httpd restart


Check the result by accessing the Wiki by pointing to the correct URL and enjoy !!!!!!