Saturday, July 28, 2007

Finding out all processes associated with open sockets

Normally I've only used the 'netstat' command to find out what are the sockets opened in the operating system by using '-a' flag, but the new thing I've discovered recently is that netstat even allows me to track the processes that are opening them, via the '-p' flag. A simple dump of the command on my system gives the following output:
# netstat -ap       
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 *:http *:* LISTEN 6695/apache2
tcp 0 0 *:ssh *:* LISTEN 6604/sshd
udp 0 0 *:bootpc *:* 5294/dhcpcd
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags Type State I-Node PID/Program name Path
unix 2 [ ACC ] STREAM LISTENING 10287 6696/apache2 /var/run/cgisock
unix 2 [ ACC ] STREAM LISTENING 9767 6324/gdm /tmp/.gdm_socket

... remaining output truncated.
The '-p' flag allows us to track applications that are holding onto open sockets, which is a good way to understand why certain sockets may have to be open, like bootpc in my example, which is necessary for the DHCP daemon to function.

Knowing this information will allow you to close down any unnecessary services that you do not need, reducing the amount of attack vectors that your machine is exposed to.

Watching Barry Bonds' 754th

By virtue of some free tickets from business associates of ours, we were treated to a baseball game at AT&T stadium, the match up between the home team, the San Francisco Giants and the Florida Marlins.

It was exciting for me personally, for it was the first time I have ever been to a baseball game. Besides that, it may also possibly be baseball history in the making as Barry Bonds, the lead batter for the Giants, is closing in to the all time record of 755 home runs.

We were lucky to have witnessed Barry make his 754th, and one thing that I was told, the lucky guy who catches his ball will probably be able to sell it for a cool million dollars. No wonder there were huge excitement among the people on the far side of the stadium from us where the home run ball fell on. In fact I'd say they were fanatical, as there were even people sailing and canoing in the waters outside the stadium, where it was said that Barry had at least dropped 50 home run balls out there.

While I would have liked Barry to score his 755th and even his record breaking 756th, but it didn't happen. Still, it was great to have been there and enjoying the excitement of being able to be in part of the game.
Thursday, July 26, 2007

Having fun with java.lang.Object

java.lang.Object is the mother of all objects in the Java world. While being the core of Java, it is not a native object, but rather stored as compiled class file that is located in $JAVA_HOME/jre/lib/rt.jar. This means that if you try overwriting the file at java/lang/Object.class within the jar file, your Object will get loaded instead of the original Object definition.

The idea here is to overwrite java.lang.Object which will give you first access to any other object before anybody else. However, it's probably not a wise idea to modify the original jar file itself, as Java will break if you make some bad changes to rt.jar. I recommend that you copy rt.jar instead, and tell java to use it instead of the original by using the -Xbootclasspath flag. For this purpose, I'd assume that you've named your new jar file as modified-rt.jar.

Now look for src.zip in your $JAVA_HOME directory and extract java/lang/Object.java. Compile that and add the class file into your new jar:


$ javac java/lang/Object.java
$ jar uvf modified-rt.jar java/lang/Object.class


The compiled class won't be any different from the standard lang.Object within the java class. (Do a 'diff' on it if you like). A triva on the compiled java.lang.Object, is that javac actually treats it differently when it comes to compiling the constructor. If you run javap on it, you'll find out that it doesn't have an INVOKESPECIAL constructor call that is present for all other objects, an implicit constraint that is defined by the Java Machine Specification. It made sense, after all there is no other object that is its superclass.

To make sure that the new modified-rt.jar runs ok, write a test application to make sure that the JVM will run as normal. I'm going to use the following example class file, and use it illustrate what I'm going to do later, so you might want to do the same as well. Save the following file as ObjectFieldReflection.java:


import java.lang.reflect.*;

public class ObjectFieldReflection {
public static void main(String args[]) throws Exception {
Field[] f_a = Object.class.getDeclaredFields();
for (Field f : f_a) {
f.setAccessible(true);
System.out.println("Fieldname="+f.getName()+" value="+f.get(null));
}
}
}


The above application will try to cycle through all the fields of java.lang.Object and print out the value within the fields. Since the default java.lang.Object doesn't have any fields at all, there's really nothing to print out, and the application will just terminate as normal:


$ java -Xbootclasspath:rt.jar ObjectFieldReflection


One of the things that may be fun to do is to count the number of objects that is instantiated by Java over the lifecycle of the application. An easy way to do that is to create a static field in java.lang.Object, and use the default constructor to count every time an object is created. Edit the java/lang/Object.java file, and add the following static field declaration and a default constructor so that it looks like this:


public static int createdCount = 0;

public Object() {
createdCount++;
}


Recompile and re-add that into the jar file, and run it again. Now you should be able to find out the number of objects created in the lifecycle of your application, which the output looks something like this:


$ java -Xbootclasspath:rt.jar ObjectFieldReflection
Fieldname=createdCount value=1200


It tells you that 1200 objects have been created just for the example simple application to run. Imagine how many more classes are created for a large application? Let's say you want to find out about the number of objects garbaged in the lifecycle of your application instead. Modify Object.java like this:


public static int garbagedCount = 0;

public void finalize() {
garbagedCount++;
}


finalize() is a special method that all Java object calls before being garbaged collected. It is similar to destructors in C++, although there are many subtle differences between them in reality. If you tried running with the new code, the JVM crashes with a core dump:


#
# An unexpected error has been detected by HotSpot Virtual Machine:
#
# SIGSEGV (0xb) at pc=0xb79df93f, pid=25096, tid=3085408944
#
# Java VM: Java HotSpot(TM) Client VM (1.5.0_08-b03 mixed mode)
# Problematic frame:
# V [libjvm.so+0x30793f]
#
# An error report file with more information is saved as hs_err_pid25096.log
#
# If you would like to submit a bug report, please visit:
# http://java.sun.com/webapps/bugreport/crash.jsp
#
Aborted


So what's going on with that? Your guess is as good as mine, but here's what I think: Java has to rely on the Garbage Collector(GC) to handle memory collection and because the GC uses complex algorithms to make reclaiming memory efficient, it is probably expecting that java.lang.Object is by default the easily reclaimed sort. But since we're putting code into finalize(), it actually changes that assumption, since all objects have to be individually 'collected', thus requiring the less efficient 'Mark and Sweep' GC method, something that the JVM is not expecting, hence crashing it.

So while tampering with Java core class files may be a nice, unintrusive way of collecting information without having to modify existing applications, or applications which you do not have the source to, be mindful that sometimes it may not be worth the trouble when it comes to dealing with the unintended consequences that arise, especially when coded in a manner that contravene the rules of the Java specification.
Tuesday, July 24, 2007

Rotating image banners for blogger


This post is deprecated. More details...
Some of you were curious to find out how to create a rotating banner in blogger, here's how I managed to do it:

1) Enabling image header display on blogger first.
Theoratically, this is not necessary if you knew your way around blogger's template language, but since I embed my code inside the useImage conditional block, it has to be enabled before header images will be shown. Select the Template->Page Elements tab and click 'edit' on the (Header) element, which the following window appears:



Select the image that you want, from an external URL. You won't be using the 'From your computer' option, because there's no way you can know how the url of the image is managed in order to use it. The actual picture doesn't matter, but it is usually the one you want to be showing when javascript is not enabled. Click on 'Save changes' once you are done selecting the image.

Blogger is stingy in the sense that it only allows one image to be uploaded at a time, so you'll need to use an external hosting site to host your other pictures in order for rotation. You can use any image hosting site, and I use flickr for this task.

2) Modifying the blogger template.
The template needs to be modified to use javascript to perform the random image rotation. Select the Edit HTML tab, and find the following lines in your template, and insert the modification highlighted in red:
<b:if cond='data:useImage'>
<b:if cond='data:imagePlacement == "REPLACE"'>
<!--Show just the image, no text-->
<div id='header-inner'>
<a expr:href='data:blog.homepageUrl' style='display: block'>
<img expr:alt='data:title' expr:height='data:height'
expr:id='data:widget.instanceId +
"_headerimg"' expr:src='data:sourceUrl'
expr:width='data:width' style='display: block'/>
</a>
</div>
<b:else/>
<!--Show image as background to text-->
<div class='titlewrapper' style='background: transparent'>
<h1 class='title' style='background: transparent; border-width: 0px'>
<b:if cond='data:blog.url == data:blog.homepageUrl'>
<data:title/>
<b:else/>
<a expr:href='data:blog.homepageUrl'><data:title/></a>
</b:if>
</h1>
</div>
<div class='descriptionwrapper'>
<p class='description'><span><data:description/></span></p>
</div>
<!-- Start Modification. -->
<script type='text/javascript'>
var banner= new Array()
banner[0]="http://your.image.url"
banner[1]="http://your.image.url"
banner[2]="http://your.image.url"
banner[3]="http://your.image.url"
banner[4]="http://your.image.url"
var random=Math.round((banner.length-1)*Math.random());
document.write("<img src='"+banner[random]+"' style='display: block'/>");
</script>
<noscript>
<img expr:alt='data:title' expr:height='data:height'
expr:id='data:widget.instanceId +
"_headerimg"' expr:src='data:sourceUrl'
expr:width='data:width' style='display: block'/>
</noscript>
<!-- End Modification. -->

</b:if>
Make sure you replace "http://your.image.url" with the actual url of your images, which should now allow you to display changing image banners for blogger.
Monday, July 23, 2007

Making Firefox associate .pdf files automatically

For a long time, I kept wondering how Firefox was able to provide a sensible default application to open a downloaded pdf file, which was present in other distros but not in Gentoo Linux. I knew it was in my configuration setup, I just never knew where.

Before, whenever I download a .pdf file, I'm always given this dialog box:



I was never able to find the configuration panel to setup the default application within Firefox, which was why I was living with this annoying handicap for a long time until I read about file associations into the mailcap file. Here's the entry that I've added into my ~/.mailcap
application/pdf;/usr/bin/gv %s
By adding just that line associates the .pdf file format to gv: