Abhishek Singh Bailoo

Weblog

Oct 3

Asterisk iptables

Source: http://www.selbytech.com/2010/04/how-to-setup-iptables-for-asterisk-1-6-2-on-centos-5-4/

First things first, I want to point out, if you’re not careful when you’re setting up your iptables settings, there’s a very real possibility of blocking all remote access to your server.  If you’re working on your server remotely, be very careful, and be sure to read all of this article before proceeding!

First, let’s make sure we’ve already got iptables installed on our box.  It should be installed by default on most CentOS 4.x and 5.x installs.

# rpm -q iptables
iptables-1.3.5-5.3.el5_4.1

# lsmod | grep ip_tables
ip_tables              17029  1 iptable_filter
x_tables               17349  5 xt_state,ip_tables,ip6t_REJECT,xt_tcpudp,ip6_tables

With that out of the way, we can look at how iptables is currently setup, using the “iptables -L” command.  The following should be the default rules on a fresh CentOS 5.4 install.


# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
RH-Firewall-1-INPUT  all  --  anywhere             anywhere
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
RH-Firewall-1-INPUT  all  --  anywhere             anywhere
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
Chain RH-Firewall-1-INPUT (2 references)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere            icmp any
ACCEPT     esp  --  anywhere             anywhere
ACCEPT     ah   --  anywhere             anywhere
ACCEPT     udp  --  anywhere             224.0.0.251         udp dpt:mdns
ACCEPT     udp  --  anywhere             anywhere            udp dpt:ipp
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ipp
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited

If for some reason iptables isn’t running yet, you can enable it by running

# system-config-securitylevel

Now, the defaults are fine and good for defaults, but they aren’t really what we’re looking for.  So at this point we’re going to clear them out, and setup a very basic default set of access rules.  I like to use the basic ruleset from the CentOS wiki, located here.

# iptables -P INPUT ACCEPT
# iptables -F
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT

Let’s take a look at what we did here:

iptables -P INPUT ACCEPT – This sets the default policy on the input chain to ACCEPT, so we don’t lock ourselves out if we’re connected remotely via ssh.

iptables -F – This is the command to flush the current rule set and only use the defaults (which we just set to ACCEPT on inbound connections, which gives us a blank slate to work with without locking us out of our own box).

iptables -A INPUT -i lo -j ACCEPT – This is a simple rule to allow all access from the loopback adapter.  The -A switch means we’re Appending a new rule to the chain.  -i means this rule has to do with all traffic flowing through a network interface (in this case, the lo, or loopback, interface).  -j means to Jump to the ACCEPT action.  A lot of applications expect to be able to talk with the loopback adapter, so be sure to include this rule.

iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT – You should already recognize some parts of this line.  What’s new here is the -m switch, which we use to load a module (in this case, the ‘state’ module). The state module is able to examine the state of a packet and determine if it is NEW, ESTABLISHED or RELATED. NEW refers to incoming packets that are new incoming connections that weren’t initiated by the host system. ESTABLISHED and RELATED refers to incoming packets that are part of an already established connection or related to an already established connection.

iptables -A INPUT -p tcp –dport 22 -j ACCEPT – This rule is a very important rule, at least it’s important if you’re connecting remotely!  This rule is appended to the INPUT chain and says that any packets coming in on the tcp protocol (-p), on port 22 (–dport 22), should be accepted.  Port 22 is of course the default ssh port.  If you’ve changed your ssh port in your sshd_config, you would of course alter this line accordingly.

iptables -P INPUT DROP – Remember our first rule?  When we set the default policy for the INPUT chain to ACCEPT?  This line changes the default policy for the INPUT chain back to DROP, which is what is required if you want to actually block traffic coming into your server.  If you correctly set the previous line to allow ssh traffic, you shouldn’t lock yourself out at this point.

iptables -P FORWARD DROP – This rule is pretty much the same as the previous one, except that we’re setting the default policy for the FORWARD chain, which handles traffic flowing through our system from one interface to another (i.e if you’re using your server as a router, which in this case we’re not).

iptables -P OUTPUT ACCEPT – And finally, this rule allows all traffic to flow outwards from your server.

Now that we’ve got these new rules, we should save them so that they’re applied the next time we restart the iptables service.

# iptables-save

or

# service iptables save

If you want to learn more about iptables and the various switches available to you, I recommend you read the IPTables How-To on the CentOS wiki I linked to earlier.  There’s a lot of useful information there.

Now, if you want to run asterisk on your server that you’ve got protected with IPTables, you’ll need to setup a few specific rules.  Let’s go over those here:

# iptables -A INPUT -p udp -m udp --dport 5060 -j ACCEPT
# iptables -A INPUT -p udp -m udp --dport 10000:20000 -j ACCEPT
# iptables -A INPUT -p udp -m udp --dport 4000:4999 -j ACCEPT
# iptables -A INPUT -p udp -m udp --dport 4569 -j ACCEPT
# iptables -A INPUT -p tcp -m tcp --dport 5038 -j ACCEPT

Let’s take a look at what we’re doing here:

iptables -A INPUT -p udp -m udp –dport 5060 -j ACCEPT – This rule and the next are needed if you have SIP endpoints or a SIP connection to your ITSP.  UDP port 5060 is the port used for SIP traffic.  If you don’t want to accept SIP traffic from anyone, anywhere, you can further restrict this line by adding source IP addresses or networks with the -s switch:

# iptables -A INPUT -p udp -m udp -s 172.19.240.24 --dport 5060 -j ACCEPT
# iptables -A INPUT -p udp -m udp -s 172.23.129.58 --dport 5060 -j ACCEPT
# iptables -A INPUT -p udp -m udp -s 172.36.15.0/24 --dport 5060 -j ACCEPT

iptables -A INPUT -p udp -m udp –dport 10000:20000 -j ACCEPT – This rule goes hand in hand with the previous rule.  This is the rule that allows RTP traffic.  By default, asterisk uses a large range of rtp ports to establish rtp connections, and you have to set a large range of udp ports as well.  If you’re uncomfortable with this idea, you can trim down on the number of ports used for your RTP traffic in asterisk’s /etc/asterisk/rtp.conf file.

# cat /etc/asterisk/rtp.conf
[general]
rtpstart=10000
rtpend=10050

# iptables -A INPUT -p udp -m udp --dport 10000:10050 -j ACCEPT

A good rule of thumb is to have 4 ports per concurrent call you plan on having flow through your system, plus 10% for breathing room.  So if you plan on having at most 10 concurrent calls on your system at any time, configure asterisk to use 44 ports (10 calls x 4 ports = 40, 40 * 1.10 = 44).  Be sure the range in your firewall matches the range in your rtp.conf file.

iptables -A INPUT -p udp -m udp –dport 4000:4999 -j ACCEPT – This rule is used to allow udptl traffic, which is a T.38 transport protocol.  If you don’t plan on doing faxing, you can skip this rule.  I don’t have any handy rules of thumb for the number of udptl ports used per T.38 fax, so you may want to leave this rule at it’s default.  You can try changing it down, but until I hear otherwise from the folks at Digium, I’ll leave the defaults as the recommended.

iptables -A INPUT -p udp -m udp –dport 4569 -j ACCEPT – This rule is for IAX2 connections.  IAX2 is another VoIP protocol, much like SIP.  Unlike SIP, it only needs one port open on your firewall for both control traffic and audio / data traffic.  You don’t need to open any ranges of ports to allow multiple concurrent calls using IAX2 either, as it’s all handled through the one port.  If you plan on making any IAX2 connections through your firewall, be sure to open this port.

iptables -A INPUT -p tcp –dport 5038 -j ACCEPT – This rule is to allow connections to the Asterisk Manager Interface, or AMI.  If you’re not accessing AMI remotely, you should leave this rule off your firewall.

Now that you’ve got your rules in place, go ahead and test your system.  If everything seems to be working properly, save your new rules to your iptables config by running one of the following commands:

# iptables-save

or

# service itpables save

And that’s it!  You should be all set now.  If you have any questions, please feel free to leave a comment below.

Next week we’ll cover using Fail2Ban along with IPTables to secure your asterisk server from malicious and costly attacks.


Recover MySQL root Password

Source: http://www.cyberciti.biz/tips/recover-mysql-root-password.html

If you simple want to change root password then

$ mysqladmin -u root password NEWPASSWORD

Otherwise, if you do not know the root password then

You can recover MySQL database server password with following five easy steps.
 


Step # 1: Stop the MySQL server process.

Step # 2: Start the MySQL (mysqld) server/daemon process with the —skip-grant-tables option so that it will not prompt for password.

Step # 3: Connect to mysql server as the root user.

Step # 4: Setup new mysql root account password i.e. reset mysql password.

Step # 5: Exit and restart the MySQL server.

Here are commands you need to type for each step (login as the root user):

Step # 1 : Stop mysql service

# /etc/init.d/mysql stop
Output:

Stopping MySQL database server: mysqld.

Step # 2: Start to MySQL server w/o password:

# mysqld_safe --skip-grant-tables &
Output:

[1] 5988
Starting mysqld daemon with databases from /var/lib/mysql
mysqld_safe[6025]: started

Step # 3: Connect to mysql server using mysql client:

# mysql -u root
Output:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.15-Debian_1-log

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Step # 4: Setup new MySQL root user password

mysql> use mysql;
mysql> update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit

Step # 5: Stop MySQL Server:

# /etc/init.d/mysql stop
Output:

Stopping MySQL database server: mysqld
STOPPING server from pid file /var/run/mysqld/mysqld.pid
mysqld_safe[6186]: ended

[1]+  Done                    mysqld_safe --skip-grant-tables

Step # 6: Start MySQL server and test it

# /etc/init.d/mysql start
# mysql -u root -p


Install php 5.2 centos

Source: http://wiki.centos.org/HowTos/PHP_5.1_To_5.2

Summary

  

This guide describes how to upgrade the standard PHP 5.1.x packages in CentOS 5.x 32-bit to the current development versions 5.2.x. These instructions were created using CentOS 5.3 32-bit and with the following PHP packages installed:   

 

# rpm -qa |grep php
 
  php-common-5.1.6-15.el5.i386
  php-cli-5.1.6-15.el5.i386
  php-5.1.6-15.el5.i386
  php-pdo-5.1.6-15.el5.i386
  php-bcmath-5.1.6-15.el5.i386
  php-ldap-5.1.6-15.el5.i386
  php-devel-5.1.6-15.el5.i386
  php-gd-5.1.6-15.el5.i386
  php-xml-5.1.6-15.el5.i386
  php-mbstring-5.1.6-15.el5.i386
  php-mysql-5.1.6-15.el5.i386
  php-dba-5.1.6-15.el5.i386
 

  

As long as you’re using the standard PHP packages on your CentOS server you won’t need to do anything extra. If you’re using extra PHP packages that aren’t part of the standard CentOS repositories (like php-mcrypt) you’ll have to remove them or find updated versions of them.    

Add the development repositories

  

First thing we need to do is add the development repositories to yum. When we add the development repository we’re going to configure it so it only pulls PHP packages. To start we’ll need create a new yum repository configuration file (use your favorite editor):   

 

 # /etc/yum.repos.d/CentOS-Testing.repo
 

  

Copy/paste the following into this file:   

 

  # CentOS-Testing:
   # !!!! CAUTION !!!!
   # This repository is a proving grounds for packages on their way to CentOSPlus and CentOS Extras.
   # They may or may not replace core CentOS packages, and are not guaranteed to function properly.
   # These packages build and install, but are waiting for feedback from testers as to
  # functionality and stability. Packages in this repository will come and go during the
  # development period, so it should not be left enabled or used on production systems without due
  # consideration.
  [c5-testing]
  name=CentOS-5 Testing
  baseurl=http://dev.centos.org/centos/$releasever/testing/$basearch/
  enabled=1
  gpgcheck=1
  gpgkey=http://dev.centos.org/centos/RPM-GPG-KEY-CentOS-testing
  includepkgs=php*

Make sure to remove any spaces at the start of each line, then save and close the file and you’re done.

Update PHP packages

Before updating your PHP packages you’ll want to get a list of what you currently have installed. To get a list of current PHP packages run the following:

 # rpm -qa |grep php

Now you can use yum to update the PHP packages on your system:

 # yum update

You should be shown a list of packages that are going to be updated. Compare it to the list of PHP packages on your system. Note any packages that are not in the list. You’ll need to remove these packages or find updates for them because they won’t work after you update to PHP 5.2.x. If that is acceptable type “y” to continue and let yum update the packages.

Once yum has completed restart Apache:

 # service httpd restart

To verify the update is working create a simple testing.php in your www directory with the following source code:

<?php
  phpinfo();
?>

and open it in a web browser. The new PHP version should be reflected at the top of the page.

Conclusion

You should now have PHP 5.2.6 running on CentOS 5.3 32-bit.

 # rpm -qa |grep php

  php-cli-5.2.6-2.el5s2
  php-mbstring-5.2.6-2.el5s2
  php-devel-5.2.6-2.el5s2
  php-pdo-5.2.6-2.el5s2
  php-gd-5.2.6-2.el5s2
  php-dba-5.2.6-2.el5s2
  php-common-5.2.6-2.el5s2
  php-bcmath-5.2.6-2.el5s2
  php-xml-5.2.6-2.el5s2
  php-pear-1.5.1-2.el5s2
  php-ldap-5.2.6-2.el5s2
  php-5.2.6-2.el5s2
  php-mysql-5.2.6-2.el5s2


 # php -v

  PHP 5.2.6 (cli) (built: Sep 15 2008 20:42:05)
  Copyright (c) 1997-2008 The PHP Group
  Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies

Note: If your “php -v” output returns errors about PDO or JSON click here

Extras

Updating/Installing mcrypt

If you have php-mcrypt for PHP 5.1.x installed you’ll want to remove it:

Note: Your version number maybe different. Alter below command accordingly.

 rpm -e php-mcrypt-5.1.6-15.el5.centos.1

Download php-mcrypt for PHP 5.2.x and install it. You can find a 32-bit php-mcrypt package here FedoraJunkies.

Note: You’ll notice the “—nodeps” flag in the example. When you try to install php-mcrypt without it you get an error that php-common-5.2.6-2.el5s2 is missing even though it is installed.

 wget -c http://sourcemirrors.org/scotth/centos/5/php/php-mcrypt-5.2.6-2.i386.rpm
 rpm -i --nodeps php-mcrypt-5.2.6-2.i386.rpm

Restart Apache and you should now see mcrypt information on your testing.php page.

JSON and PDO being loaded twice

When you run the command “php -v” you might see the following errors:

 # php -v

  PHP Warning:  Module 'json' already loaded in Unknown on line 0
  PHP Warning:  Module 'PDO' already loaded in Unknown on line 0
  PHP 5.2.6 (cli) (built: Sep 15 2008 20:42:05)
  Copyright (c) 1997-2008 The PHP Group
  Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies

This is caused by the following two lines in the /etc/php.ini file:

; Extension JSON
extension=json.so

; Extension PDO
extension=pdo.so

Comment out these lines by adding a ”;” in front of “extension=”. These two modules are already loaded via these two files:

/etc/php.d/json.ini
/etc/php.d/pdo.ini

Install Apache on Centos Rackspace

Source: http://www.rackspace.com/knowledge_center/index.php/CentOS_-_Apache_and_PHP_install

CentOS - Installing Apache and PHP5

CentOS comes with Apache v.2.2.3 and PHP v.5.1.6 and they are easily installed via the default CentOS Package Manager, yum.

The advantage of using yum (as opposed to installing via source code) is that you will get any security updates (if and when distributed) and dependencies are automatically taken care of.

Apache Install

A basic Apache install is very easy:

sudo yum install httpd mod_ssl

Oddly, the server does not start automatically when you install it so you have to do this by hand:

sudo /etc/init.d/httpd start

The first thing you will see is this error:

Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name,
using 127.0.0.1 for ServerName

As you can see, the address 127.0.0.1 is used as the server name by default. It’s a good idea to set the ServerName for the next time the server is started.

Open the main Apache “config”:

sudo nano /etc/httpd/conf/httpd.conf

Towards the end of the file you’ll find a section that starts with ServerName and gives the example:

#ServerName www.example.com:80

All you need to do is enter your Cloud Server host name or a fully-qualified domain name:

ServerName demo

Note that my Cloud Server host name is “demo”.

Now just reload Apache:

sudo /etc/init.d/httpd reload

And the warning has gone.

Firewall

Notice that in some versions of CentOS, a firewall is installed by default which will block access to port 80, on which Apache runs. The following command will open this port:

sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT

Remember to save your firewall rules after adding that instruction so your web server will be accessible the next time you reboot:

sudo service iptables save

For more information on firewalls and their configuration, it is strongly recommended to read the Firewalls section of our knowledge base.

Default Page

If you navigate to your Cloud Server IP address:

http://123.45.67.890

You will see the default CentOS Apache welcome page.

This means the Apache install is a success.

Chkconfig

Now that we have Apache installed and working properly, we need to make sure that it’s set to start automatically when the Cloud Server is rebooted.

sudo /sbin/chkconfig httpd on

Let’s check our work to confirm:

sudo /sbin/chkconfig --list httpd
httpd           0:off        1:off  2:on    3:on    4:on    5:on    6:off

The setting works.

PHP5 Install

Let’s move on to the PHP5 install. I’m not going to install all the modules available, just a few common ones so you get the idea.

As before, due to using yum to install PHP5, any dependencies are taken care of:

sudo yum install php php-common php-gd php-mcrypt php-pear php-pecl-memcache php-mhash php-mysql php-xml

Once done, reload Apache:

sudo /etc/init.d/httpd reload

Oct 1

Configure jabber gtalk asterisk

#apt-get instal libgnutls-dev

Download, compile and install iksemel - xml parser and jabber protocol library

http://code.google.com/p/iksemel/downloads/list

Do not worry about the warning message, apparently iksemel does not compile with libgnutls2+ because of absence of gnutls-config but that is okay.

Compile and install asterisk after ensuring that jabber, gtalk channels and resources are selected in menuselect.

Configuration

#cat jabber.conf

[general]
debug=yes
autoprune=no
autoregister=yes

[asterisk]
type=client
serverhost=talk.google.com
username=myname@gmail.com/Talk
secret=password
priority=1
port=5222
usetls=yes
usesasl=yes
buddy=username@gmail.com
status=available
statusmessage=”I am a robot! Ha!”
timeout=100

#cat gtalk.conf

[general]
context=default
allowguest=yes

[guest]
disallow=all
allow=ulaw
context=guest

#cat extensions.conf

[gtalk-in]
exten => s,1,Answer()
exten => s,n,Wait(3)
exten => s,n,SendDTMF(1)
exten => s,n,Goto(demo,s,1)

Also See

https://wiki.asterisk.org/wiki/display/AST/Calling+using+Google


Start Process at Linux Boot

How to start a new process at Linux Boot automatically ?

All commands in /etc/rc.d/rc.local are executed AFTER the init scripts, so adding your shell process to this script is a quick method.

The formal alternative is to put appropriate start/stop scripts in /etc/init.d and then make symbolic links in /etc/rc.d/init.d


Reverse SSH tunnel or connecting to computer behind NAT router

Source: http://www.alexonlinux.com/reverse-ssh-tunnel-or-connecting-to-computer-behind-nat-router

Introduction

Few days ago I encountered a problem. How do you connect to a computer behind NAT router? Any NAT router is also a firewall. Sometimes you do have access to firewall configuration and can set up port forwarding. Yet often it is complicated and even impossible. Common situation is when you want to connect to a computer in the office from home. Companies usually hide office computers behind NAT routers and firewalls. Hence you cannot connect to office computer as is.

This is exactly the problem I had to overcome. After googling for couple of minutes I found a solution called reverse SSH tunnel. Yet I could not find a guide that explains how to make it work from A to Z. So I decided to write one.

Understanding the setup

In our basic setup we have a Home Computer. It runs Linux and can freely access the Internet. Office Computer is the Linux machine behind NAT router. We want to connect to Office Computer but can’t because of the NAT router. Server is additional Linux machine. It has to be accessible from both home and office computers via SSH.

Preparations

First, we have to make sure that SSH server on Server has GatewayPorts option turned on. You most likely have openssh SSH server. If so, open /etc/ssh/sshd_config and make sure it has following line.

1GatewayPorts yes

If it’s missing, add it and restart SSH service.

Now this is important. Using method described here you can connect to different ports on Office Computer. However, if you want to connect to it via SSH you have to make sure that GatewayPorts is on on the Office Computer as well.

Also, to connect you need access to the Office Computer. I.e. you either have to ask someone to execute commands on Office Computer for you, or you have to run them yourself in advance.

Connecting

This is the easy part.

Assuming you want to connect to port X on Office Computer, do the following.

On Office Computer do the following:

1ssh -R 6333:localhost:X user_on_server@server

Server will require regular SSH credentials (either certificate or password) and will open regular SSH session for you. This is the tunnel session. Keep it open as long as you want to stay connected to the Office Computer.

On Home Computer connect to port 6333 on Server as if it was port X on Office Computer. In case you want to connect to SSH port on Office Computer, set X to 22 (SSH port) in step 1 and do the following:

1ssh user_on_office_computer@server -p 6333

Again, you may be asked to identify yourself. Do it as you were connecting to Office Computer directly.

Avoiding session expiration

As I mentioned in Preparations section of this guide, you can do step 1 in advance, before going home. Alternatively, you can ask someone to do the command for you. In case you prefer to do it yourself, you may want to make sure that tunnel connection you established won’t expire.

There are three options in /etc/ssh/sshd_config that control SSH session expiration. Once in a while SSH server sends keep-alive messages to connected clients. Temporary connectivity problem can cause it to disconnect certain SSH session, despite this is only a very temporary problem. Depending on the configuration of you SSH server, you may want to prevent these keep-alive messages. On the contrary you may want to increase interval between them or change number of lost keep-alive messages that indicate to SSH server that a connection to a client has been lost.

TCPKeepAlive configuration option enables or disables keep-alive messages. The default is yes (i.e. send keep-alives) and it is a good practice to keep it this way.

ClientAliveInterval specifies number of seconds between every keep-alive message. Depending on quality of connection between Office Computer and the Server we may want to set it to, let’s say 10.

ClientAliveCountMax controls number of lost keep-alive messages that cause SSH server to pull the plug. We want it relatively big, but not too big. With ClientAliveInterval equals 10, its a good idea to loose the connection after keep-alive messages fail for lets say 5 minutes – 300 seconds. This means we can make ClientAliveCountMax equals 30.


SSH without password

Source: http://linuxproblem.org/art_9.html

Your aim

You want to use Linux and OpenSSH to automize your tasks. Therefore you need an automatic login from host A / user a to Host B / user b. You don’t want to enter any passwords, because you want to call ssh from a within a shell script.

How to do it

First log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:

a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa): 
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A

Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):

a@A:~> ssh b@B mkdir -p .ssh
b@B's password: 

Finally append a’s new public key to b@B:.ssh/authorized_keys and enter b’s password one last time:

a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@B's password: 

From now on you can log into B as b from A as a without password:

a@A:~> ssh b@B hostname
B

A note from one of our readers: Depending on your version of SSH you might also have to do the following changes:

  • Put the public key in .ssh/authorized_keys2
  • Change the permissions of .ssh to 700
  • Change the permissions of .ssh/authorized_keys2 to 640

Install Asterisk CentOS

#yum install gcc-c++ make gnutls-devel kernel-devel kernel ncurses-devel

#reboot; if new kernel is installed

# cd /usr/src

#wget http://downloads.asterisk.org/pub/telephony/asterisk/releases/asterisk-1.8.7.0.tar.gz

#tar xvzf asterisk-1.8.7.0.tar.gz

#cd asterisk-1.8.7.0

#./configure —disable-xmldoc

#make menuselect

select cdr mysql in addons if needed

#make all

#make install

#make sample

#make config


PHP cURL Tutorial

Source: http://www.catswhocode.com/blog/10-awesome-things-to-do-with-curl

http://morethanseven.net/2007/01/20/posting-to-twitter-using-php.html

cURL, and its PHP extension libcURL, are tools which can be used to simulate a web browser. In fact, it can for example, submit forms. In this article, I’m going to show you 10 incredible things that you can do using PHP and cURL.

New to cURL? If yes, check out the following articles to learn the purposes and basics of cURL/libcurl.

Please note that some of the techniques shown here can be used for “blackhat” methods. The goal of this article is only educationnal, please do not use any of the snippets below for illegal stuff.

1 – Update your Facebook status

Wanna update your facebook status, but don’t want to go to facebook.com, login, and finally being able to update your status? Simply save the following code on your server, define the variables, and voilà!

<?PHP
/*******************************
*	Facebook Status Updater
*	Christian Flickinger
*	http://nexdot.net/blog
*	April 20, 2007
*******************************/

$status = 'YOUR_STATUS';
$first_name = 'YOUR_FIRST_NAME';
$login_email = 'YOUR_LOGIN_EMAIL';
$login_pass = 'YOUR_PASSWORD';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&amp;next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
$page = curl_exec($ch);

curl_setopt($ch, CURLOPT_POST, 1);
preg_match('/name="post_form_id" value="(.*)" \/>'.ucfirst($first_name).'/', $page, $form_id);
curl_setopt($ch, CURLOPT_POSTFIELDS,'post_form_id='.$form_id[1].'&status='.urlencode($status).'&update=Update');
curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
curl_exec($ch);
?>

Source: http://codesnippets.joyent.com/posts/show/1204

2 – Get download speed of your webserver

Do you ever wanted to know the exact download speed of your webserver (or any other?) If yes, you’ll love that code. You just have to initialize the $url variable with any resources from the webserver (images, pdf, etc), place the file on your server and point your browser to it. The output will be a full report of download speed.

<?php error_reporting(E_ALL | E_STRICT);

// Initialize cURL with given url
$url = 'http://download.bethere.co.uk/images/61859740_3c0c5dbc30_o.jpg';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Sitepoint Examples (thread 581410; http://www.sitepoint.com/forums/showthread.php?t=581410)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);

set_time_limit(65);

$execute = curl_exec($ch);
$info = curl_getinfo($ch);

// Time spent downloading, I think
$time = $info['total_time']
      - $info['namelookup_time']
      - $info['connect_time']
      - $info['pretransfer_time']
      - $info['starttransfer_time']
      - $info['redirect_time'];

// Echo friendly messages
header('Content-Type: text/plain');
printf("Downloaded %d bytes in %0.4f seconds.\n", $info['size_download'], $time);
printf("Which is %0.4f mbps\n", $info['size_download'] * 8 / $time / 1024 / 1024);
printf("CURL said %0.4f mbps\n", $info['speed_download'] * 8 / 1024 / 1024);

echo "\n\ncurl_getinfo() said:\n", str_repeat('-', 31 + strlen($url)), "\n";
foreach ($info as $label => $value)
{
	printf("%-30s %s\n", $label, $value);
}
?>

Source: http://cowburn.info/2008/11/29/download-speed-php-curl

3 – Myspace login using cURL

<?php

function login( $data, $useragent = 'Mozilla 4.01', $proxy = false ) {
    $ch = curl_init();
    $hash = crc32( $data['email'].$data['pass'] );
    $hash = sprintf( "%u", $hash );
    $randnum = $hash.rand( 0, 9999999 );
    if( $proxy ) curl_setopt( $ch, CURLOPT_PROXY, $proxy );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, '/tmp/cookiejar-'.$randnum );
    curl_setopt( $ch, CURLOPT_COOKIEFILE, '/tmp/cookiejar-'.$randnum );
    curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_POST, 0);
    curl_setopt( $ch, CURLOPT_URL, 'http://www.myspace.com' );
    $page = curl_exec( $ch );
    preg_match( '/MyToken=(.+?)"/i', $page, $token );
    if( $token[1] ) {
        curl_setopt( $ch, CURLOPT_URL, 'http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken='.$token[1] );
        curl_setopt( $ch, CURLOPT_REFERER, 'http://www.myspace.com' );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, Array( 'Content-Type: application/x-www-form-urlencoded' ) );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        $postfields = 'NextPage=&email='.urlencode( $data['mail'] ).'&password='.urlencode( $data['pass'] ).'&loginbutton.x=&loginbutton.y=';
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postfields );
        $page = curl_exec( $ch );
        if( strpos( $page, 'SignOut' ) !== false ) {
                return $randnum;
        }
        else {
            preg_match( '/MyToken=(.+?)"/i', $page, $token );
            preg_match( '/replace\("([^\"]+)"/', $page, $redirpage );
            if( $token[1] ) {
                curl_setopt( $ch, CURLOPT_POST, 0 );
                curl_setopt( $ch, CURLOPT_URL, 'http://home.myspace.com/index.cfm?&fuseaction=user&Mytoken='.$token[1] );
                $page = curl_exec( $ch );
                curl_close( $ch );
                if( strpos( $page, 'SignOut' ) !== false ) {
                    return $randnum;
                }
            }
            elseif( $redirpage[1] ) {
                curl_setopt( $ch, CURLOPT_REFERER, 'http://login.myspace.com/index.cfm?fuseaction=login.process&MyToken='.$token[1] );
                curl_setopt( $ch, CURLOPT_URL, $redirpage[1] );
                curl_setopt( $ch, CURLOPT_POST, 0 );
                $page = curl_exec( $ch );
                curl_close( $ch );
                if( strpos( $page, 'SignOut' ) !== false ) {
                    return $randnum;
                }
            }
        }
    }
    return false;
}
?>

Source: http://www.seo-blackhat.com/article/myspace-login-function-php-curl.html

4 – Publish a post on your WordPress blog, using cURL

I know that most of you enjoy WordPress, so here is a nice “hack” as the ones I regulary publish on my other blog WpRecipes.
This function can post on your WordPress blog. You don’t need to login to your WP dashboard etc.
Though, you must activate the XMLRPC posting option in your WordPress blog. If this option isn’t activated, the code will not be able to insert anything into WordPress database. Another thing, make sure the XMLRPC functions are activated on your php.ini file.

function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8')
{
    $title = htmlentities($title,ENT_NOQUOTES,$encoding);
    $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);

    $content = array(
        'title'=>$title,
        'description'=>$body,
        'mt_allow_comments'=>0,  // 1 to allow comments
        'mt_allow_pings'=>0,  // 1 to allow trackbacks
        'post_type'=>'post',
        'mt_keywords'=>$keywords,
        'categories'=>array($category)
    );
    $params = array(0,$username,$password,$content,true);
    $request = xmlrpc_encode_request('metaWeblog.newPost',$params);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_URL, $rpcurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    $results = curl_exec($ch);
    curl_close($ch);
    return $results;
?>

Source: http://porn-sex-viagra-casino-spam.com/coding/poster-automatiquement-sur-wordpress-avec-php/

5 – Test the existence of a given url

I know, it sounds basic. In fact, it is basic, but it is also very useful, especially when you have to work with external resources.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.jellyandcustard.com/");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch)
echo $data;
?>

Source: http://www.phpsnippets.info/test-existence-of-a-given-url-with-curl

6 – Post comments on WordPress blogs

In a previous article, I have discussed how spammers spams your WordPress blog. To do so, they simply have to fill the $postfields array with the info they want to display and load the page.
Of course, this code is only for educationnal purposes.

<?php
$postfields = array();
$postfields["action"] = "submit";
$postfields["author"] = "Spammer";
$postfields["email"] = "spammer@spam.com";
$postfields["url"] = "http://www.iamaspammer.com/";
$postfields["comment"] = "I am a stupid spammer.";
$postfields["comment_post_ID"] = "123";
$postfields["_wp_unfiltered_html_comment"] = "0d870b294b";
//Url of the form submission
$url = "http://www.ablogthatdoesntexist.com/blog/suggerer_site.php?action=meta_pass&id_cat=0";
$useragent = "Mozilla/5.0";
$referer = $url; 

//Initialize CURL session
$ch = curl_init($url);
//CURL options
curl_setopt($ch, CURLOPT_POST, 1);
//We post $postfields data
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
//We define an useragent (Mozilla/5.0)
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
//We define a refferer ($url)
curl_setopt($ch, CURLOPT_REFERER, $referer);
//We get the result page in a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//We exits CURL
$result = curl_exec($ch);
curl_close($ch);

//Finally, we display the result
echo $result;
?>

Source: http://www.catswhocode.com/blog/how-spammers-spams-your-blog-comments

7 – Follow your Adsense earnings with an RSS reader

Most bloggers uses Adsense on their blog and (try to) make money with Google. This excellent snippet allows you to follow your Adsense earnings…with a RSS reader! Definitely awesome.
(Script too big to be displayed on the blog, click here to preview)
Source: http://planetozh.com/blog/my-projects/track-adsense-earnings-in-rss-feed/

8 – Get feed subscribers count in full text

If you’re a blogger, you’re probably using the popular FeedBurner service, which allo you to know how many people grabbed your rss feed. Feedburner have a chicklet to proudly display your subscriber count on your blog. I personally like the chicklet’s look, but I heard lots of bloggers complaining about it. happilly, cURL can simply grab the count value and return it to you as a variable so you can display it as you want on your blog.

//get cool feedburner count
$whaturl="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=feedburner-id";

//Initialize the Curl session
$ch = curl_init();

//Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Set the URL
curl_setopt($ch, CURLOPT_URL, $whaturl);

//Execute the fetch
$data = curl_exec($ch);

//Close the connection
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fb = $xml->feed->entry['circulation'];
//end get cool feedburner count

Source: http://www.hongkiat.com/blog/display-google-feed-subscriber-count-in-text/

9 – Get the content of a webpage into a PHP variable

This is a very basic thing to do with cURL, but with endless possibilities. Once you have a webpage in a PHP variable, you can for example, retrieve a particular information on the page to use on your own website.

<?php
    ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
?>

10 – Post to Twitter using PHP and cURL

Twitter is very popular since some time now, and you probably already have an account there. (We have one too) So, what about using cURL to tweet from your server without connectiong to Twitter?

<?php
// Set username and password
$username = 'username';
$password = 'password';
// The message you want to send
$message = 'is twittering from php using curl';
// The twitter API address
$url = 'http://twitter.com/statuses/update.xml';
// Alternative JSON version
// $url = 'http://twitter.com/statuses/update.json';
// Set up and execute the curl process
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$url");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message");
curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
// check for success or failure
if (empty($buffer)) {
    echo 'message';
} else {
    echo 'success';
}
?>