Monday, June 22, 2009

Check perl syntax from command line

When we run your PERL scripts in browser, we may get “500 Internal Server Error” when something goes wrong.
There would be many reasons for this but Out of many check one thing which we can do very quickly is to check if your PERL script contains errors.

To do it login to server where PERL script running and execute command:
To check syntax
/path/to/perl -wc /path/to/script.cgi

To runtime script
/path/to/perl -w /path/to/script.cgi

Friday, April 3, 2009

Web Application Security

Web application layers
  1. Data :Original data: Text, images, files
  2. Database : Access, SQL Server, MySQL, ORACLE
  3. Code : Perl, php, servelet, jsp, asp
  4. Webserver : Apache, IIS, Websphere, Weblogic, Netscape Enterprise
  5. User interface Code : Html, Forms, Javascript, Coldfusion
  6. Browser
  7. Input
Any layer is potentially open to attack!

Top 10 Reason :
  • – Unvalidated input
  • – Broken access control
  • – Broken authentication and session management
  • – Cross site scripting
  • – Buffer overflows
  • – Injection flaws
  • – Improper error handling
  • – Insecure storage
  • – Denial of service
  • – Insecure configuration management
Unvalidated input:
– Never trust input from a user
– Malicious user can tamper with anything and try to:
  • Cause errors to occur and give up info
  • Buffer overflow
  • Modify parameters
– Common attacks:
  • Modifying URL
  • SQL Injection
  • Cross Site Scripting
  • Session hijacking with cookie modification
Broken access control
Types of attacks:
– Insecure ID (guess IDs)
– Forced browsing past access control checks
  • “/client” is checked for access control
  • “/client/client1/data” is not
  • If someone guesses the full URL….
– Path traversal (../../../)
– File permissions (OS permission + web server permission)
– Client side caching

Authentication and Session Management
– Two main issues, credential management and session hijacking
– Flawed credential management functions:
  • Password changes (expiry, etc)
  • Forgot my password
– All account management functions should require authentication first

Web applications need to keep track of users
HTTP does not offer session management
Web application must take care of this by session IDs stored in either:
  • – Cookies
  • – Embedded in the URL
  • – Embedded in dynamic web page
Authentication and Session Management: “Session Hijacking”
How is your session ID being generated?
– Time based?
– Sequential?
How do you protect it?
– Integrity with hash?
– Encryption?
– Encode it with easily reversible scheme?
– Timeouts for length of session ID?

Buffer overflows
– Corrupt execution stack of web application
– Cause application to execute arbitrary code
– Very common problem
– Keep your apps and OS patched!

Improper error handling
– Debug messages that can help attacker gain information that can be leveraged into a compromise
– Turn your debug off!
– Personalize error messages to ensure no information is given

Insecure configuration management
– 90%* of breakins can be stopped by properly configuring your web server!
– Don’t do default installations!

Insecure configuration management: Default directories
Dot dot sequence (../../) directory traversal:
– /../../winnt/system32/cmd.exe?/c dir +
Unicode directory traversal
– /..%5c..%5cwinnt/system32/cmd.exe?/c dir +
– /cgi-bin/..%c1%1c..%c1%1c../winnt/system32/cmd.exe?/c +dir
Unicode %5c..%5c=\..\
Unicode %c1%c1..%c1%c1=\..\


How to stop Web application attacks
  • – Error message customization
  • – Restricted access to sensitive information
  • – Patch Web servers
  • – Remove the sensitive page from Google
  • – Regularly perform application test
  • – Deploy a web application firewall
  • – Deploy IPS that will analyze application level

Thursday, April 2, 2009

xgettext options and examples

SYNOPSIS
    xgettext - extract gettext strings from source
     xgettext [OPTION] [INPUTFILE]
DESCRIPTION
• Extract translatable strings from given input files.
• Mandatory arguments to long options are mandatory for short options too. Similarly for optional arguments.
Input files location:
INPUTFILE ...
input files
• -f, --files-from=FILE
    get list of input files from FILE
• -D, --directory=DIRECTORY
    add DIRECTORY to list for input files search
If input file is -, standard input is read.
Output files location:
• -d, --default-domain=NAME
    use NAME.po for output (instead of messages.po)
• -o, --output=FILE
    write output to specified file
• -p, --output-dir=DIR
    output files will be placed in directory DIR
If output file is -, output is written to standard output.
Choice of input file language:
• -L, --language=NAME
    recognise the specified language (C, C++, ObjectiveC, PO, Shell, Python, Lisp, EmacsLisp, librep, Scheme, Smalltalk, Java, JavaProperties, C#, awk, YCP, Tcl, Perl, PHP, GCC-source, NXStringTable, RST, Glade)
• -C, --c++ shorthand for --language=C++
By default the language is guessed depending on the input file name extension.
Input file interpretation:
• --from-code=NAME
    encoding of input files (except for Python, Tcl, Glade)
By default the input files are assumed to be in ASCII.
Operation mode:
• -j, --join-existing
    join messages with existing file
• -x, --exclude-file=FILE.po
    entries from FILE.po are not extracted
• -c, --add-comments[=TAG]
    place comment block with TAG (or those preceding keyword lines) in output file
Language specific options:
• -a, --extract-all
    extract all strings (only languages C, C++, ObjectiveC, Shell, Python, Lisp, EmacsLisp, librep, Scheme, Java, C#, awk, Tcl, Perl, PHP, GCC-source, Glade)
• -k, --keyword[=WORD]
    additional keyword to be looked for (without WORD means not to use default keywords)
(only languages C, C++, ObjectiveC, Shell, Python, Lisp, EmacsLisp, librep, Scheme, Java, C#, awk, Tcl, Perl, PHP, GCC-source, Glade)
• --flag=WORD:ARG:FLAG
    additional flag for strings inside the argument number ARG of keyword WORD
(only languages C, C++, ObjectiveC, Shell, Python, Lisp, EmacsLisp, librep, Scheme, Java, C#, awk, YCP, Tcl, Perl, PHP, GCC-source)
• -T, --trigraphs
    understand ANSI C trigraphs for input (only languages C, C++, ObjectiveC)
• --qt recognize Qt format strings (only language C++)
• --kde recognize KDE 4 format strings (only language C++)
• --boost recognize Boost format strings (only language C++)
• --debug more detailed formatstring recognition result
Output details:
• -e, --no-escape
    do not use C escapes in output (default)
• -E, --escape
    use C escapes in output, no extended chars
• --force-po
    write PO file even if empty
• -i, --indent
    write the .po file using indented style
• --no-location
    do not write ’#: filename:line’ lines
• -n, --add-location
    generate ’#: filename:line’ lines (default)
• --strict
    write out strict Uniforum conforming .po file
• --properties-output
    write out a Java .properties file
• --stringtable-output
    write out a NeXTstep/GNUstep .strings file
• -w, --width=NUMBER
    set output page width
• --no-wrap do not break long message lines, longer than the output page width, into several lines
• -s, --sort-output
    generate sorted output
• -F, --sort-by-file
    sort output by file location
• --omit-header
    don’t write header with ‘msgid ""’ entry
• --copyright-holder=STRING
    set copyright holder in output
• --foreign-user
    omit FSF copyright in output for foreign user
• --package-name=PACKAGE
    set package name in output
• --package-version=VERSION
    set package version in output
• --msgid-bugs-address=EMAIL@ADDRESS
    set report address for msgid bugs
• -m, --msgstr-prefix[=STRING]
    use STRING or "" as prefix for msgstr entries
• -M, --msgstr-suffix[=STRING]
    use STRING or "" as suffix for msgstr entries
Informative output:
• -h, --help display this help and exit
• -V, --version
output version information and exit
Examples:
• xgettext -o myapp.po -p ./locale --force-po --from-code=UTF-8 --keyword --keyword=__ --keyword=gettext -L PHP *.php
• xgettext –a abc.php // specific file
• xgettext –a *.php // All file


refrence: http://www.gsp.com/cgi-bin/man.cgi?section=1&topic=xgettext

Internationalization PHP web sites using Smarty and gettext

What do we need?
  1. Gettext extention enabled in your PHP installation.
  2. Smarty gettext plugin, you can download it from sourceforge: http://sourceforge.net/projects/smarty-gettext/
Step I: Prepare your templates.
This is really easy step you jest need to put text you want to translate between {t}{/t},
example:
{t}translate this{/t}
OR
{t 1=$customers 2=$orders}There are %1 customers waiting for %2 orders.{/t}


The {t} block should be registered in the smarty. So the following code should be added while creating new smarty class.

require('Smarty.class.php');
require('smarty-gettext.php');

$this -> Smarty();
$this->register_block('t', 'smarty_translate');

smarty_translate is the method in the smarty gettext plugin which handles the translation.

Step II: Prepare input files for gettext
To do this you will need a tsmarty2c.php file from Smarty gettex plugin, and use it in console, here is an example:
php tsmarty2c.php PATH_TO_YOUR_TEMPLATE_DIR/template.tpl > template.c

php.exe is present in the installation path of PHP(C:\wamp\bin\php\php5.2.9) and it is a CLI(Command line interpreter) file. It will parse the tsmarty2c.php and generate the C file in the specified path.

Repeat this step for every file,
Step III: Prepare a .po file
To create a .po file you will need to use xgettext utility, for every .c file you created in the step II. Here is an example how to use it:
$ xgettext -o dictionary.po --join-existing --omit-header --no-location template.c

This file has two parts: header, and dictionary part, which you will need to edit.
msgid "translate this"
msgstr "here goes your translation"

Step IV: Convert .po file to .mo using msgfmt utility.

After translating everything, you will need to create the .mo file, here is example
$ msgfmt -o dictionary.mo dictionary.po

Step V: Prepare directory structure.
Gettext library has requires that files are stored in appropriate directory structure, here is an example:
/locale
/pl_PL
/LC_MESSAGES
smartybook.po
smartybook.mo

Step VI: Finale!
The final step is to tell your application to use translation that you have prepared. Below is an example of the PHP code you can use:
$language_code = 'pl_PL';
putenv("LANG=$language_code");
setlocale(LC_ALL, $language_code);
$domain = 'dictionary';
bindtextdomain($domain, './locale');
bind_textdomain_codeset( $domain, 'UTF-8');
textdomain($domain);

Need to set proper path to 'local' directory, used by a bindtextdomain function

Internationalization, Localization & Globalization

Internationalization (i18n)

Internationalization is the process of planning, designing and implementing a “culturally and technically” neutral product, which can easily be localized for various cultures.
Internationalization needs to be addressed in the earliest product planning stages.


i18n stands for the word “Internationalization” The number 18, represents the number of letters found between the “i” and the “n” in the word “Internationalization”.


Localization (l10n)
Localization involves taking a product and making it linguistically and culturally appropriate to the target locale (country/region and language) where it will be used and sold.

It is the adaptation of a system for a particular locale.

This includes localizing
  • Measurements (inches to centimeters),
  • Degrees (Fahrenheit to Celsius),
  • Currencies (US dollar to Indian Rupees),
  • Date formats (mm/dd/yyyy to dd/mm/yyyy),
  • Regional spelling (color to colour),
  • Number format (comma or period to separate thousands)
and other culturally dependent information.

Globalization (g11n)
Globalization addresses the business issues associated with taking a product global.
In the globalization of high-tech products this involves integrating localization throughout a company, after proper internationalization and product design, as well as marketing, sales, and support in the world market.

Globalization in the broadest sense encompasses both internationalization and localization, as well as putting into place the requisite materials, financial, and personnel resources in a global market to support your product or service on a local level.

so, g11n = i18n + l10n, :)

Reference :
http://teck.in/internationalization-localization.html

Wednesday, March 25, 2009

What is Smarty? Why Smarty? How to use Smarty?

About Smarty [What is, Why/How to Use Smarty]

It’s not a new name when we talk about LAMP. Not even like, I am the first going to write any thing about this.

It’s just for my Quick reference (As many time I collected some good information from the net and later that is not available for so many reason... :) )

Smarty is a PHP template available open source. Easy to use, have good documentation and plug-in available and even allow to write custom fuctions

What is a template and what’s the use to have that?

Templates are used to separate the application logic from presentation logic. Programmer handles the application side and presentation side will be maintained by designer.

So templates try to present the code in such a way so that designer can easily understand or don’t have to go through all the details of coding.

Available PHP templates are:-

  • Smarty PHP template,
  • PEAR::HTML_Template_Flexy PHP template,
  • 4/2/2009 class="MsoNormal" style="">PEAR::HTML_Template_IT PHP template,
  • PEAR::HTML_Template_PHPLIB PHP template,
  • PEAR::HTML_Template_Sigma PHP template,
  • PEAR::HTML_Template_Xipe PHP template,
  • patTemplate PHP template.

Why use Smarty template?

In Smarty’s word:

  • Designers can't break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.
  • Errors in the templates are confined to the Smarty’s error handling routines, making them as simple and intuitive as possible for the designer.
  • With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.
  • Programmers aren't messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.
  • Templates are a close representation of what the final output will be, which an intuitive approach is. Designers don't care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.
  • You are not opening your server to the execution of arbitrary PHP code. Smarty has many security features built in so designers won't breach security, whether intentional or accidental. They can only do what they are confined to in the templates.

Smarty uses {$title} instead of <? echo $title; ?>.

{$title} is less extraneous than <? echo $title; ?>, so it was pretty evident that a simpler syntax helps to make templates easier to read and maintain.

Installation of smarty template

  1. Download smarty. You will get “libs” folder. Libs folder will have : -
    1. internals, plugin, configFile.class.php, debug.tpl, smarty.class.php and smarty_compile.class.php.
  2. Now create four dirs:- (under a folder like /smarty/)
    1. Smarty/templates/
    2. Smarty/template_c/
    3. Smarty/cache/
    4. Smarty/configs/

Note : template_c will have your all compiled template.

  1. Now you will store all your templates in /templates/ folder.
  2. Your config file will be placed at /configs/ folder.
  3. Smarty will store cache file at /cache/ folder, if you have enabled cache. You will enable cache through setting.

Note : Give /template_c and /cache proper permission for writing.

Now start coding with Smarty Template

Your first smarty page: - index.php [PHP file]

// Full path to smarty class-

require ‘your_Smarty_path/Smarty.class.php’;

$smarty = new Smarty();

// Configurations

$smarty->template_dir = ‘your_smarty_path /templates’;

$smarty->compile_dir = ‘your_smarty_path /templates_c’;

$smarty->cache_dir = ‘your_smarty_path /cache’;

$smarty->config_dir = ‘your_smarty_path /configs’;

# now assign variables (defined in template)

$smarty->assign(‘name’, ‘Smarty Enabled File’);

$smarty->display(‘index.tpl’); // template file of index.php

Now index.tpl [Smarty File]

<html>

<head>

<title> My First Smarty File

</head>

<body>

{$name}

</body>

</html>

This is the simplest example of smarty template.

Smarty config file: Smarty config file can have, configuration directives for whole site with some control statement for controlling the config directive usability also. Through this you can tell which variable in config file will be printed or not. The variable can be maintained for section wise also.

Mention config file in template-

{config_load file = ‘config.conf’} at top of the template page.

Use variables of config file like this in template:-

<title> {#pageTitle#}

See two ‘#’ sign before and after variable.

In smarty config file, variable will be declared like this:-

#global variable

pageTitle = 'testing'

You can use double quotes or avoid it in config file. In general use double quotes for string.

Smarty config file can have sections

# student section

[student]

myVars = '…';

# hidden section. Database section.

[.database]

databaseName = 'IGNOU';

databaseUser = 'smarty';

Sample config file

# this is comment

# global vars

pageTitle = 'Testing'

bodyBgColor = 'gray'

[student]

pageTitle = 'Student Info Page'

bodyBgColor = 'orchid'

Use of template variables

{config_load file='config.conf' section='student'}

or

{config_load file='config.conf'}

First will give preference to student section variables in config file. So, when variables in template file do not found in student section then it will look in global variable section.

Documentation for using smarty template

You will find full document of smarty template uses at

Smarty Document

More Smarty Example:

{strip} {/strip} is used in template for stripping whitespace from source.

One dimension array loop in smarty

For Loop

In PHP file:

$arrValue = array('bob','jim','joe','jerry','fred');

$smarty->assign('student', $arrValue);

In Smarty template (tpl) file:

{section name=mysec loop=$student}

{$student[mysec]}

{/section}

Looping Associative array in smarty

In PHP file:

// assign an associative array of data

$arrValue = array(

array('student' => 'bob', 'phone' => '555-3425'),

array('student' => 'jim', 'phone' => '555-4364'),

array('student' => 'joe', 'phone' => '555-3422'),

array('student' => 'jerry', 'phone' => '555-4973'),

array('student' => 'fred', 'phone' => '555-3235')

);

$smarty->assign('student ', $arrValue);

In Smarty Template (tpl) file:

Loop in associative array:

{section name=mysec2 loop=$student }

{strip}

{$users[mysec2].student} : {$users[mysec2].phone}

{/strip}

{/section}

Using PHP code in template (tpl) file:

For running php codes directly in template page, use {php} {/php}.

{php}

echo 'Hello World';

{/php}

Variable modifiers example: capitalize, escape and display date.

In tpl file This will capitalize name variable value:

{$name | capitalize}

Date: {$smarty.nowdate_format:"%d-%m-%Y"}

Include file in template file:

{include file="footer.tpl" title="Header below body"}

Smarty predefined variable

We can use PHP predefined variable in smart template (tpl) file:

Script Name: {$smarty.server.SCRIPT_NAME}

PATH: {$smarty.env.PATH}

PHP_VERSION: {$smarty.const.PHP_VERSION}

Smarty "Capture" Function:

{capture name=banner assign=testAssign}

Hello Testing

{/capture}

Now checking for banner is assigned or not!

{if $smarty.capture.banner ne ''}

{/if}

I have also used assign=testAssign, So I can use this also-

{$testAssign}

Smarty support Custom Function. How to write Custom Function…

Reference :
http://waxjelly.wordpress.com/2007/03/14/how-to-write-a-custom-smarty-function-in-php
http://www.smarty.net

Tuesday, March 24, 2009

How to install MySQL on Windows

Option 1: Use All-in-One distributions packages

There are some distributions packages available that contain Apache, PHP, MySQL and other applications in a single installation file, e.g. XAMPP, WampServer etc.

These packages are good for beginner as well as for Quick setup.

If need custom/ advance configuration use manually installing MySQL, it will help you learn more about the system and give you more control.

Option 2: Manual Installation

Manual Installation

Step 1: Download MySQL

Download MySQL from dev.mysql.com/downloads/. download the “Without installer” version.

Step 2: Extract the files

Extract the ZIP to your C: drive and rename the folder from “mysql-x.x.xx-win32″ to “mysql”.

MySQL can be installed anywhere on your system. If you want a lightweight installation, you can remove every sub-folder except for bin, data, scripts and share.

Step 3: Move the data folder (optional)

I recommend placing the data folder on another drive or partition to make backups and re-installation easier. For the purposes of this example, we will create a folder called D:\MySQLdata and move the contents of C:\mysql\data into it.

You should now have two folders, D:\MySQLdata\mysql and D:\MySQLdata\test. The original C:\mysql\data folder can be removed.

Step 4: Create a configuration file

MySQL provides several configuration methods but, in general, it is easiest to to create a my.ini file in the mysql folder. There are hundreds of options to tweak MySQL to your exact requirements, but the simplest my.ini file is:

[mysqld]

# installation directory

basedir="C:/mysql/"

# data directory

datadir="D:/MySQLdata/"

Step 5: Test your installation

The MySQL server is started by running C:\mysql\bin\mysqld.exe. Open a command box (Start > Run > cmd) and enter the following commands:

cd \mysql\bin

mysqld

This will start the MySQL server which listens for requests on localhost port 3306. You can now start the MySQL command line tool and connect to the database.

Open another command box and enter:

cd \mysql\bin

mysql -u root

This will show a welcome message and the mysql> prompt. Enter “show databases;” to view a list of the pre-defined databases.

Step 6: change the root password

The MySQL root user is an all-powerful account that can create and destroy databases. If you are on a shared network, it is advisable to change the default (blank) password. From the mysql> prompt, enter:

UPDATE mysql.user SET password=PASSWORD("my-new-password") WHERE User='root';

FLUSH PRIVILEGES;

You will be prompted for the password the next time you start the MySQL command line.

Enter “exit” at the mysql> prompt to stop the command line client. You should now shut down MySQL with the following command:

mysqladmin.exe -u root shutdown

Step 7: Install MySQL as a Windows service

From a command prompt, enter:

cd \mysql\bin

mysqld --install

Open the Control Panel, Administrative Tools, and then Services and double-click MySQL.

Set the Startup type to “Automatic” to ensure MySQL starts every time you boot your PC.

Alternatively, set the Startup type to “Manual” and launch MySQL whenever you choose using the command “net start mysql”.

The Windows service can be removed using:

cd \mysql\bin

mysqld --remove