Posts Tagged ‘scripts’

NTLM Authentication

Tuesday, March 24th, 2009

Introduction:

This BOK details how to get a Java-based web-application to negotiate with a IE web client for username and domain information. This is a common requirement for web-based applications especially ones that do not want to bore users with a login page. IE will negotiate a user’s password hashes with the webserver, which checks their authenticity against a windows domain controller. If valid, the user’s username and domain will be accessible to the webserver servlets.

NTLM Authentication and how we achieve it:

 
The method HttpServletRequest.getRemoteUser() should return the username of the person using the browser which fired a request to this Servlet.
This method, however works correctly only if the user has been authenticated first by a webserver authentication scheme -
which could be BASIC,DIGEST or CLIENT-CERT. This is the kind of setup the the Apache webserver provides, giving a challenge-response, username-password method of authentication.

What we do here is use a Servlet filter provided as part of the open-source jCIFS package, to get an IE user's username and domain. 

This filter will take the trouble of intercepting user requests, asking IE for the user's password hashes,validating them against a windows domain controller and enabling HttpServletRequest.getRemoteUser() to return the windows user id.
 
Please note this method will not work for non-IE clients, simply because this is a proprietary extension by Microsoft. 
 
For other browsers you will have to rely on BASIC or certificate-based authentication.

How to setup your web application:

 First, we need to download a jcifs jar from http://jcifs.samba.org. I have tested this with jcifs version 0.7.14.jCIFS is from the makers of Samba and provides APIs to access Windows shares, networks and the ability to authenticate against a Windows domain controller. Place this jar under WEB-INF/lib of your web application. There is a filter called jcifs.http.NtlmHttpFilter which implements all the wizadry above. You need to register it in your application's web.xml descriptor:
 
<web-app>
...
    <!-- NTLM HTTP Authentication only works with MSIE -->
    
    <filter>
        <filter-name>NTLM HTTP Authentication Filter</filter-name>
        <filter-class>jcifs.http.NtlmHttpFilter</filter-class>

        <!-- CCD will help you with a PDC and WINS server ip at your location. -->
        <init-param>
            <param-name>jcifs.http.domainController</param-name>
            <param-value>192.168.170.5</param-value>
        </init-param>

        <init-param>
            <param-name>jcifs.netbios.wins</param-name>
            <param-value>192.168.166.13</param-value>
        </init-param>
    </filter>

    <!-- This is the url under which we need access to the username and domain. -->

    <filter-mapping>
        <filter-name>NTLM HTTP Authentication Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

...

</web-app>
 
That's it. Now all IE requests to your webserver urls as specified in the web.xml entries are negotiated so that you can call a HttpServletRequest.getRemoteUser() to get the remote user's username in the form.

            DOMAIN\username.

Please note at no point will a password dialog pop up for the user, the password hashes are picked from IE and validated with the domain controller.
 
 
Example code for a servlet :
 
 
public void doGet( HttpServletRequest req,
                        HttpServletResponse resp )
throws IOException, ServletException
        
        {

PrintWriter out = resp.getWriter();

resp.setContentType( “text/html” );
out.println( “<HTML><HEAD><TITLE>NTLM HTTP Authentication Example</TITLE></HEAD><BODY>” );
out.println( “<h2>NTLM HTTP Authentication Example</h2>” );

out.println( req.getRemoteUser() + ” logged in” );

 

}

If the filter has not been configured properly, a null will be printed for the above call to req.getRemoteUser().

 

References:

  • Web Link :- http://jcifs.samba.org.

PERL Script -A word search program

Monday, March 23rd, 2009

# This script is used to count the number of occurrence of a given search word in the files provided in the command line.

 

# The user has to provide the file names as parameters in the command line.

 

 

#!/usr/local/bin/perl

# Declaring the variables

my $wordToSearch;

my $fileCount=0;

my @wordCount;

my $totalWordCount=0;

 

# Declaring the variables for sending mail

my $fromaddress = “sreejith_ar\@infosys.com”;

my $toaddress = “to_dave\@infosys.com”;

my $subject = “Give some subject”;

my $mailer = “/usr/lib/sendmail -f$fromaddress -oi”;

 

#Prompting the user to enter the word to search and storing it in variable.

print(”Enter the word to be searched:”);

$wordToSearch=<STDIN>;

 

 

#Choping the input to get rid of the new line character at the end

chop ($wordToSearch);

 

#Starting the loop which will continue till the files given in the command line is exhausted.

while ($fileCount < @ARGV)

{

          $wordCount[$fileCount]= 0;

          #Tries to open the file one by one. If the file cannot be opened then the program will print an error message

          unless (open (INFILE, $ARGV[$fileCount]))

          {

                   die (”Cannot open the input file $ARGV[$fileCount]\n”);

        }

          #If the program reached untill here that means the file was available to open.

          #The loop continues untill the end of file is reached.

          while ($line = <INFILE>)

          {       

                   my $count=0;

                   #Chop the line for removing the new line character.

                   chop($line);

                   #Split the line based on space and stores it in the array @array

                   my @array = split(/ /,$line);

 

                   #The loop continues until it reaches the end of the array

                   while($count < @array)

                   {

                             #Checks the array one by one to find whether the elements matches with the search words.

                             #If matches then increments the word count.

                             if ($array[$count] eq $wordToSearch)

                             {

                                      $wordCount[$fileCount]= $wordCount[$fileCount]+1;

                             }

                             $count=$count+1;

                   }

          }

          #Count the total number of words in all the files.

          $totalWordCount=$totalWordCount+$wordCount[$fileCount];

          #Print the result.

          print (”The Number of Occurance of the word \”$wordToSearch\” in the file \”$ARGV[$fileCount]\” is: $wordCount[$fileCount]\n\n”);

          $fileCount=$fileCount+1;

}

 

print(”The total number of Ocuurance of the word \”$wordToSearch\” in all the files is : $totalWordCount \n\n”);

#Below is the optional code which you can add if you want to send a mail with the details.

 

open (MAIL, “|$mailer -t”) || die “Can’t open mailer”;

print MAIL “To: $toaddress\n”;

print MAIL “cc: \n”;

print MAIL “Subject: $subject\n\n”;

$count=0;

while($count < @ARGV)

{

          print MAIL “The Number of Occurance of the word \”$wordToSearch\” in the file \”$ARGV[count]\” is: $wordCount[count]\n\n”;

}

print MAIL “The total number of Ocuurance of the word \”$wordToSearch\” in all the files is : $totalWordCount \n\n\n\n”;

print MAIL “\n\nThis email was system generated, please do not reply.”;

print MAIL “\n\n\n\n\n\n\n\n\n\n\n\nThis e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and destroy this e-mail. Any unauthorized copying, disclosure or distribution of the material in this e-mail is strictly forbidden.”;

close (MAIL);

Perl – Coding Tips

Monday, March 23rd, 2009

Introduction

This document covers the basic functionalities in perl. These include the following:

·         Open and read file

·         Substring

·         Trim white spaces

·         Join string with/out delimiter

·         Remove newline

·         Split into array [reading key value pair]

·         String comparison and numeric comparison

·         Assign data in Hash or associative array and access the data

·         Write to and Close file

 

 

Open and Read file

 

To open and read a file, the read access to the file should be given.

 

open (<File identifier>,”<”,”<file>”)

or die “open failed:  $!”

 

File Identifier – After opening the file, the file will be referenced with the file identifier.

Symbol<’ – open a file in read mode

die – If open of the file failed, the program will display the error message and abort

 

$var=< File identifier>

 

E.g.: $var=’this is the first line of the file’

 

Read the first record (first line) from the file. Variable $var will hold the first line of the file.

 

@file_array=< File identifier >

 

The contents of the file can be assigned to an array

 

 

Substring

 

$substr_var=substr <string>, <start position>, <field length>

 

Get a substring of the first record from the file. The first record is stored in the variable $var.

 

In perl, the start position of a string is 0.

E.g.: If we need to cut first 5 characters from $var, start position will be 0 and field length will be 5.

$substr_var=substr $var, 0, 5

So, $substr_var=’this ‘

 

Note: Start position of a string in UNIX is 1.

 

 

Trim White Spaces

 

Substitute one or more white space characters with nothing from the end of the string (trailing spaces)

$variable =~ s/\s+$//

 

Substitute one or more white space characters with nothing from the beginning of the string (leading spaces)

$variable =~ s/^\s+//

 

Substitute one or more white space characters with nothing from anywhere in the string

$string =~ s/\s+//g

 

Substitute one or more white space characters with nothing from end and beginning of the string (leading and trailing spaces)

$test =~ s/^\s+|\s+$//g

         

         

Join string with/out delimiter

 

Join “”, <string 1>, <string2> [Join without any delimiter]

Output: <string1><string2>

 

Join “,”, <string 1>, <string2> [Join with ‘,’ delimiter]

Output: <string1>,<string2>

 

 

Remove newline

 

Substitute newline with nothing from the end of the string

$variable =~ s/\n+$//

 

chomp ($variable)

If variable is a hash, it chomps the hash’s values, but not its keys

 

 

Array [split on delimiter]

Array designated by @

 

@Arraytrial = (‘Trial’,’Array’)

$# Arraytrial=1 [largest index value]

 

To clean any array just set the largest index value to -1

$# Arraytrial = -1;

 

String can be put into array splitting it on a delimiter

@ Arraytrial = split(’,',$variable) [splitted on comma ‘,’]

          Split is an in built function which splits the string on the delimiter.

 

 

Data comparison

 

The comparison operator for numbers and strings are as follows:

 

Compare                   

Numbers      

String

Less than

lt

Greater than

gt

Less than equal

<=

le

Greater than equal

>=

ge

Equal

==

eq

Not equal

!=

ne

compare

<=>

cmp

         

 

 

Hash/Associative Array

Hash or associative array designated by %

 

Hashes contain data in pairs called KEY and associated VALUE

 

%names = (‘somali’,’444’,’arundhati’,’631’)

Or

% names = (somali         -> ‘444’,
                    arundhati     -> '631')
Or
my( %names);
$names{ <key> } = <value>

 

Print a hash

print “@{[% names]}”

 

 

 

Write and Close file

 

Open a file in write mode. Here if the file does not exist, the file will be created. If it exists, the file will be overwritten.

         

open (<File identifier>,”>“,”<file>”)

or die “open failed:  $!”

 

File Identifier – After opening the file, the file will be referenced with the file identifier.

Symbol>’ – open a file in write mode

die – If open of the file failed, the program will display the error message and abort

 

To append data into an existing file, the file needs to be opened in append mode.

 

open (<File identifier>,”>>“,”<file>”)

or die “open failed:  $!”

 

Symbol>>’ – open a file in append mode

 

To write to a file, write access to the file should be given.

 

print “$var\n” <File identifier>;

 

Close the file

 

close (<File identifier>)  

or die “close failed: $!”

 

 

Notes

 

There are many free Perl software are available on internet. Also you can use the UNIX command prompt just like unix scripts by using command “#!/usr/bin/perl” in script.

 

Reference(s)

http://docstore.mik.ua/orelly/perl/prog/ch01_05.htm

http://perldoc.perl.org/perlop.html

www.perl.com

www.perlfect.com

www.pageresource.com