Red Hat / CentOS Apache 2 FastCGI PHP Configuration

Posted on in Categories Apache, CentOS, Howto, Networking, package management, php, RedHat/Fedora Linux, Security, Tips last updated December 30, 2008

FastCGI is a protocol for interfacing interactive programs with a web server. FastCGI’s main aim is to reduce the overhead associated with interfacing the web server and CGI programs, allowing a server to handle more web page requests at once.

Also, PHP is not recommended with multithreaded Apache2 (worker MPM) because of performance and some 3rd party PHP extensions are not not guaranteed thread-safe.

nginx and lighttpd has inbuilt support for FastCGI. For Apache web server you need to use either mod_fastcgi or mod_fcgid.

mod_fastcgi allows server and application processes to be restarted independently — an important consideration for busy web sites. It also facilitates per-application security policies — important for ISPs and web hosting companies.

In this quick tutorial, you will learn about Apache 2 + mod_fastcgi + PHP installation and configuration under Red Hat Enterprise Linux / CentOS Linux version 5.x+.

Red Hat Open Sourced Identity, Policy, Auditing Management Security Framework Tool

Posted on in Categories Linux, RedHat/Fedora Linux, Security last updated March 20, 2008

Red Hat has open-sourced its identity-management and security system to promote its assertion that open-source software provides the most secure infrastructure. From the press release:

Red Hat Certificate System was acquired from AOL three years ago as part of the Netscape technology acquisition. In keeping with our commitment to open source software, today Red Hat has released all of the source code to Red Hat Certificate System. Much of the technology in Red Hat Certificate System was already open source, including the Apache web server, Red Hat Directory Server and the FIPS140-2 level 2 validated NSS cryptographic libraries, but today’s move further demonstrates Red Hat’s belief that the open source development model creates more secure software.

I think the freeIPA project is really good addition. It provides central management of identity, policy, and auditing for Unix and Linux using open-source and open-standards technologies.

freeIPA under Fedora Linux
(Fig. 01: freeIPA running under Fedora Linux [Image Credit freeIPA project])

Howto Setup Linux Apache Web Server Cluster with Linux Virtual Server and Heartbeat

Posted on in Categories Apache, Business, High performance computing, Howto, Linux, Linux distribution, Suse Linux last updated August 23, 2007

This article explains howto setup and running with the Linux Virtual Server and Linux-HA.org’s Heartbeat in 5 easy steps. You can construct a highly available Apache Web server cluster that spans multiple physical or virtual Linux servers with Linux Virtual Server (LVS) and Heartbeat v2:

Spreading a workload across multiple processors, coupled with various software recovery techniques, provides a highly available environment and enhances overall RAS (Reliability, Availability, and Serviceability) of the environment. Benefits include faster recovery from unplanned outages, as well as minimal effects of planned outages on the end user.

This article illustrates the robust Apache Web server stack with 6 Apache server nodes (though 3 nodes is sufficient for following the steps outlined here) as well as 3 Linux Virtual Server (LVS) directors. We used 6 Apache server nodes to drive higher workload throughputs during testing and thereby simulate larger deployments. The architecture presented here should scale to many more directors and backend Apache servers as your resources permit, but we haven’t tried anything larger ourselves. Figure 1 shows our implementation using the Linux Virtual Server and the linux-ha.org components.

Howto Setup Linux Apache Web Server Cluster with Linux Virtual Server and Heartbeat

However article failed to mention few things such as redundant networking, a cluster file system / shared storage and other stuff. Nevertheless tutorial is a good start for new Linux admin.

=> Set up a Web server cluster in 5 easy steps

Howto migrate from Microsoft Internet Information Server (IIS) to Apache on Linux

Posted on in Categories Apache, RedHat/Fedora Linux, Tips, Windows server last updated January 6, 2007

This is an interesting article.

For people migrating from Windows to Linux, the Apache Web server is entirely different world from Microsoft Internet Information Server. Apache can be alienating to IIS / Windows administrators, because migrating to Apache is more than just copying files.

The IIS to Apache migration process needs to be handled with the same care and perspective as the process of migrating desktops and their attendant applications. In some cases, IIS to Apache may be even more difficult and may have a larger impact on users and administrators.

In this article, author talk about the process of migrating a site from IIS to Apache, with Red Hat Linux as the specific target.

nixCraft FAQ Roundup – Dec 8, 2008

Posted on in Categories FAQ last updated December 8, 2006

Recently updated/posted Linux and UNIX FAQ:

=> Boot Ubuntu Linux into Rescue mode to fix system – How do I boot my Ubuntu Linux server into Rescue mode to fix system?

=> Unable to create installation source – Add directories into YaST as an installation source – I have created my own patch files on the hard drive. How do I add all those directories into Suse Linux YaST as an installation source?

=> How to uninstall GRUB – How do I uninstall GRUB using old good MS-DOS fdisk or Linux/UNIX dd command?

=> Can I run fsck or e2fsck when Linux file system is mounted? Can I run run fsck/e2fsc on a live Linux file system?

=> Configure Sendmail SSL encryption for sending and receiving email – Configure Sendmail MTA to use SSL encryption for sending/receiving email using valid SSL certificate.

=> Linux configure Network Address Translation or NAT – Old good Linux NAT!

=> Use sudo or sudoers to start, stop & restart Apache – Sudo to stop and/or restart Apache web server!

=> How to install firefox-2.0.tar.gz in Linux – I have downloaded firefox file from mozilla web site to my Linux desktop system. The name of file is firefox-2.0.tar.gz. How do I install firefox-2.0.tar.gz in Fedora Core Linux?

Enjoy!

PHP Send Email Using Authenticated SMTP Mail Server In Real Time

Posted on in Categories Apache, Howto, lighttpd, Mail server, php, Postfix, Security, Troubleshooting last updated November 30, 2006

PHP has mail() function to send an email to users. However this mail() will not work:

=> If sendmail (or compatible binary) is not installed

=> If Apache Web server / Lighttpd running in chrooted jail

=> And your smtp server needs an authentication before sending an email

=> Or you just need to send email using PHP PEAR

In all these cases you need to use PHP PEAR’s Mail:: interface. It defines the interface for implementing mailers under the PEAR hierarchy, and provides supporting functions which are useful in multiple mailer backends. In this tip you will learn about how to send an e-mail directly to client smtp server in real time.

PHP Pear’s Mail.php is located in /usr/share/pear/ directory. Following is sample code to send an email via authenticated smtp server.

PHP send email using PHP SMTP mail Pear functions – Sample source code

Following code is well commented, you need to make necessary changes as per your setup.

<?php
include("Mail.php");
/* mail setup recipients, subject etc */
$recipients = "[email protected]";
$headers["From"] = "[email protected]";
$headers["To"] = "[email protected]";
$headers["Subject"] = "User feedback";
$mailmsg = "Hello, This is a test.";
/* SMTP server name, port, user/passwd */
$smtpinfo["host"] = "smtp.mycorp.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtpusername";
$smtpinfo["password"] = "smtpPassword";
/* Create the mail object using the Mail::factory method */
$mail_object =& Mail::factory("smtp", $smtpinfo);
/* Ok send mail */
$mail_object->send($recipients, $headers, $mailmsg);
?>

Sending smtp email from chrooted Apache or Lighttpd webserver

Read following section, if you are running a secure chrooted Apache or Lighttpd web server. I have already written about setting php mail() function in chrooted jail. If you are using chrooted jail server setup, copy all files from /usr/share/pear directory to /chroot-directory/usr/share/pear directory. For example if lighttpd chrooted jail located in /webroot directory, you need to type following commands to install PHP pear support:
# mkdir -p /webroot/usr/share/pear
# cd /webroot/usr/share/pear
# cp -avr /usr/share/pear .

If PHP SAFE MODE is on, you must set /webroot/usr/share/pear directory permission to webserver username to allow access. Otherwise you will see error as follows:

1-Nov-2006 09:43:19] PHP Warning:  main(): SAFE MODE Restriction in effect.  The script whose uid is 506 is not allowed to access /usr/share/pear/PEAR.php owned by uid 0 in /usr/share/pear/Mail.php on line 636.

So if webserver username is lighttpd or apache use following command to setup correct ownership:
# chown lighttpd:lighttpd /webroot/usr/share/pear -ROR# chown apache:apache /webroot/usr/share/pear -R

You may also find modified wordpress WP-ContactForm plugin useful. It is a drop in form for users to contact you. It can be implemented on a page or a post. Original authored by Ryan Duff, which use php mail() function to send email. I have modified the same to send email via my ISP authenticated gateway using PHP PEAR’s Mail:: interface 😀

Change Linux or UNIX system password using PHP script

Posted on in Categories Apache, lighttpd, php, Shell scripting last updated August 3, 2006

If you just wanted to change your own password or other user passwords use passwd command.

I was asked to setup a PHP based interface to change the password. Since my knowledge of php is limited. Here is what I did:

Warning: This is an outdated and insecure information. Please see the official php.net document for more information. You have been warned to ignore this post.

Required tools/setup:

You must have following tools/software installed

=> Shell script to change password

=> Sudo access

=> Apache or Lighttpd web server

=> PHP server side

Step # 1: Setup a shell script to change password

This shell script use expect tool to change the password (see more about expect tool here).

Sample shell script code

#!/bin/sh
# \
exec expect -f "$0" ${1+"[email protected]"}
set password [lindex $argv 1]
spawn passwd [lindex $argv 0]
sleep 1
expect "assword:"
send "$password\r"
expect "assword:"
send "$password\r"
expect eof

You can execute this script as follows (dowload link):
$ chpasswd username password

Download script and copy to your webroot or location where webserver can read this script file:
$ cp chpasswd /var/www/

ALTERNATIVELY, if you are using Ligtttpd web server:
$ cp chpasswd /home/lighttpd

Step # 2: Setup sudo to execute a command as root user

Apache or Lighttpd web server drops root privileges as soon as they go into background. This makes changing password scenario difficult as passwd command needs root privileges to change other user account password.

Typically, Apache 2 use www-data user and Lighttpd use lighttppd username to drop privileges. Login as root user and type the following command:
# visudo

Now allow your web server to execute a script (chpasswd) w/o password. If you are using Apache web server, type the following command:
www-data ALL=NOPASSWD: /var/www/chpasswd

ALTERNATIVELY, if you are using Ligtttpd web server, type the following command:
lighttpd ALL=NOPASSWD: /home/lighttpd/chpasswd

Save and close the file.

Step # 3: Create a PHP based interface

Now you need to write a php script. Here is sample php script. This is a demo script. You should modify it according to your requirement or setup. At minimum, you need to setup correct shell script location so that it will work for you out of box. Open php script and locate line:
$shellscript = "sudo /home/lighttpd/chpasswd";

Change it to point to correct location. PHP Source code:

<?php
// change .. me! - shell script name
$shellscript = "sudo /home/lighttpd/chpasswd";
 
// Make sure form is submitted by user
if(!(isset($_POST['pwdchange']))) {
 // if not display them form
 writeHead("Change password");
 writeForm();
 writeFoot();
}
else {
 // try to change the password
 $callshell=true;
 // get username and password
 $_POST['username'] = stripslashes(trim($_POST['username']));
 $_POST['passwd'] = stripslashes(trim($_POST['passwd']));
 
// if user skip our javascript ...
// make sure we can only change password if we have both username and password
 if(empty($_POST['username'])) {
   $callshell=false;
 }
 if(empty($_POST['passwd'])) {
   $callshell=false;
 }
 if ( $callshell == true ) {
  // command to change password
  $cmd="$shellscript " . $_POST['username'] . " " . $_POST['passwd'];
  // call command
  // $cmd - command, $output - output of $cmd, $status - useful to find if command failed or not
   exec($cmd,$output,$status);
   if ( $status == 0 ) { // Success - password changed
   writeHead("Password changed");
   echo '<h3>Password changed</h3>Setup a new password';
   writeFoot();
   }
   else { // Password failed
      writeHead("Password change failed");
      echo '<h3>Password change failed</h3>';
      echo '<p>System returned following information:</p>';
      print_r($output);
      echo '<p><em>Please contact tech-support for more info! Or try <a href='.$_SERVER['PHP_SELF'].'again</a></em></p>';
      writeFoot();
   }
 }
 else {
   writeHead("Something was wrong -- Please try again");
   echo 'Error - Please enter username and password';
   writeForm();
   writeFoot();
 }
}
 
// display html head
function writeHead($title) {
echo '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> ' .$title. '</title>
<style type="text/css" media="screen">
.passwdform {
	position: static;
	overflow: hidden;
}
 
.passwdleft {
	width: 25%;
	text-align: right;
	clear: both;
	float: left;
	display: inline;
	padding: 4px;
	margin: 5px 0;
}
 
.passwdright {
	width: 70%;
	text-align: left;
	float: right;
	display: inline;
	padding: 4px;
	margin: 5px 0;
}
 
.passwderror {
	border: 1px solid #ff0000;
}
 
.passwdsubmit {
}
</style>
 
</head>
 
<body>';
 
}
// display html form
function writeForm() {
echo '
<h3>Use following form to change password:</h3>
 
<script>
function checkForm() {
if (document.forms.changepassword.elements[\'username\'].value.length == 0) {
    alert(\'Please enter a value for the "User name" field\');
    return false;
}
if (document.forms.changepassword.elements[\'passwd\'].value.length == 0) {
    alert(\'Please enter a value for the "Password" field\');
    return false;
}
  return true;
}
</script>
 
<div class="contactform">
<form action="' . $_SERVER[PHP_SELF]. '" method="post" onSubmit="return checkForm()" name="changepassword">
<div class="passwdleft"><label for="lblusername">User Name: </label></div>
<div class="passwdright"><input type="text" name="username" id="lblusername" size="30" maxlength="50" value="" /> (required)</div>
<div class="passwdleft"><label for="lblpasswd">Password: </label></div>
<div class="passwdright"><input type="password" name="passwd" id="lblpasswd" size="30" maxlength="50" value="" /> (required)</div>
<div class="passwdright"><input type="submit" name="Submit" value="Change password" id="passwdsubmit" />
<input type="hidden" name="pwdchange" value="process" /></div>
</form>
</div>
';
 
}
// display footer
function writeFoot(){
echo '</body>
</html>
';
}
?>

Step # 4: Run the script

Point a web browser to your server url – https://mydomain.com/changepassword.php. You should see a username and password form as follows:

changepassword php script output # 1

If a password is changed successfully, you should get confirmation as follows:

changepassword php script output # 2

For some reason if a password failed to change, you should get detailed error message as follows:

changepassword php script output # 3

Step # 5: Security

Note this is an example and not final solution as it is little insecure.

  • Never ever run this script over http session. Always run over https session.
  • Put script in a password protected directory (see how to setup Apache or Lighttpd web server password protected directory).
  • Never ever, trust user input. Above php script is just a sample, for real life production you should consider more powerful user input validation. Discussion regarding PHP programming security is beyond the scope of this article. You can consult a good PHP book or search a web using your favorite search engine 🙂