Pages

Wednesday, 4 September 2013

Web application and Servlets notes

Servlet Context and Session Listeners

• Servlet context listeners.
– These listeners are notified when the servlet context (i.e., the Web application) is initialized and destroyed.
• Servlet context attribute listeners.
– These listeners are notified when attributes are added to, removed from, or replaced in the servlet context.
• Session listeners.
– These listeners are notified when session objects are created, invalidated, or timed out.
• Session attribute listeners.
– These listeners are notified when attributes are added to, removed from, or replaced in any session.

Implement the appropriate interface.
– Use ServletContextListener, ServletContextAttributeListener,
HttpSessionListener, or HttpSessionAttributeListener

Use these objects.
– This process is application specific, but there are some common
themes. For example, with the servlet context, you are most likely
to read initialization parameters (getInitParameter), store data for
later access (setAttribute), and read previously stored data
(getAttribute).

Declare the listener.
– You do this with the listener and listener-class
elements of the general Web application deployment descriptor
(web.xml) or of a tag library descriptor file.

Provide any needed initialization parameters.
– Servlet context listeners commonly read context initialization
parameters to use as the basis of data that is made available to all
servlets and JSP pages. You use the context-param web.xml
element to provide the names and values of these initialization
parameters.

How to pass parameters to whole web application – ServletContext

Here’s a serlvet code example to demonstrate how to pass a parameter to whole web application by using ServletContext “init-param” in web.xml.

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure outside the “servlet” element
        <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.mkyong.ServletDemo</servlet-class>
 </servlet>
 
 <context-param>
   <param-name>email</param-name>
   <param-value>admin@email.com</param-value>
 </context-param>

Servlet code

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
 
  PrintWriter pw = response.getWriter();
  pw.println(getServletContext().getInitParameter("email"));
 
 }
The “getServletContext().getInitParameter(“email”)” method is use to get the ServletContext parameter value in web.xml. In addition , this parameter is accessible by the whole web application.

How to pass parameters to a servlet – ServletConfig

Here’s a serlvet code example to demonstrate how to pass a parameter to a servlet by using ServletConfig “init-param” in web.xml

In the deployment descriptor (web.xml)

Put your parameter value in “init-param” and make sure inside the “servlet” element
        <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.mkyong.ServletDemo</servlet-class>
 
  <init-param>
   <param-name>email</param-name>
   <param-value>admin@email.com</param-value>
  </init-param>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>ServletName</servlet-name>
  <url-pattern>/Demo</url-pattern>
 </servlet-mapping>

Servlet code

public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws IOException{
 
  PrintWriter pw = response.getWriter();
  pw.println(getServletConfig().getInitParameter("email"));
 
 }
The “getServletConfig().getInitParameter(“email”)” method is use to get the ServletConfig parameter value in web.xml. Btw, this parameter only available for this servlet only. If you want a parameter which allow globally access by whole web application, you need put the parameter in servlet context element.
Here’s an example to pass parameter to whole web application.

Thursday, 22 August 2013

Allow and instruct the web application to query an untrusted https URL

Https query from web application like JSON to the site that needs to add certification exception (the trust) manually. When the user use their own browser to launch a https query to a web site that its certificate is not supported by the standard authorities, the user will be prompted for a permission to accept the certificate as an exception.

For web application server to launch the query, there is no way to prompt the web application to accept the exception, and the default is to reject the untrusted certificate. The web server will complain that the certificate is not found from the keystore for the requested target.

javax.xml.ws.soap.SOAPFaultException
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target


Now, we have to tell the web server to trust the certificate from the target.
1> Query the target URL by web browser.
2> Download and save the certificate <xxx.pem> from the target.
3> Append the certificate to the keystore

1. cd /usr/java/jdk1.6.0_33/jre/lib/security

2. /usr/java/jdk1.6.0_33/bin/keytool -import -v -trustcacerts -alias <Create your own> -file <filepath/xxx.pem> -keypass changeit -keystore ./cacerts -storepass changeit







Tuesday, 13 August 2013

Mounting file system, fstab, mtab

Basic format: mount -t <filesystem type> old_dir new_dir

1> Mounting a directory to another directory to let them access the same content
mount --bind old_dir<directory has content> new_dir<directory designed to access the content>

2> Mounting a device <like CDROM> with no -t parameter, it will let the OS to guess
mount /dev/cdrom /cd

3> NFS
  • /etc/exports specifies the access control of the mounting directory.

/home vale(rw) vstout(rw) vlight(rw)
/usr/X11R6 vale(ro) vstout(ro) vlight(ro)
/usr/TeX vale(ro) vstout(ro) vlight(ro)
/ vale(rw,no_root_squash)
/home/ftp (ro) 
/var/myApp 172.16.95.17/255.255.255.255(rw,no_root_squash) 

Each line defines a directory and the hosts allowed to mount it. Wildcard is allowed (* ?).
Range of ip address / network mask can be used to specify the host. 
If no host is give, any host matches and is allowed to mount the directory.
  • CLI form to mount NFS volume. 
    mount -t nfs nfs_volume local_dir options
     
  • /etc/fstab entry of NFS
[root@localhost ~]# cat /etc/fstab
/dev/VolGroup00/LogVol00 /                       ext3    defaults        1 1
/dev/VolGroup00/LogVol01 /data                   ext3    defaults        1 2
LABEL=/boot1            /boot                   ext3    defaults        1 2
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
LABEL=SWAP-sda6         swap                    swap    defaults        0 0
172.16.95.93:/var/myApp    /logserver-1/var/myApp     nfs     hard,intr       0 0

4> fstab and mtab
[root@localhost ~]# cat /etc/fstab
/dev/VolGroup00/LogVol00 /                       ext3    defaults        1 1
LABEL=/boot             /boot                   ext3    defaults        1 2
tmpfs                   /dev/shm                tmpfs   defaults        0 0
devpts                  /dev/pts                devpts  gid=5,mode=620  0 0
sysfs                   /sys                    sysfs   defaults        0 0
proc                    /proc                   proc    defaults        0 0
/dev/VolGroup00/LogVol01 swap                    swap    defaults        0 0
/var/myApp /localserver-1/var/myApp none rw,bind 0 0

There are 3 ways of using fstab.
1> mount -a will cause all the filesystem listed on fstab to be mounted, except those noted as noauto. Adding the -F will make mount fork. Usually it is used by boot scripts.

2> To mount or umount the filesystem mentioned on the fstab, it is sufficed to give only the device or the mount point.

e.g In fstab, /tmp/a /tmp/b none rw,bind 0 0
mount /tmp/a or mount /tmp/b will suffice.

3>  Normally, only the superuser can mount  file  systems.   However, when  fstab  contains  the user option on a line, anybody can mount the corresponding system.

Friday, 28 June 2013

Configure Sendmail as SMTP Mail Client

Configuration

Step # 1: Disable Sendmail Daemon In a Listing Mode

# vi /etc/sysconfig/sendmail

Modify the line:
DAEMON=no
 

Step #2: Configure Mail Submission

# vi /etc/mail/submit.cf 
 
D{MTAHost}<smtp.mailserver.com>


Sending Emails With Sendmail

SMTP Headers File  

<e.g /tmp/mail.txt>
From: "Me" <jxx_1@mail1.com>
To: "jxx_1@mail1.com" <jxx_1@mail1.com>
Subject: First Email
MIME-Version: 1.0
Content-Type: text/plain

Hello, World!
.

Send Email

cat /tmp/mail.txt | sendmail -i -t

-t tells sendmail that the message contains all the information it needs to send an email, i.e. the To: and From: fields, etc. Otherwise it's going to expect you to pass them as arguments on the command line.
-i tells sendmail that we're piping the message in from a file, so it should ignore the single-period requirement and expect an EOF instead. If you don't pass this argument when piping a file, then sendmail will expect a lone period at the end of your message file.
 
Source: 

Tuesday, 25 June 2013

Network connection troubleshooting

Error message: eth0 interface on and off once a while
tail -f /var/log/messages:
dmesg | less: 
e100: eth0: e100_watchdog: link down
e100: eth0: e100_watchdog: link up, 100Mbps, full-duplex

[root@localhost ~]# ethtool eth0
Settings for eth0:
        Supported ports: [ TP MII ]
        Supported link modes:   10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
        Supports auto-negotiation: Yes
        Advertised link modes:  10baseT/Half 10baseT/Full
                                100baseT/Half 100baseT/Full
        Advertised auto-negotiation: Yes
        Speed: 100Mb/s
        Duplex: Full
        Port: MII
        PHYAD: 1
        Transceiver: internal
        Auto-negotiation: on
        Supports Wake-on: g
        Wake-on: g
        Current message level: 0x00000007 (7)
        Link detected: yes

[root@localhost ~]# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:02:B3:4D:BD:6B 
          inet addr:172.16.95.27  Bcast:172.16.95.255  Mask:255.255.255.0
          inet6 addr: fe80::202:b3ff:fe4d:bd6b/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:720866 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1243358 errors:19788 dropped:0 overruns:0 carrier:19788
          collisions:287 txqueuelen:1000
          RX bytes:61520720 (58.6 MiB)  TX bytes:1164775778 (1.0 GiB)

[root@localhost ~]# mii-tool -v eth0
eth0: negotiated 100baseTx-FD flow-control, link ok
  product info: Intel 82555 rev 4
  basic mode:   autonegotiation enabled
  basic status: autonegotiation complete, link ok
  capabilities: 100baseTx-FD 100baseTx-HD 10baseT-FD 10baseT-HD
  advertising:  100baseTx-FD 100baseTx-HD 10baseT-FD 10baseT-HD flow-control
  link partner: 100baseTx-FD 100baseTx-HD 10baseT-FD 10baseT-HD flow-control

Reset auto-negotiation
[root@localhost ~]#  mii-tool -r eth0

If all fail, replace the cable.


Some clients in the subnet has cached the IP with old MAC address, I want them to update the new value by doing a ARP broadcast, is it possible in Linux?

Yes, it's called "Unsolicited ARP" or "Gratuitous ARP". Check the manpage for arping for more details, but the syntax looks something like this:
arping -U 192.168.1.101
If you're spoofing an address, you may need to run this first:
echo 1 > /proc/sys/net/ipv4/ip_nonlocal_bind
Finally, because of its spoofing ability, sending Unsolicited ARP packets is sometimes considered a "hostile" activity, and may be ignored, or might lead to being blocked by some third-party firewalls.

Usage Example:

 The problem is I accidentally assign a new machine with an used IP, so they conflict the IP. I can't access the old machine using SSH. Now I remotely shutdown the wrong (new) machine, but I still cannot access the old machine, I suspect the router has cached MAC address in its ARP table.

Monday, 8 April 2013

VPN IPSEC - Forticlient 2 FGT

Steps to create dialup VPN by Forticlient


1> Create Phase 1


2> Phase 2





Tuesday, 19 March 2013

Tomcat - server.xml

Testing Tool: 

curl, wget, telnet 

 Containers

Tomcat refers to Engine, Host, Context, and Cluster, as container. The highest-level is Engine; while the lowest-level is Context. Certain components, such as Realm and Valve, can be placed in a container.

Engine

A Engine is the highest-level of a container. It can contains one or more Hosts. You could configure a Tomcat server to run on several hostnames, known as virtual host.
<Engine name="Catalina" defaultHost="localhost">
The Catalina Engine receives HTTP requests from the HTTP connector, and direct them to the correct host based on the hostname/IP address in the request header.

Realm

A Realm is a database of user, password, and role for authentication (i.e., access control). You can define Realm for any container, such as Engine, Host, and Context, and Cluster.
<Realm className="org.apache.catalina.realm.LockOutRealm">
  <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
The default configuration defines a Realm (UserDatabaseRealm) for the Catalina Engine, to perform user authentication for accessing this engine. It uses the JNDI name UserDatabase defined in the GlobalNamingResources.
Besides the UserDatabaseRealm, there are: JDBCRealm (for authenticating users to connect to a relational database via the JDBC driver); DataSourceRealm (to connect to a DataSource via JNDI; JNDIRealm (to connect to an LDAP directory); and MemoryRealm (to load an XML file in memory).

Hosts

A Host defines a virtual host under the Engine, which can in turn support many Contexts (webapps).
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
The default configuration define one host called localhost. The appBase attribute defines the base directory of all the webapps, in this case, <CATALINA_HOME>\webapps. By default, each webapp's URL is the same as its directory name. For example, the default Tomcat installation provides four webapps: docs, examples, host-manager and manager under the webapps directory. The only exception is ROOT, which is identified by an empty string. That is, its URL is http://localhost:8080/.
The unpackWARs specifies whether WAR-file dropped into the webapps directory shall be unzipped. For unpackWARs="false", Tomcat will run the application from the WAR-file directly, without unpacking, which could mean slower execution.
The autoDeploy attribute specifies whether to deploy application dropped into the webapps directory automatically.

Cluster

Tomcat supports server clustering. It can replicate sessions and context attributes across the clustered server. It can also deploy a WAR-file on all the cluster.

Valve

A Valve can intercept HTTP requests before forwarding them to the applications, for pre-processing the requests. A Valve can be defined for any container, such as Engine, Host, and Context, and Cluster.
In the default configuration, the AccessLogValve intercepts an HTTP request and creates a log entry in the log file, as follows:
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
       prefix="localhost_access_log." suffix=".txt"
       pattern="%h %l %u %t &quot;%r&quot; %s %b" />
Other valves include:
  • RemoteAddrValve: which blocks requests from certain IP addresses,
  • RemoteHostValve: which blocks request based on hostnames,
  • RequestDumperValve: which logs details of the requests,
  • SingleSignOn Valve: when placed under a <host>, allows single sign-on to access all the webapp under the host.

Sample of server.xml


<Server port="8006" shutdown="SHUTDOWN" debug="0">
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" debug="0"/>
  The GlobalResourcesLifecycleListener enables the global resources, and makes possible the use of JNDI for accessing resources such as databases.
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" debug="0"/>

  <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>

The <GlobalNamingResources> element defines the JNDI (Java Naming and Directory Interface) resources, that allows Java software clients to discover and look up data and objects via a name.
The default configuration defines a JNDI name called UserDatabase via the <Resource> element, which is a memory-based database for user authentication loaded from "conf/tomcat-users.xml".

    <!-- Editable user database that can also be used by UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml"
       description="User database that can be updated and saved">
    </Resource>
  </GlobalNamingResources>

  <Service name="portal">
    <!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
    <Connector port="80"
               maxThreads="150"
               minSpareThreads="25"
               maxSpareThreads="75"
               enableLookups="false" 
               acceptCount="100"
               debug="0"
               connectionTimeout="2000"
               disableUploadTimeout="true"
               compression="on"
               address="172.16.95.150"/>
     <!-- fams.fortinet.com -->
     <Connector port="443"
                keystoreFile="/root/certificates/fams2012.p12"
                keystorePass="Fortinet0511#"
                keystoreType="PKCS12"
                SSLEnabled="true"
                maxThreads="150"
                minSpareThreads="25"
                enableLookups="false"
                disableUploadTimeout="true"
                scheme="https"
                secure="true"
                connectionTimeout="2000"
                clientAuth="false"
                maxKeepAliveRequests="20"
                sslProtocol="TLS"
                address="172.16.95.150"
                restrictedUserAgents="^.*MS Web Services Client Protocol.*$"/>

     <!-- fzm1.fortinet.com -->
     <Connector port="443"
                keystoreFile="/root/certificates/fmz1.p12"
                keystorePass="fortinet123"
                keystoreType="PKCS12"
                SSLEnabled="true"
                maxThreads="150"
                minSpareThreads="25"
                enableLookups="false"
                disableUploadTimeout="true"
                scheme="https"
                secure="true"
                connectionTimeout="2000"
                clientAuth="false"
                maxKeepAliveRequests="20"
                sslProtocol="TLS"
                address="172.16.95.155"
                restrictedUserAgents="^.*MS Web Services Client Protocol.*$"/>
    <!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
    <Connector port="8009"
               enableLookups="false"
               redirectPort="443"
               debug="0"
               protocol="AJP/1.3" />
    <Engine name="portal" defaultHost="portal" debug="0">

      <!-- Global logger unless overridden at lower levels -->
      <Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm" debug="0" resourceName="UserDatabase"/>
      <Host name="portal"
            debug="0"
            appBase="webapps"
            unpackWARs="true"
            autoDeploy="true"
            xmlValidation="false"
            xmlNamespaceAware="false">
        <Logger className="org.apache.catalina.logger.FileLogger" directory="logs"  prefix="manager_log." suffix=".txt" timestamp="true"/>
        <Logger className="org.apache.catalina.logger.SystemOutLogger" timestamp="true"/>
        <Context path=""
                 docBase="/usr/local/portal/fams"
                 debug="0"
                 reloadable="true"
                 crossContext="true"
                 allowLinking="true"
                 privileged="true"/>
      </Host>
    </Engine>
  </Service>
</Server>