Hacking Prototypal Inheritance for Fun and Profit

Written by Pete Corey on Jan 29, 2018.

Every object in Javascript is built on top of a “prototype”. A prototype can either be either another object, or null. When an object’s prototype is another object, the first object can inherit fields from the second.

This type of prototypal inheritance is well-accepted and relatively well understood by most Javascript developers, but there are dangerous implications behind this kind of inheritance model.

Let’s dive into how we can hack prototypal inheritance for fun and profit!

How are Prototypes Created?

A Javascript object’s prototype is referenced through the hidden __proto__ field. This field can be found on every object in an application. The __proto__ field can either point to another object, or null if the current object has no prototype.

The two options for an object's prototype.

The prototype of an object can explicitly be set using Object.create, and passing in your desired prototype.


let p = { foo: 123 };
let a = Object.create(p);
let b = Object.create(null);

In this example, our new a object inherits the foo field from the p object being used as its prototype. Our new b object has no prototype, and inherits no fields.

Our two new objects and their prototype chains.

The prototype of an object can also be manually set through the __proto__ field:


let c = {};
c.__proto__ = { bar: 234 };

In this case, we replace the reference to c’s original prototype with a reference to a new object. We can now access the inherited bar field through c.

It's objects all the way down.

By default, all Javascript objects created through the literal notion point to Object.prototype as their prototype. Object.prototype is an object that holds helper functions like constructor, hasOwnProperty, and toString. Additionally, Object.prototype has a prototype of null.

This means that in addition to the bar field, our c object also has access to everything living in Object.prototype via its prototype’s prototype!

Setting the Scene

Armed with this information, let’s think about how we can exploit a simple (read: contrived) Node.js application.

Let’s assume that we’re building an application using an Express-like framework. We’ve created one endpoint to update values in an in-memory key-value store:


const store = {
    cats: "rule",
    dogs: "drool"
};

app.post('/update/:key/:value', function(req, res) {
    let { key, value } = req.params;
    res.send(_.set(store, key, value));
});

The /update route is used to update our store with various facts. This route is unauthorized as its intended to be used by unauthenticated clients.


We have another route, /restricted, that’s only intended to be used by authenticated, authorized users:


app.post('/restricted', function(req, res) {
    let user = getUser(req);
    if (!user || !user.isAdmin) {
        throw new Error("Not authorized!");
    }
    res.send("Permission granted!");
});

Let’s assume that the getUser function returns a user object based on a session token provided through req. Let’s also assume that the isAdmin field is set to true on administrator user objects, and unset on non-administrator user objects.

Hacking the Prototype

Now that the scene is set, imagine that we’re a normal, non-administrator, user of this application, and we want access to the /restricted endpoint.

Our calls to /restricted return a "Not authorized!" exception because our user object returned by getUser doesn’t have an isAdmin field. With no way of updating our admin flag, it seems we’re stuck.

Or are we?

Thankfully, our recent reading on prototypal inheritance has given us a flash of malevolent insight!

The /update endpoint is using Lodash’s _.set function to update the value of any field in our store, including nested fields. We can use this to our advantage. We quickly make a call to /update with a key of "__proto__.isAdmin", and a value of "true" (or any other truthy value), and try our restricted endpoint again:


Permission granted!

Victory! We’ve given ourself access to a restricted endpoint by modifying an arbitrary object within our Javascript application!

But how did we do it?

Explaining the Magic

As we mentioned earlier, unless specifically created with a different prototype, all objects reference Object.prototype as their prototype. More specifically, all objects in an application share the same reference to the same instance of Object.prototype in memory.

If we can modify Object.prototype, we can effectively modify the fields inherited by all of the objects in our application.

Our request to the /update endpoint, with a key of "__proto__.isAdmin", and a value of "true" effectively turned into this expression on our server:


_.set(store, "__proto__.isAdmin", "true")

This expression reaches into Object.prototype through the __proto__ field of our store and creates a new isAdmin field on that object with a value of "true". This change has far reaching consequences.

Everything is an admin!

After we update our “store”, every object that exists in our application now inherits an isAdmin field with a value of "true". This means that on retrieving our user object from getUser, it looks something like this:


{
  _id: 123,
  name: 'Pete',
  __proto__: {
    isAdmin: 'true',
    constructor: ...,
    hasOwnProperty: ...,
    toString: ...,
    ...
    __proto__: null
  }
}

Because our base user object has no isAdmin field, trying to access isAdmin on this object results in the isAdmin field from our underlying Object.prototype object to be returned. Object.prototype returns a value of "true", causing our server’s permission check to pass, and giving us access to juicy, restricted functionality.

In Reality

Obviously, this a fairly contrived example. In the real world, this type of vulnerability wouldn’t present itself in such a simple way. That said, this vulnerability does exist in the real world. When it rears its head, it’s often incredibly ugly. Adding unexpected fields to every object in your system can lead to disastrous results.

For example, imagine a vulnerability like this existing in a Meteor application. Once the underlying Object.prototype is updated with superfluous fields, our entire applications falls to pieces. Any queries made against our MongoDB collections fail catastrophically:

Exception while invoking method 'restricted' MongoError: 
  Failed to parse: { 
    find: "users", 
    filter: { 
      _id: "NktioYhaJMuKhbWQw", 
      isAdmin: "true" 
    }, 
    limit: 1, 
    isAdmin: "true" 
  }. Unrecognized field 'isAdmin'.

MongoDB fails to parse our query object with the added isAdmin fields, and throws an exception. Without being able to query our database, our application is dead in the water.

Fixing the Vulnerability & Final Thoughts

The fundamental fix for this issue is incredibly simple. Don’t trust user-provided data.

If a user is allowed to update a field on an object (or especially a nested field in an object), always whitelist the specific fields they’re allowed to touch. Never use user-provided data in a way that can deeply modify an object (any object) on the server.

If you’re interested in this kind of thing, I encourage you to check out my latest project, Secure Meteor! It’s an in-the-works guide designed to help you secure your past, present, and future Meteor applications. As a token of thanks for signing up, I’ll also send you a free Meteor security checklist!

Generating Bitcoin Private Keys and Public Addresses with Elixir

Written by Pete Corey on Jan 22, 2018.

Lately I’ve been working my way through Mastering Bitcoin, implementing as many of the examples in the book in Elixir as I can.

I’ve been amazed at how well Elixir has fared with implementing the algorithms involved in working with Bitcoin keys and addresses. Elixir ships with all the tools required to generate a cryptographically secure private key and transform it into a public address string.

Let’s walk through the process step by step and build our our own Elixir module to generate private keys and public addresses.

What are Private Keys and Public Addresses?

A Bitcoin private key is really just a random two hundred fifty six bit number. As the name implies, this number is intended to be kept private.

From each private key, a public-facing Bitcoin address can be generated. Bitcoin can be sent to this public address by anyone in the world. However, only the keeper of the private key can produce a signature that allows them to access the Bitcoin stored there.

Let’s use Elixir to generate a cryptographically secure private key and then generate its most basic corresponding public address so we can receive some Bitcoin!

Pulling a Private Key Out of Thin Air

As I mentioned earlier, a Bitcoin private key is really just a random two hundred and fifty six bit number. In other words, a private key can be any number between 0 and 2^256.

However, not all random numbers are created equally. We need to be sure that we’re generating our random number from a cryptographically secure source of entropy. Thankfully, Elixir exposes Erlang’s :crypto.strong_rand_bytes/1 function which lets us easily generate a list of truly random bytes.

Let’s use :crypto.strong_rand_bytes/1 as the basis for our private key generator. We’ll start by creating a new PrivateKey module and a generate/0 function that takes no arguments:


defmodule PrivateKey do
  def generate
end

Inside our generate/0 function, we’ll request 32 random bytes (or 256 bits) from :crypto.strong_rand_bytes/1:


def generate do
  :crypto.strong_rand_bytes(32)
end

This gives us a random set of 32 bytes that, when viewed as an unsigned integer, ranges between 0 and 2^256 - 1.

Unfortunately, we’re not quite done.

Validating our Private Key

To ensure that our private key is difficult to guess, the Standards for Efficient Cryptography Group recommends that we pick a private key between the number 1 and a number slightly smaller than 1.158e77:

An excerpt of the SECG guidelines.

We can add this validation check fairly easily by adding the SECG-provided upper bound as an attribute to our PrivateKey module:


@n :binary.decode_unsigned(<<
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
  0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
  0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
>>)

Next, we’ll add a valid?/1 function to our module that returns true if the provided secret key falls within this range, and false if it does not:


defp valid?(key) when key > 1 and key < @n, do: true
defp valid?(_), do: false

Before we pass our private key into our valid?/1 function, we’ll need to convert it from a thirty two byte binary into an unsigned integer. Let’s add a third valid?/1 function head that does just that:


defp valid?(key) when is_binary(key) do
  key
  |> :binary.decode_unsigned
  |> valid?
end

We’ll finish off our validation by passing our generated private key into our new valid?/1 function. If the key is valid, we’ll return it. Otherwise, we’ll generate a new private key and try again:


def generate do
  private_key = :crypto.strong_rand_bytes(32)
  case valid?(private_key) do
    true  -> private_key
    false -> generate
  end
end

Now we can call PrivateKey.generate to generate a new Bitcoin private key!

From Private Key to Public Key …

The most basic process for turning a Bitcoin private key into a sharable public address involves three basic steps. The first step is to transform our private key into a public key with the help of elliptic curve cryptography.

We’ll start by adding a new to_public_key/1 function to our PrivateKey module:


def to_public_key(private_key)

In our to_public_key/1 function, we’ll use Erlang’s :crypto.generate_key function to sign our private_key using an elliptic curve. We’ll specifically use the :secp256k1 curve:


:crypto.generate_key(:ecdh, :crypto.ec_curve(:secp256k1), private_key)

We’re using the elliptic curve key generation as a trapdoor function to ensure our private key’s secrecy. It’s easy for us to generate our public key from our private key, but reversing the computation and generating our private key from our public key is nearly impossible.

The :crypto.generate_key function returns a two-element tuple. The first element in this tuple is our Bitcoin public key. We’ll pull it out using Elixir’s elem/1 function:


:crypto.generate_key(:ecdh, :crypto.ec_curve(:secp256k1), private_key)
|> elem(0)

The returned value is a sixty five byte binary representing our public key!

… Public Key to Public Hash …

Once we have our public key in memory, our next step in transforming it into a public address is to hash it. This gives us what’s called the “public hash” of our public key.

Let’s make a new function, to_public_hash/1 that takes our private_key as an argument:


def to_public_hash(private_key)

We’ll start the hashing process by turning our private_key into a public key with a call to to_public_key:


private_key
|> to_public_key

Next, we pipe our public key through two hashing functions: SHA-256, followed by RIPEMD-160:


private_key
|> to_public_key
|> hash(:sha256)
|> hash(:ripemd160)

Bitcoin uses the RIPEMD-160 hashing algorithm because it produces a short hash. The intermediate SHA-256 hashing is used to prevent insecurities through unexpected interactions between our elliptic curve signing algorithm and the RIPEMD algorithm.

In this example, hash/1 is a helper function that wraps Erlang’s :crypto.hash.


defp hash(data, algorithm), do: :crypto.hash(algorithm, data)

Flipping the arguments to :crypto.hash in this way lets us easily pipe our data through the hash/1 helper.

… And Public Hash to Public Address

Lastly, we can convert our public hash into a full-fledged Bitcoin address by Base58Check encoding the hash with a version byte corresponding to the network where we’re using the address.

Let’s add a to_public_address/2 function to our PrivateKey module:


def to_public_address(private_key, version \\ <<0x00>>)

The to_public_address/2 function takes a private_key and a version byte as its arguments. The version defaults to <<0x00>>, indicating that this address will be used on the live Bitcoin network.

To create a Bitcoin address, we start by converting our private_key into a public hash with a call to to_public_hash/1:


private_key
|> to_public_hash

All that’s left to do is Base58Check encode the resulting hash with the provided version byte:


private_key
|> to_public_hash
|> Base58Check.encode(version)

After laying the groundwork, the final pieces of the puzzle effortlessly fall into place.

Putting Our Creation to Use

Now that we can generate cryptographically secure private keys and transform them into publishable public addresses, we’re in business.

Literally!

Let’s generate a new private key, transform it into its corresponding public address, and try out on the Bitcoin testnet. We’ll start by generating our private key:


private_key = PrivateKey.generate

This gives us a thirty two byte binary. If we wanted, we could Base58Check encode this with a testnet version byte of 0xEF. This is known as the “Wallet Import Format”, or WIF, of our Bitcoin private key:


Base58Check.encode(private_key, <<0xEF>>)

As its name suggests, converting our private key into a WIF allows us to easily import it into most Bitcoin wallet software:

Importing our test private key.

Next, let’s convert our private key into a testnet public address using a version byte of 0x6F:


PrivateKey.to_public_address(private_key, <<0x6F>>)

Now that we have our public address, let’s find a testnet faucet and send a few tBTC to our newly generated address! After initiating the transaction with our faucet, we should see our Bitcoin arrive at our address on either a blockchain explorer, or within our wallet software.

Our tBTC has arrived.

Victory!

Final Thoughts

Elixir, thanks to its Erlang heritage, ships with a wealth of tools that make this kind of hashing, signing, and byte mashing a walk in the park.

I encourage you to check our the PrivateKey module on Github to get a better feel for the simplicity of the code we wrote today. Overall, I’m very happy with the result.

If you enjoyed this article, I highly recommend you check out the Mastering Bitcoin book. If you really enjoyed this article, feel free to send a few Bitcoin to this address I generated using our new PrivateKey module:


1HKz4XU7ENT46ztEzsT83jRezyiDjvnBV8

Stay tuned for more Bitcoin-related content as I work my way through Mastering Bitcoin!

Secure Meteor

Written by Pete Corey on Jan 15, 2018.

For the past three years, I’ve been writing and speaking about Meteor security, building and deploying secure Meteor applications, working with amazing teams to better secure their applications, and building security-focused packages and tools for the Meteor ecosystem.

Needless to say, I’ve learned a lot over that time.

I’m excited to announce that I’ve started work on a new project called Secure Meteor in an attempt to capture and distill everything I know about Meteor security into an easily understandable, actionable guide to building secure Meteor applications.

Secure Meteor is still very much in its early days, so there’s not much to share yet. That said, as a teaser and a token of thanks for showing interest in the project, I want to give you the most detailed Meteor security checklist available anywhere, for free!

Be sure to sign up to receive your free security checklist, and let me know what you’d like to see in the project.