How to obtain signer’s details from a JavaScript signed data

July 2, 2009 by bozhobg

In a previous post I described how to sign data with only javascript. Now, this data should be used on the server side for something. Here is how a Java developer can extract the signature details, and verify whether the content received from a form is really what has been signed. The general scenario is – a user submits a form, the data from which he signs. Then on the server the submitted data should be verified against the signed (PKCS7) data.

One needs the Bouncycastle libraries and apache commons codec:
commons-codec-1.3.jar
bcprov-jdk16-143.jar
bcmail-jdk16-143.jar

package com.materna.remedy.plugins;

import java.security.Security;
import java.security.cert.CertStore;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class CertificateDataExctractor {
	private Map<String, Object> extractInfos(String base64EncodedPKCS7,
			String contentString, boolean isIe) {

		try {
			byte[] data = Base64.decodeBase64(base64EncodedPKCS7.trim().getBytes());

			Security.addProvider(new BouncyCastleProvider());

			CMSSignedData signedData = new CMSSignedData(data);

			if (signedData.getSignedContent() == null) {
				byte[] contentBytes;
				if (!isIe) {
					contentBytes = contentString.getBytes();
				} else {
					contentBytes = contentString.getBytes("UnicodeLittleUnmarked");
				}

				CMSProcessable cmsProcesableContent = new CMSProcessableByteArray(
						contentBytes);
				signedData = new CMSSignedData(cmsProcesableContent, data);
			}

			CertStore certsStore = signedData.getCertificatesAndCRLs(
					"Collection", "BC");
			SignerInformationStore signersStores = signedData.getSignerInfos();

			boolean verified = true;
			boolean validCertificate = true;
			Map<String, Object> signerData = null;

			for (Iterator<SignerInformation> iter = signersStores.getSigners()
					.iterator(); iter.hasNext();) {
				SignerInformation signer = iter.next();
				// emulate(signer);

				Collection certCollection = certsStore.getCertificates(signer
						.getSID());

				if (!certCollection.isEmpty()) {
					X509Certificate cert = (X509Certificate) certCollection
							.iterator().next();

					try {
						if (!signer.verify(cert.getPublicKey(), "BC")) {
							verified = false;
						}
					} catch (Exception ex) {
						ex.printStackTrace();
						// if this is an attempt to verify it assuming Firefox,
						// try assuming IE. If it is already IE - the
						// verification doesn't pass
						if (!isIe) {
							return extractInfos(base64EncodedPKCS7,
									contentString, true);
						}
						verified = false;
					}

					// If this is the last signer in the chain, obtain the data
					if (!iter.hasNext()) {
						signerData = extractSubjectInfos(cert);
					}
				}
			}
			return signerData;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}

	}
}

And of course, you provide your own implementation of getSubjectInfos method, putting whatever data you need from the certificate in the Map.

A really useful eclipse shortcut to configure

June 20, 2009 by bozhobg

I wonder why it isn’t in the default set – “generate getters and setters”. This is one of the most frequent actions. I’m setting it to ALT+SHIFT+G (Generate).

Вече и спамът е законен…

June 1, 2009 by bozhobg

В нашата страна спамът бил законен. Не знам от кога е така, но днес получих писмо, чийто 1-ви ред беше:

Съгласно Закона за електронна търговия, чл. 6 (1) Ви съобщаваме, че е възможно това търговско съобщение да не е поискано от Вас.

Да видим какво казва законът:

Чл. 6. (1) Доставчик на услуги, който изпраща непоискани търговски съобщения по
електронната поща без предварително съгласие на получателя, е длъжен да осигури ясното
и недвусмислено разпознаване на търговското съобщение като непоискано още с
постъпването му при получателя

Всички да ъпдейтват спам-ботовете и да добавят на 1-вия ред “Това може да не сте го поискали”.

Лайняната улица

May 22, 2009 by bozhobg

Улицата е Княз Борис I, София. Всеки ден по около десетина минути вървя по нея към работа. И всеки ден тротоарът е осран. С кучешки лайна. Много.
Обяснението е просто – улицата води до малко паркче пред църквата “Св.Георги победоносец”, където хората извеждат кучетата си. Обяснението е просто като хората, които предизвикват ‘феномена на лайняната улица’. Които пък от своя страна са представителна извадка за населението. Ами да – защо да почистят, като така или иначе никой друг не си чисти – толкова е “логично”.
Е, това лайната на политиците ли се сега? Те ли серат всеки ден по тая улица и не си чистят? Или всеки ежедневно се изсира публично, малко по малко превръщайки всичко, което ни заобикаля, в една смърдяща тоалетна. Или по-добре – в един подлез-тоалетна, защото е ниско. И върглаяйки се в екскременти, псуваме си на ум политиците, които са универсалното оправдание за всичко, и заспиваме спокойно, готови за нови фекални подвизи на другия ден.

Обобщението, което правя не е никак тенденциозно, а е по-скоро доста експресивна илюстрация на социалната ни действителност.

NoScript and AdBlock plus – two sides to every story

May 2, 2009 by bozhobg

(If you don’t want to read too much here, check the links below)

Recently a lot of crap has been written at many places against NoScript (reddit, slashdot, the addon page on mozilla’s site, etc).
We can easily call it a flame war, but that’s not the point – the point is to have a good-working protective solution for any web-behaviour. I don’t AdBlock plus, but a friend of mine does, and she is pretty happy with it. I’m pretty happy with NoScript, so every train has its passengers. Again – that is not the point. The point is that obviously AdBlock plus developer(s) trying to drive users away from NoScript. As you are reading this, you have probably read the blog-post in ABP site : http://adblockplus.org/blog/attention-noscript-users.

But of course, there is two sides to every story:

http://forums.informaction.com/viewtopic.php?p=2777#p2777

http://noscript.net/faq#qa3_21
https://addons.mozilla.org/en-US/firefox/addon/722 saying:

Notice to AdBlock Plus users: after a targeted attack from EasyList which broke functionality like direct links to development builds on developer’s sites, NoScript 1.9.2.3 and above configure a regular filterset whitelisting them. As any filterset, you can easily disable it with two clicks if you prefer.

And so, I saw a pile of users removing NoScript just for the reason someone has mocked it. How rational. Good luck to those in not getting infected.

“Who started the flame war” is an irrelevant question here – the question is why people are so not-quite-intelligent. I will continue using NoScript.

How to create a digital signing solution with only JavaScript

April 16, 2009 by bozhobg

It is sometimes required to have the user sign a text in order to certify that he is the one who has done the operation. For example, in an e-banking software, the user might have to sign a text describing the transaction (“Transfer 300 dollars to IBAN xxxxxxxxx”), or sign a request for a governmental eService. This could be achieved by a java-applet, but as JRE owners are not a majority, it is preferable to use other ways.

Of course, the preconditions are, that the user has a digital signature, issued by a CA, and has followed the CA’s manual for installing the certificate in a browser. If these steps are not completed successfully, the solution below wouldn’t work.

Also, note that this uses PKCS7 (java developers: use bouncy castle to verify it), instead of the XAdES standard. Internet Explorer has support for XAdES, but FireFox doesn’t.

Let’s see a simple HTML page that should sign a given text:


<script src="sign.js" type="text/javascript"></script>

<input id="text" type="text" />
<input onclick="signDigest(document.getElementById('text').value);" type="button" value="Sign" />

and then the JavaScript itself:


function signDigest(text)
{
if(window.event)
window.event.cancelBubble = true;

var dest = sign(text); //TODO
alert(dest);
return dest;
}

// CAPICOM constants
var CAPICOM_STORE_OPEN_READ_ONLY = 0;
var CAPICOM_CURRENT_USER_STORE = 2;
var CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
var CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6;
var CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9;
var CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
var CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 0x00000080;
var CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
var CAPICOM_INFO_SUBJECT_SIMPLE_NAME = 0;
var CAPICOM_ENCODE_BASE64 = 0;
var CAPICOM_E_CANCELLED = -2138568446;
var CERT_KEY_SPEC_PROP_ID = 6;

function IsCAPICOMInstalled()
{
if(typeof(oCAPICOM) == "object")
{
if( (oCAPICOM.object != null) )
{
// We found CAPICOM!
return true;
}
}
}

function FindCertificateByHash()
{

try
{
// instantiate the CAPICOM objects
var MyStore = new ActiveXObject("CAPICOM.Store");
// open the current users personal certificate store
MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);

// find all of the certificates that have the specified hash
var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, strUserCertigicateThumbprint);

var Signer = new ActiveXObject("CAPICOM.Signer");
Signer.Certificate = FilteredCertificates.Item(1);
return Signer;

// Clean Up
MyStore = null;
FilteredCertificates = null;
}
catch (e)
{
if (e.number != CAPICOM_E_CANCELLED)
{
return new ActiveXObject("CAPICOM.Signer");
}
}
}

function sign(src)
{
if(window.crypto &amp;&amp; window.crypto.signText)
return sign_NS(src);

return sign_IE(src);
}

function sign_NS(src)
{
var s = crypto.signText(src, "ask" );
return s;
}

function sign_IE(src)
{
try
{
// instantiate the CAPICOM objects
var SignedData = new ActiveXObject("CAPICOM.SignedData");
var TimeAttribute = new ActiveXObject("CAPICOM.Attribute");

// Set the data that we want to sign
SignedData.Content = src;
var Signer = FindCertificateByHash();

// Set the time in which we are applying the signature
var Today = new Date();
TimeAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
TimeAttribute.Value = Today.getVarDate();
Today = null;
Signer.AuthenticatedAttributes.Add(TimeAttribute);

// Do the Sign operation
var szSignature = SignedData.Sign(Signer, true, CAPICOM_ENCODE_BASE64);
return szSignature;
}
catch (e)
{
if (e.number != CAPICOM_E_CANCELLED)
{
alert("An error occurred when attempting to sign the content, the errot was: " + e.description);
}
}
return "";
}

And that should do the stuff – the signed text can be sent to the server, where it can be verified (in case, of course, the server has the public part of the user’s certificate)

P.S. One important note when verifying afterward – Internet Explorer uses UnicodeLittleUnmarked (UTF-16LE) to encode the signed data, before signing it. So when verifying, use this encoding.

How to iterate over java.util.Set in JSF

March 3, 2009 by bozhobg

I spent quite some time trying to find a solution for the following JSF issue: it is not possible to iterate over a java.util.Set.
- ui:repeat (facelets) doesn’t work
- a4j:repeat (richfaces) doesn’t work
- c:forEach works..only in case it does not rely on a variable defined by a parent component (rich:dataTable for instance)

All above are pretty logical phenomena, as UIData relies on ordered data, and generally a Set is not ordered.

In my case I had to use a Set defined in the Hibernate (JPA) object (PersistentSet).
An important note: you should use a set in case the view order is of no matter to you.

The solution..is pretty simple. And I’ll suggest it to be a part of facelets/richfaces for the next version, unless of course there is some valid specific

reason for it not to be.

1. Define your own UI component extending an existing repeater component. I used a4j:repeat (HtmlAjaxRepeat)
2. Override the metohd getDataModel
3. Define your component in your faces-config
4. create a custom facelets tag definition
5. Define a context-variable in web.xml pointing to the facelet tag definition.

Note: for use with JSP instead of Facelets, you should define a .tld and a Tag handler, which is not an ojbect of this post.

Now let’s see the steps in detail:

1,2. Here some code:

package com.myproject.components;
import java.util.ArrayList;
import java.util.Set;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.ajax4jsf.component.html.HtmlAjaxRepeat;
import org.ajax4jsf.model.SequenceDataModel;

public class UIIterator extends HtmlAjaxRepeat {

   @SuppressWarnings("unchecked")
   @Override
   protected DataModel getDataModel() {
      Object current = getValue();
      if(current instanceof Set){
          return new SequenceDataModel(new ListDataModel(
                new ArrayList((Set) current)));
      }
      return super.getDataModel();
   }
}

So, as we don’t care about the order of the elements, we just create a new ArrayList out of the Set. And we can now easily return the appropirate DataModel.

3. Add this to your faces-config. (I copied it from the a4j definition)

<component>
		<description />
		<display-name>Iterator</display-name>
		<component-type>com.myproject.Iterator</component-type>
		<component-class>com.myproject.components.UIIterator</component-class>

		<component-extension>
			<component-family>javax.faces.Data</component-family>
			<renderer-type>org.ajax4jsf.components.RepeatRenderera</renderer-type>
		</component-extension>
	</component>

4. Here is the tag definition for facelets

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
"http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet">
<namespace>http://myproject.com/cust</namespace>

<tag>
<tag-name>repeat</tag-name>
<component>
<component-type>com.myproject.Iterator</component-type>
<renderer-type>org.ajax4jsf.components.RepeatRenderer</renderer-type>
</component>
</tag>

</facelet-taglib>

Save this file as /WEB-INF/facelets/custom.taglib.xml

5. Add to your web.xml

<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>/WEB-INF/facelets/custom.taglib.xml</param-value>
</context-param>

6. It is now ready to use

xmlns:cust=”http://myproject.com/cust”

<cust:repeat var=”myVar” value=”${aSet}”>

</cust:repeat>
I think it is way neater than other workarounds, like defining a custom EL Resolver.

Why I might not want to use Flex

November 27, 2008 by bozhobg

While waiting for my eclipse to shut down, because the Flex Builder plugin again made it crash, I decided to write a little about my Flex experience.

I’m now on the finish straight of a small-to-medium project which uses Flex as a front-end.

On first sight Flex is smooth and pleasant to work with. You draw a bunch of beautiful components, write three lines of actionscript, and here’s is our nice “advanced hello”. But whenever one gets more into the details, the immaturity of Flex (and ActionScript) is too visible, alas.

First, to start with the more general stuff:

  • exception handling. For a Java-guy like me, the exception handling ‘not perfect’. When an Error is caught, all you can know about it is .. the error code. Isn’t this too 1990? Stacktraces you can somehow acquire by calling “trace”, but it requires some configurations.
  • event handling. At first, it does not seem troublesome when you see the event handling mechanism. object.addEventListener(stringConstantEventType, handlerMethod). Ok, I don’t really mind the String constant (though I should), but the handler method accepts only an Event as an argument. (And when you write your method to have the wrong argument class it starts to feel strange). This makes it impossible to pass other arguments to the ‘listener’. Yes, you can use fields of the declaring class, but what if two asynchronous notifications happen? Actually, a brief look at the Ovserver (listener) pattern shows the right way to do this. I don’t know why it is so strange.
  • multithreading. Here I still don’t get things quite well – I read that Flex is single-threaded, and there is no way of manipulating threads. What a shame – especially if the flash player supports multithreading. In fact Flex maybe supports some kind of multithreading, with which it serves asynchronous requests, but are these mechanisms accessible for the developer? Actually, my recent experience hints towards the hypothesis that Flex has 2 threads – one for UI and one for the alleged asynchronous requests. So only one async request at a time. I might be wrong, of course.
  • dynamically typed AS3. Completely no problem with this, but something bothered me. When I referenced an objecet by its interface, the compiler did not know it is an Object, and so I couldn’t call its Object mehtods (toString()). So I need to cast it to Object (or whatever I want). And where did the dynamic typing go..?
  • event dispatching. This might well go to the section above, but here I don’t mean the machanisms, but some strange implementation details. I have exactly two examples – the Event.COMPLETE is dispatched by an Image before the Image object has marked itself as completed. And this caused problems. Also, the Click event is not dispatched if MouseDown is.
  • now on to some very specific things. Starting with the file upload. Something very basic and regularly needed. Prior to Flex 3.2 (and I’m using 3.1), there is not getBytes, or similar methods for a file. So the only option to send the file is via a Http request (instead of some remoting that I would prefer). But ok – I created a servlet which would parse the request, check the size, type, dimensions of the image, and return whether it is allowed to be uploaded or not. But much to my surprise, as far as I understand (please, anyone correct me if I’m wrong), there was no way of getting feedback from the server. So I had to think of a way. I thought of a solution, which I’m ashamed of – I used the HttpStatusError, and I mapped an arbitrary Http status code to a certain error (type not supported, size too big, etc.)
  • fonts cannot be loading dynamically – they must be precompiled. Which is my case made me write an java image creation servlet, but I suppose that in the common case it would be sufficient.
  • hibernate support – I only took a glimpse of the examples of a hibernate support, saw some re-definitions of collection mappings (<one-to-many ..), and ran away screaming.

So, from these points I dare to conclude that Flex is still immature. Version 5 might be really good. But not now, and not until some serious considerations and rafactoring.

That’s why I’m likely to propose GWT as a RIA solution for forthcoming projects.

Content Management Systems – a bad idea?

August 11, 2008 by bozhobg

CMS – Content Management Systems are meant to…manage content. So if we need a generally static content, which should be editable by non-technical persons, it is probably a good idea to use them. Probably.

I’ve had some experience with a number of CMS (Joomla, DotNetNuke for example), and read/tried some more. What do all of them claim to offer – faster development, easier reusing of repeated tasks (registration, news feeds, etc). But let’s review some of the claims, and compare the use of CMS to making a site from scratch:

  • editing by non-technical persons made easy: Without a step-by-step guide a non-technical person would never make it through the complicated menus, buttons. And what most CMSs offer is some ugly javascript editor-enabled textarea, which generates bulky and incorrect (X)HTML. On the other hand, with a similar step-by-step guide, a non-technical person can easily use Dreamweaver to make his pages and link them to menu items.
    • easily reusing repeated tasks: let’s call the pieces of reusable code “modules” (they are often called that way). They should integrate well with both the CMS, and with existing modules. In practicse this is never the case. If at all any integration between modules is to be achieved, a bunch of inconvenient configurations are to be done.  And when at some point you find out that the existing module is not actually working as you want, it becomes a fight with the constraints of the cms. On the other hand, if you have already developed a number of sites, and have developed them well enough, you can reuse your own code (or even someone else’s independent code) knowing perfectly well what the outcomes will be.
    • creating new functionality: as mentioned in the previous point, lot’s of constraint and cms-specific rules are to be observed. They cannot be forced programatically, so you will be lucky if you have a whole list of these constraints and dependencies. Otherwise you should guess each time something doesn’t work. And these constraints and dependencies are not few at all in big CMSs. On the other hand, writing a custom functionality as just plain code, with no configurations, implicit and explicit dependencies seems easier. Of course, it should integrate with the existing system, but this integration is done transparently.

    In all the above point “learning curve” should’ve been included. It takes too much time to master a concrete CMS. And why, when, if you structure you work well, you can achieve even better speed and quality?

    So let’s introduce the term “prepared scratch” – that is, all general stuff like db connections, main configurations, etc, is already prepared, and you start writing your custom dynamic/static pages from that point. Believe me it will turn out to be a lot easier, and will save neurons.

    NetBeans 6.1 – not even 10% a useful IDE

    July 8, 2008 by bozhobg

    I am forced to work with NetBeans (6.1) from time to time. We are creating a Desktop app, and hence NB’s Matisse is a good idea.
    But.. recently I started using only Matisse, and when I finish drawing, go back to Eclipse. Why? Well,

    • NetBeans is becoming rather slow, gets stuck randomly – on copy/paste, on autocomplete, on loading the projects, on pressing a shortcut. Note that my machine is Core2Duo 2.2, 2G of RAM, so not a weak one.
    • indexing of files is obviously not working as it should – when trying to Open Type (CTRL + SHIFT + T, from eclipse shortcuts) half of the classes are just not there. And I have to manully locate them in the project explorer. Furthermore, the suggestions are rather stupid. Classes that appear on the first lines are completely unrealated to the project. (See Eclipse for the better implementation)
    • some stupid caching. I updated a project (we are using 4 separate projects, in order to separate functionality), and then it wouldn’t run. It turned out a jar has been removed by one of my colleages. He added it, and committed. I updated, the project properties file WAS updated, but when I rightclick>properties, the jar isn’t there.
    • refreshing errors – the red dots here and there in the project explorer are not where they should be. They are updated only when one opens the file, and sees that – hey, there are no errors here. Also, today I removed a class, that was reduntant (merely extending some jdk interface). There were places, where the red dots appeared, and I corrected the usages. However, when I tried to run, not much to my surprise actually, the compiler comlained about 2-3 other places, where red dots do not exist. The cool thing is that I’ve been running with such hidden compilation errors for 2 days – obviously they have been cached in the build as well.
    • missing key features. Like on commit, selecting which files to commit and which not. Such basic stuff should not be missing from production-stable IDE. Another thing is that, to my knowledge, they don’t have call and class hierarchies.

    So, in short – NetBeans can NOT be used in production, unless one slowly goes around with the mouse, and uses only 2-3 options.
    No matter how much extras and plug-ins they create, if the base, and most used functionality is working so bad, I doubt NB will soon become a useful IDE.

    I have always wondered why there are developers that seem to like NB very much — are they searching for classes by unfolding packages in the project explorer, or copying using the mouse, or running “Clean” on every base class modification or removal of class?