Monthly Archives: November 2013

Password Security Using KeePass Password Safe (And A Small List Of Similar Software)

Written by William Roush on November 11, 2013 at 6:45 pm

As we use more and more applications online, it becomes more important to be able to stay secure after a data breach at any one of them, last thing we want is to find out one of the sites you subscribe to has had a data breach and uses weak encryption, and a hacker uses that password you’ve reused to gain access to other accounts of yours!

Why Use A Password Generator?

One of the main security recommendations is to use a unique password for every application we have. In my case I’d have to remember over 100 passwords! There are some methods that I’ve seen out there to memorize that many passwords including PasswordCard, but even remembering 100+ combinations of colors/symbols can be difficult. Even when I had rotations of passwords it was hard to remember which sites used which passwords.

Until we move onto something like Public-key authentication (Linux has an option to use this), it is best for us to find a software suite that will assist us in following this very important security guideline.

What Is Keepass?

KeePass is a desktop application (there are mobile versions for Android and iPhone available) that allows you to manage your passwords via a heavily encrypted file. This password can be encrypted using a master password, a keyfile, your Windows account, or any combination of the three. Because your KeePass file is encrypted, you can share it using really simple methods such as storing it on a web server, however I’ve found it best to drop it on something like DropBox or your own cloud using SharePlan or OwnCloud.


Creating a new KeePass database file.

Creating a new KeePass database file.


Managing passwords is a snap, it also comes with an auto-type feature, where you put your cursor in the box on the website, go to KeePass, and click “Perform Auto-Type”.


Right click menu, showing auto-type, editing keys, etc.

Right click menu, showing auto-type, editing keys, etc.


Additionally KeePass will generate very long and complex passwords, you can tweak the password generation options depending on your need (some sites limit you to a maximum length, very annoying when you have a more secure password you’d like to use).


A long range of options for password generation.

A long range of options for password generation.


You can store a lot of relevant data with your KeePass passwords, don’t ever forget a username again (for those pesky sites that don’t use your e-mail address)!


New password screen, showing a very complex password length you couldn't memorize.

New password screen, showing a very complex password length you couldn’t memorize.


Other Options

LastPass / RoboForm / 1Password / Dashline

All of the above applications follow the same general idea: store your passwords on the public cloud. They typically have better integration with browsers to auto-fill form fields (KeePass can get “confused” at times due to form layout, and not fill it out properly). Additionally you don’t run the risk of losing your passwords because you lost your KDBX file, and the sharing of your passwords between your multiple devices is simplified.

Software like LastPass offer local-only decryption, which I find is a requirement before I even consider a cloud offering. However LastPass has had a data breach before that resulted in all master passwords needing to be reset, so it’s hard to gauge how secure the system can be when everything is hinging on your master password that you regularly communicate to LastPass with.

PasswordState

PasswordState is a web based application that provides similar features to the above systems, but for a corporate environment on a private cloud, where password lists may need to be shared or be able to be transferred in the event of a staff member leaving. On top of that you’d want a full audit log of users looking up passwords, and PasswordState provides all of this in a slick interface. This doesn’t seem to have the nice accessibility tools for mobile devices that some of the offerings above have, but the price is cheap (free for up to 5 users, and ~$400USD will cover 10 users for a year, with support being ~$70USD) and for stuff like corporate passwords I strongly recommend private cloud solutions, especially where the sharing of passwords between multiple accounts makes it easier for outsiders to crack into it.

Tamper-proof Licensing Using Cryptographic Signatures

Written by William Roush on November 4, 2013 at 9:15 pm

I’m going to dive right into writing a basic licensing system using strong established cryptographical signing processes to prevent tampering or the creation of a key generator. I’m going to digitally sign the plain-text license using OpenPGP’s private key, this will generate a human readable license file, but modifying the payload will cause an exception to be thrown and tampering detected.

Solutions

I’m going to go over the basic options available. There are many others and there are a lot of hybrids of these various types, but for a quick introduction to licensing options, this should get you up to speed.

No Licensing

Of course the option for no licensing is always available. This provides no protection against a user copying your application and giving it to another user. Sometimes the overhead of writing and maintaining licensing code may not be worth the effort.

Plaintext Keys

Plaintext keys store user information, dates, times and keys in various locations, such as files on the hard disk, registry keys or resource files. These are fairly trivial to change and circumvention information can be passed around by word of mouth. You can attempt to store keys in hidden places like some other software, but these can and likely will be tracked down, and depending on if your method is ethically unsound, can land you unfavorable opinion with your would-be customers.

These are very easy, and can be a preferred choice if you’re not concerned with someone attempting to crack your licensing code, but may want some features granted by having licensing support in your software.

Symmetrical Cryptography / Hash Verification

Both of these methods fall under the same pros/cons for the most part. Symmetrical keys will encrypt the entire license file and should use some sort of secure algorithm (ex: AES256) with a secret key. Hash verification may store the data encrypted or unencrypted, but will hash the key information either with a secret method or a secret salt and store that with the license file, where you can validate that it hasn’t been tampered with, tampered keys fail validation.

Both of these suffer from the same issue: the code to decrypt/hash and verify your license files provide all the information needed to encrypt/hash new license files, allowing someone to create a license generator. In other languages these is a higher barrier of entry to be able to reverse engineer a native library, but in .NET your code can be fairly easily decompiled and methods like this reverse engineered (generally even when obfuscated).

Asymmetrical Cryptography

Asymmetrical cryptography, also known as Public-key cryptography is a method of encrypting data using the public key, and only being able to decrypt it with the private key (this can also be used for verification purposes by reversing the usage of the keys). In our example, we’ll use the example of digital signatures: where we use the private key for signing the license, and the public key to verify it hasn’t been tampered with.

Without the private key, a user cannot issue new licenses, a key generator will be impossible to make without one. The best bet resides in the malicious person to take one of two paths: to modify the software to remove the license requirement entirely, or modify the software to use a different public key, so they can use their own private key to generate licenses.

We’re on a better path now: a malicious user that has to patch our binaries to circumvent licensing will incur the overhead of having to patch every binary we release, while we can’t ever stop circumvention, we can make it annoying!

Online Verification

Online verification is one of the hardest methods, if not the hardest to circumvent. However a lot has to be assumed about your customers. You need to assume your users will be online at regular intervals, additional the use of software they’ve purchased will be entirely dependent on you keeping your licensing servers up and running.

Circumvention requires you to rewrite binaries to no longer check online, or spoof authentication servers.

PGP and You

I’m going to useĀ OpenPGP, an open encryption standard that includes public-key cryptography. This library is used a lot for signing/encrypting e-mails and code among various programming groups, and I’ll continue to use this later for various examples such as signing code in a later blog.

Generating Your Key Pair

I recommend using GPG4Win, an easy to use application for creating and managing GPG and X509 certificates.

Select "File" > "New Certificate"

Select “File” > “New Certificate”

We want to create an OpenPGP key pair.

We want to create an OpenPGP key pair.

Enter the certificate information.

Enter the certificate information.

Your private key is the key to your kingdom, use a strong passphrase.

You want to save the private key (*.gpg) somewhere where your application can access it.

You want to save the private key (*.gpg) somewhere where your application can access it.

You'll want to export the public key too.

You’ll want to export the public key too.

Dealing with PGP On .NET

I’m going to use a very commonly used cryptography library for .NET BouncyCastle, mainly because it’s extremely powerful and licensed under MIT a very open license friendly to both open source projects and closed source.

An Example License File

We’re going to go ahead with the most basic setup: we’re not going to encrypt the payload so we can understand what is going on, for further obscurity you can encrypt the payload or even the entire license, but it wont add much additional security (just make it harder to understand what is going on till they decompile your .NET code).

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

William Roush
1/1/2018 12:00:00 AM
1/1/2014 12:00:00 AM
-----BEGIN PGP SIGNATURE-----
Version: BCPG C# v1.7.4114.6375

iQFYBAABAgBCBQJSdv5OOxxSb3VzaFRlY2ggRXhhbXBsZSBDb2RlIFNpZ25pbmcg
S2V5IDxleGFtcGxlQHJvdXNodGVjaC5uZXQ+AAoJEGyAwS0mpw1Ki5MH/jQAKiur
FF06Q7D0BeaUE6eBk40I2LocZwSE2Osx94Tdux08L8vpaOUG4xBx6UsNKusvrbaV
hSxeU1e1LkO3QMu8+//FAFsJizTYjYZRoRe167WFRlQbteZdgeB1S+HMdDhsBs+Z
3+FGAulhs7EBmRkgSoYEX0NdJc1uEfW5kRr4KfL4v+m9UU6Z796KWFzOi8xqTcRG
eO9cNV7QtAzBOpI2CVuq6KuGj5VjNtQsxUrUNl6U/giV61Y5TYOfRnL47kX4U6sf
Uzp/iRZqemi+n7iBjMsO37+baANySaBRSKUG0EXtQM9sVxHZ7aGoXpjsU+oeWtBY
iWPAPX1ePwQ6LcM=
=57ao
-----END PGP SIGNATURE-----

Writing Your License File Management Code

First I’m going to outline some basics, we’re going to store a name and two dates, a software expiration date and a support expiration date. Additionally I’ll override ToString() for testing purposes, and write a method that returns the license data as a byte array that’ll go into our signed license file.

using System;
using System.IO;
using System.Linq;
using System.Text;

using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Security;

public class License
{
    public string Name { get; set; }
    public DateTime SoftwareExpires { get; set; }
    public DateTime SupportExpires { get; set; }

    protected PgpPrivateKey PrivateKey { get; set; }
    public PgpPublicKey PublicKey { get; set; }

    public override string ToString()
    {
        return string.Format("Name: {1}{0}Software Expires: {2}{0}Support Expires: {3}",
            Environment.NewLine,
            this.Name,
            this.SoftwareExpires,
            this.SupportExpires
        );
    }

    private byte[] PrepareLicenseForStorage()
    {
        var licenseData = string.Format(
            "{0}\n{1}\n{2}",
            this.Name,
            this.SoftwareExpires.ToString(),
            this.SupportExpires.ToString()
        );

        return Encoding.UTF8.GetBytes(licenseData);
    }

Next we’re going to define how to read a public key out of a file.

public void ReadPublicKey(string path)
{
    using (var keyFileStream = File.OpenRead(path))
    using (var pgpDecoderStream = PgpUtilities.GetDecoderStream(keyFileStream))
    {
        var keyRingBundle = new PgpPublicKeyRingBundle(pgpDecoderStream);
        var keyRings = keyRingBundle.GetKeyRings();
        foreach (PgpPublicKeyRing keyRing in keyRings)
        {
            this.PublicKey = keyRing.GetPublicKey();
            break;
        }
    }
}

Then we’re going to define how to read a private key out of a file.

public void ReadPrivateKey(string path)
{
    using (var keyFileStream = File.OpenRead(path))
    using (var pgpDecoderStream = PgpUtilities.GetDecoderStream(keyFileStream))
    {
        // Get the key ring from the private key file.
        var keyRingBundle = new PgpSecretKeyRingBundle(pgpDecoderStream);
        var keyRings = keyRingBundle.GetKeyRings();

        // Get the first key from the key ring (it's an enumerable, so it's annoying).
        PgpSecretKey secretKey = null;
        foreach(PgpSecretKeyRing keyRing in keyRings)
        {
            secretKey = (PgpSecretKey)keyRing.GetSecretKey();
            break;
        }

        // Get the private key, we don't have a pass phrase on this (you should though!). 
        // Do NOT hard code this into the library, take it as a parameter from your key generation
        // software.
        this.PrivateKey = secretKey.ExtractPrivateKey("".ToCharArray());
    }
}

Next we’re going to define the code for creating a license file.

public void CreateLicenseFile(string fileName)
{
    var hashAlgorithm = HashAlgorithmTag.Sha1;
    using (var fileWriter = new FileStream(fileName, FileMode.Create))
    using (var outputStream = new ArmoredOutputStream(fileWriter))
    {
        // Continue our signature.
        var signatureGenerator = new PgpSignatureGenerator(this.PublicKey.Algorithm, hashAlgorithm);
        signatureGenerator.InitSign(PgpSignature.BinaryDocument, this.PrivateKey);
        foreach (string userId in this.PublicKey.GetUserIds())
        {
            var pgpSigatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
            pgpSigatureSubpacketGenerator.SetSignerUserId(false, userId);
            signatureGenerator.SetHashedSubpackets(pgpSigatureSubpacketGenerator.Generate());
            break;
        }

        var licenseDataBuffer = this.PrepareLicenseForStorage();

        // We're going to write out the cleartext portion.
        outputStream.BeginClearText(hashAlgorithm);
        outputStream.Write(licenseDataBuffer, 0, licenseDataBuffer.Length);

        // This updates our signature with the data in our license.
        signatureGenerator.Update(licenseDataBuffer, 0, licenseDataBuffer.Length);
        outputStream.EndClearText();

        // Add newline after text so we start the PGP signature header on the next line.
        byte[] newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
        fileWriter.Write(newLineBytes, 0, newLineBytes.Length);

        // Outputs the signature into the file.
        using (var bcpgStream = new BcpgOutputStream(outputStream))
        {
            signatureGenerator.Generate().Encode(bcpgStream);
        }
    }
}

Finally, we need to be able to create a license object from a signed license file.

public static License LoadLicenseFromFile(string fileName, PgpPublicKey publicKey)
{
    using (var inputStream = new FileStream(fileName, FileMode.Open))
    using (var armoredStream = new ArmoredInputStream(inputStream))
    using (var memoryStream = new MemoryStream())
    {
        // We're going to read the payload of the signed text in.
        while (armoredStream.IsClearText())
        {
            memoryStream.WriteByte((byte)armoredStream.ReadByte());
        }
        
        // Load the signature data from the armored file and initalize it with the public key.
        PgpObjectFactory pgpFact = new PgpObjectFactory(armoredStream);
        PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();
        PgpSignature sig = p3[0];
        sig.InitVerify(publicKey);

        // We're going to seek to the beginning, and strip off the final "/r/n-" from the message.
        memoryStream.Seek(0, SeekOrigin.Begin);
        for (int i = 0; i < memoryStream.Length - 3; i++)
        {
            sig.Update((byte)memoryStream.ReadByte());
        }
        
        if (!sig.Verify())
        {
            throw new Exception("Verification Failed")
        }

        // Parse our stored license data.
        string[] licenseData = Encoding.UTF8.GetString(memoryStream.ToArray()).Split('\n');
        return new License
        {
            Name = licenseData[0],
            SoftwareExpires = DateTime.Parse(licenseData[1]),
            SupportExpires = DateTime.Parse(licenseData[2])
        };   
    }
}

From here we have the underlying infrastructure needed to write a license file that cannot be tampered with and that our application can verify is correct.

Changes To Production Code

First in production you’ll never want to ship your licensing software with your private key or with your secret phrase, that stays with you for generating new keys. Secondly we’ll want to read the private key from some internal resource so a malicious hacker can’t just replace your public key file without modifying binaries.