Páginas

Saturday, July 24, 2010

Change the password on someone else's Mac OS

Every modern OS has a mode that grants you superuser permissions, without the need for a password. This mode is supposed to be used to run tasks that require exclusive access to shared resources or if you lost your password, for example.

The only reason this mode exists is because these OS's are seen as multiuser and the environment in which the computer is set should be a friendly one. Nevertheless this mode, the single user mode, can be used for some very nasty things if you now your BASH (or the existing shell) basics. Here we're going to change the root password.

First, you have to turn the computer off, because this mode is entered at boot time. While the system is booting keep cmd+S pressed, until a console appears. When it does, you're good to go. Just mount the file system with mount -wu /.

Now for the final step, type passwd and return. You should be asked to enter the new root password twice. Once that's done, you have successfully gained root rights to the OS. Reboot it and try it out!

If you want to be "protected" from this, you can install SecureIt, that requests you to enter a password before showing the console, when booting.

Notes:
  1. You cannot enter single user or verbose mode if the computer owner or administrator has enabled Open Firmware Password Protection.
  2. When in single-user mode, the keyboard layout is US English.
  3. In Linux systems you have to change the configuration of the booter, can be easily done
  4. In Windows there's the Safe Mode

Friday, July 23, 2010

Java static blocks

During the course of the year I found out about a very interesting thing in Java, the static blocks. Java has a special word for variables that are initialized once per class, instead of once per instance of the class. That word is static.

static int class_variable = 0;

This way, all the instances of the class share this variable (this also means you have to be careful about concurrency control). Now, what if you want to do this with a Collection, instead of a primitive type?

That's where static blocks come in handy. Imagine we have this:

static HashMap<Integer,String> sharedHash = new HashMap<Integer,String>();

What we want now is to populate the HashMap, either from hardcoded values or a function that does the job. The solution is simple, a static block!

static
{
    sharedHash.put(1,"one");
    this.populateHash(sharedHash);
}

This populates the HashMap only once, and only when the first instance of the class is created, saving a lot of unnecessary processing and memory usage.

Using HERE documents to do repetitive programming

In recent work I had to write Factories for a lot of classes in diferent packages, these factories all had the same general format and so, because it would be really boring to code this by hand, I wrote a little script that takes advantage of HERE documents. There were two types of files, the interfaces and the actual implementations, recognized by having the Impl sufix.

The first thing is to get the paths of the interfaces, we do this with an inverted grep:

for path in $(find . -type f | grep -v Impl)

Then we get the path to directory, excluding the name of the actual file:

factoryPath=${path%/*.java}

After that we get the file name:

javaFile=${path##*/}

and the class name (the name of the file without the .java)

className=${javaFile%.java}

We now have all the basic blocks needed to build our script. From now on it's just a matter of how to combine them. From the class name we get the factory file name:

factoryFile=${className}Factory.java

The package name for the interfaces is the factoryPath variable, but changing the / for .

packageName=$(echo ${factoryPath##./} | tr '/' '.')

and the one for the actual implementation is:

packageImpl=${packageName}.impl

The next step is to create the file we are going to write into:

touch ${factoryPath}/impl/${factoryFile}

And finally let's write the file using the HERE document:

cat >${factoryPath}/impl/${factoryFile} <<HERE
package ${packageImpl};  
  

import ${packageName}.${className};
import tsl.jaxb.${className}XMLImpl;    
  
public class ${className}Factory {
    public static ${className} getInstance(String instance)

    {
        if(instance.equals("XML"))
            return new ${className}XMLImpl();
        if(instance.equals("DER"))

            return new ${className}DERImpl();
  
        return null;
    }
}  

HERE

DER Signing using Java and Bouncy Castle

Following my last post about DER coding in Java, I will now explain how to sign an object, using java.security.PrivateKey, java.security.cert.X509Certificate and the TSL standard as pointed in that post.

The TSL signature is an enveloped signature, that can be described by the following picture:


First let's assume that we have some previously initialized variables:
  • tslDER - Unsigned TSL object (instance of DEREncodable)
  • privateKey - Private key being used to sign
  • cert - PKI Certificate of the signer (this one is optional, but recommended)
Now let's define the algorithms used for signing and message digesting:

AlgorithmIdentifier sigAlg = new AlgorithmIdentifier(ObjectIdentifiers.getAlgorithmOID(sigAlgorithm));
ASN1Set sigAlgs = new DERSet(sigAlg);
AlgorithmIdentifier digestAlg = new AlgorithmIdentifier(ObjectIdentifiers.getAlgorithmOID(digestAlgorithm));
ASN1Set digestAlgs = new DERSet(digestAlg);


The getAlgorithmOID is a method that given a String returns the matching Object Identifier or throws an Exception.

After that, let's define the identification of the signer:

SignerIdentifier sid = null;
String[] names = cert.getIssuerDN().getName().split(",");

ASN1EncodableVector vec = new ASN1EncodableVector();
for (String name : names)
{
    ASN1EncodableVector nameVec = new ASN1EncodableVector();
    String[] vals = name.split("=");
    nameVec.add((DEREncodable) X509Name.DefaultLookUp.get(vals[0].trim().toLowerCase()));
    nameVec.add(new DERPrintableString(vals[1]));
    vec.add(new DERSequence(nameVec));
}

ASN1Set attr = new DERSet(vec);
X509Name issuer = new X509Name(new DERSequence(attr));
sid = new SignerIdentifier(new IssuerAndSerialNumber(issuer, cert.getSerialNumber()));


Now the encapsulated content info:

ContentInfo encapContent = new ContentInfo(ObjectIdentifiers.id_eContentType_signedTSL, tslDER);

The next step is building the byte array to be signed:


MessageDigest md = MessageDigest.getInstance(digestAlgorithm);
md.reset();
md.update(tslDER.getDERObject().getEncoded());

ASN1EncodableVector attrs = new ASN1EncodableVector();

ASN1EncodableVector contentTypeAttr = new ASN1EncodableVector();
contentTypeAttr.add(ObjectIdentifiers.id_contentType);
contentTypeAttr.add(ObjectIdentifiers.id_eContentType_signedTSL);
attrs.add(new DERSequence(contentTypeAttr));

ASN1EncodableVector messageDigestAttr = new ASN1EncodableVector();
messageDigestAttr.add(ObjectIdentifiers.id_messageDigest);
messageDigestAttr.add(new DEROctetString(md.digest()));
attrs.add(new DERSequence(messageDigestAttr));

ASN1Set signedAttr = new DERSet(attrs);

md.reset();
md.update(tslDER.getDERObject().getDEREncoded());
md.update(signedAttr.getDEREncoded());
byte[] data = md.digest();


And to finalize the signature:


Signature sig = Signature.getInstance(sigAlgorithm);
sig.initSign(privateKey);
sig.update(data);
byte[] signed = sig.sign();

SignerInfo signerInfo = new SignerInfo(sid, digestAlg, signedAttr, sigAlg, new DEROctetString(signed), null);
ASN1Set signerInfos = new DERSet(signerInfo);

ASN1Set certs = new DERSet(new DEROctetString(cert.getEncoded()));

SignedData signedData = new SignedData(digestAlgs, encapContent, certs, null, signerInfos);
ContentInfo content = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);

DER using Java and Bouncy Castle

In the last few months I have been working with Distinguished Encoding Rules (DER) of ASN.1 a standard placed by X.509, used in cryptography. I needed to code this in Java, for which I chose to use the Bouncy Castle ASN.1 library.

DER has some primitives that let's you define the various structures and types needed for your endeavors. Here are some:
  • Sequence
  • Choice
  • IA5String
  • PrintableString
  • Integer
  • Object Identifier
  • GeneralizedTime
  • Boolean
  • OctetString
Any of these types can be marked as OPTIONAL and have a tag, in the form [n].

As an example I shall use the Trust-service Status List ETSI TS 102 231 V3.1.2 standard specification.

A sequence:

LangPointer ::= SEQUENCE {
  languageTag LanguageTag,
  uRI         NonEmptyURI
  } 


Encoding:

ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(LanguageTag);
vec.add(NonEmptyURI);
DERSequence seq = new DERSequence(vec);


Decoding:


DEREncodable obj = ...;
DERSequence tslscheme = (DERSequence) obj;
Enumeration e = tslscheme.getObjects();
LanguageTag lt = (LanguageTag) e.nextElement();


A choice:

TSLpolicy ::= CHOICE {
 pointer [0] MultiLangPointer,
 text [1] MultiLangString
}


Encoding (using a sequence):


if(multiLangPointer != null)
    vec.add(new DERTaggedObject(0, MultiLangPointer));
else if(multiLangString !=null)
    vec.add(new DERTaggedObject(1, MultiLangString));


Decoding:


while(e.hasMoreElements())
{
    DERTaggedObject tagged = (DERTaggedObject) e.nextElement();
    switch (tagged.getTagNo())
    {
        case 0: multiLangPointer = tagged.getObject(); break;
        case 1: multiLangString = tagged.getObject(); break;
    }
}


The primitive types are all encoded and decoded in a similar way, the only thing changing being the name, therefore I will only give one example:

NonEmptyURI ::= IA5String (SIZE (1..MAX))

Encoding:

DERIA5String neuri = new DERIA5String(String);

Decoding (in a sequence):

DERIA5String neuri = (DERIA5String) e.nextElement();
String str = type.getString();


A little bit trickier is casting a DERGeneralizedTime to a GregorianCalendar, but here's how you do it:

DERGeneralizedTime issueTime = (DERGeneralizedTime) e.nextElement();
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddkkmmss");
GregorianCalendar greg = new GregorianCalendar();
greg.setTime(f.parse(issueTime.getTimeString()));


The date format can be changed as you see fit, to do what you need.

The last thing are the OPTIONALS, that are very much like a CHOICE, except that there can be more than one at the same time. Even though, the encoding and decoding are done in the same way, using DERTaggedObjects.

To write and read from DER encoded files, you can use ASN1Streams, initialized like this:

ASN1InputStream ain = new ASN1InputStream(new DataInputStream(new BufferedInputStream(new FileInputStream(new File(file)))));

First post

As the blog's title suggest I will be writing about the things that I find interesting. May they come to my awareness through work, fun or chance, either way I hope this is as interesting to read as it sure will be to write.

I leave you now with two quotes that I relate two, being distributed systems and cryptography my main areas of interest.

We reject kings, presidents and voting. We believe in rough consensus and running code.

ETF Credo. David Clark (MIT).


Encryption...is a powerful defensive weapon for free people. It offers a technical guarantee of privacy, regardless of who is running the government... It's hard to think of a more powerful, less dangerous tool for liberty.

Esther Dyson, EFF.


This being said, I'll to write something of substance tomorrow.