Data Security is Expensive, Negligence is Cheap

uber hack

Screw you Uber. You assholes raised 15 billion dollars, invest in some decent security already.

Apparently Uber got “hacked” in early 2014, and it took them over two years to figure out what all got stolen. As a result, they’re only sending this letter to me now.

I apply the term “hack” quite loosely: Uber employees left a login key in a public file on GitHub, and someone found the key and used it to access Uber’s database. “Hack” is a blame-deflecting way of saying Our engineers are morons and someone took advantage of that. If I leave my iPhone on the sidewalk and it gets swiped, is that a “hack” too?

In response to this data breach, the NY Attorney General already fined Uber $20,000. Okay that’s not a fine, that’s a line item in the petty cash daybook. Eric Schneiderman just set a price cap on negligence.

Corporations have little incentive to invest in data security. Really, there are 20 million companies in this country. What’s the likelihood of any single one being targeted for attack? On a risk-adjusted basis, it makes sense to neglect security concerns. When weighing the cost-benefits of hiring a team of CISM-certified sysadmins against the small chance of a $20,000 fine, it’s plain to see why Sony Pictures chose to raise a middle finger to infosec and store sensitive information in a cleartext file directory labeled “Password”.

Can you blame them? Corporations have a fiduciary duty to maximize value for their shareholders. Nowhere does there exist a duty to protect the personal data of their customers. Consumer lawsuits based on data breaches rarely succeed, unless the consumer can prove that they were quantifiably harmed.

Attitudes are different in Europe, where protection of personal data is a basic human right [1]. Companies that don’t adhere to security obligations may not operate on the continent. Over there, Facebook is not allowed to track you all over the internet, and search engines like Google have to comply with user requests to remove undesirable search results.

In the US, we prioritize liberty, or the right to be left alone. Companies like Uber and Google should be allowed to figure out their own privacy policies without government meddling. In theory, consumers will vote with their dollars. In practice, consumers have no idea how careless their service providers really are.

careless-users-in-the-cloud-and-what-it-can-do-about-it-3-638

US companies don’t care much when customers’ personal information gets stolen, but they care a lot when intellectual property is stolen. Chinese hackers are constantly testing US corporate resistance to IP theft [2]. The organizations with the best security practices will be ones with valuable IP, like Google, IBM, and DuPont. Of course, just because Google takes steps to protect your information from unauthorized access doesn’t mean they won’t abuse that data themselves.

I’m thinking I should delete all my accounts and move to Europe, or maybe a planet in Urbit.

References:
1. James Q. Whitman, The Two Western Cultures of Privacy: Dignity Versus Liberty. Yale Law Journal, 113, April 2004.
2. Adam Segal, The Hacked World Order: How Nations Fight, Trade, Maneuver, and Manipulate in the Digital Age. 2016.

Contracts, Code, and Complexity

The right to be sued is the power to accept a commitment. -–Thomas Schelling [1]

No one’s gonna do business with you without knowing they have recourse for when you try to weasel out. Even 5000 years ago, people created contracts on clay tablets so that they had something to take to the king if the counterparty welched.

Humans are opportunistic. Over time, people learned to be weasels. Some people learned to be exceptionally good weasels. Beginning in ancient Athens, these people were called lawyers (actually they were called orators, but served the same purpose).

Orators were paid well. Athenians knew that having a good lawyer could be a huge competitive advantage. If your counterparty hires Demosthenes to plead his case, then you’d better put Cicero on retainer.

Since then, litigation has been an arms race. 40% of Oracle’s headcount is employed on the legal team, and only because its friends Google and Microsoft invest just as much. Google spends $17 million a year on federal lobbying. The top issue? Patent protection.

As Karl Marx astutely observed, Competition is wasteful.

But competition does have one redeeming quality: It enables evolution. Without competitive exclusion, there would be no reason for natural selection and we’d all still be protozoa swimming in a primordial soup.

Instead, we’re complex organisms who know how to be weasels.

And it’s because counterparties spent 5000 years being weasels that contracts, and the laws governing contracts, have become so complex.

You don’t know the rule until you know its exceptions. In practice, the exceptions to the rule are the rule.

Contractual complexity is good. Complexity allocates responsibility and risk for the possible complications that might arise. This increases predictability, which allows counterparties to put more at stake.

While complex, the contracts and legal codes we have today provide better risk management than clay tablets and the Code of Hammurabi.

As the stakes increase, so does the cost of litigation. At some point humans began to think, Securing a commitment through legal coercion is expensive! Can we can have predictable risk allocation without using the threat of litigation? Maybe we don’t need the right to be sued in order to accept a commitment. Maybe a commitment can be self-governing.

A smart contract enforces a commitment without resorting to the threat of external litigation [2].

Early smart contracts won’t be robust against weasels, just like early clay tablets weren’t robust against Demosthenes. That’s why people didn’t put a lot at stake on a clay tablet. It was certainly no reason to throw out clay tablets!

It took 1600 years to go from the publican business partnerships in Rome to the Honor del Bazacle [3], the first modern joint-stock corporation. Romans had the technology to draft a corporate charter on papyrus; what they lacked was centuries of cumulative knowledge on how to structure a corporation.

Complexity has to be earned. Otherwise, it’s obfuscation. The Honor del Bazacle charter was complex because it had evolved the ability to protect its beneficiaries [4]:

Most early financial documents were fairly succinct records. Why would it take eight feet of tiny script to create a corporation?

The corporation is an organization that is designed to operate autonomously, perhaps for several centuries. The Honor del Bazacle charter is like a complete set of rules for playing a game: These rules needed to ensure that no single player, either unintentionally or willfully, could ruin the game or cheat the other players.

As a result, the Bazacle is an enterprise that still stands today.

bazacle

Last week, TheDAO put a corporation into a smart contract, and a weasel took a bunch of its money. Now its participants are pleading for an Ethereum fork that erases an unpredicted, but not unpredictable, outcome.

I have DAO tokens. I prefer that the “hacker” keep whatever ether I lost. The great thing about smart contracts is the predictable risk allocation. I signed up for the risk of losing my ether. I did not sign up for third-party adjudication.

The transaction-erasing fork will ultimately be decided by Ethereum miners, who can choose whether to adopt it in a software update. In a way, they serve as a decentralized parliament. But as someone who operates a mining node, I don’t want to be a parliamentarian. I didn’t sign up for that and I’m not qualified.

Blockchain contracts are not about adjudication by vote; we already have a very good solution for that in the modern court system. They’re about giving two parties the ability to trust a commitment. I want the rights and responsibilities that I signed up for.

References:
1. Thomas Schelling, The Strategy of Conflict. 1981.
2. Nick Szabo, Formalizing and Securing Relationships on Public Networks. 1997.
3. Germain Sicard, The Origins of Corporations: The Mills of Toulouse in the Middle Ages. 2015.
4. William Goetzmann, Money Changes Everything: How Finance Made Civilization Possible. 2016.

This one gets a picture. I was going to write a post summarizing the book, but I can't. There's too much good stuff inside.
This one gets a picture. I was going to write a post summarizing the book, but I can’t. There’s too much good stuff inside.

The Evolution of Private Loan Agreements

Adab, Mesopotamia. ca. 2900 BC
LUM-ma: Hey, can I borrow some barley to feed my kids? Harvest didn’t turn out so good this year.
MUG-si: You’ll pay me back next season?
LUM-ma: Yeah, totally.
MUG-si: Can I get that in writing?
LUM-ma: Sure, here you go:

Source: Early Dynastic and Early Sargonic Tablets from Adab in the Cornell University Collections [1]. Names are made up.
Source: Early Dynastic and Early Sargonic Tablets from Adab in the Cornell University Collections [1]. Names are made up.
Akkad, Mesopotamia. ca. 2750 BC
Farmer #1: Dammit, I’ve been drafted to go fight in Sumer. I don’t have time for this, I have farm stuff to do.
Farmer #2: I’ll take care of your farm while you’re gone. When you come back, we’ll split the harvest.
Farmer #1: Hell no, last time we tried this you let my fields get overrun with weeds and crocodiles.
Farmer #2: My buddy will guarantee that I follow through this time. If I screw up, he’ll compensate you for damages. He’s a merchant right here in Akkad so you know you can trust him.
Farmer #1: Fine. Can I get this in writing?
Farmer #2: Yup! Here:

This represents the first known surety bond [2].
This represents the first known surety bond involving a third-party guarantor [2].
Babylon, Mesopotamia. 1820 BC
Ilshu-bani: Can you spot me a couple shekels of silver? I need to buy some seeds.
Sin-tajjar: Ugh, I’m so sick of you always borrowing money from me. Get a job, man.
Ilshu-bani: I’ll pay you back at harvest time!
Sin-tajjar: That’s seven months from now. Don’t you understand the time value of money? I’ll loan you the shekels at 20% interest.
Ilshu-bani: 20%?! Good grief! What if I can’t pay that back?
Sin-tajjar: I’m not too worried. If you can’t pay me back, I get to make you my slave. Apparently that’s a law now.
Ilshu-bani: Freaking Hammurabi.
Sin-tajjar: Do you want the silver or not?
Ilshu-bani: Fine.
Sin-tajjar: Cool. Just print your name here:

Contract terms on the front, names of participants and witnesses on the back.
Contract terms on the front, names of participants and witnesses on the back [3]. The Code of Hammurabi put the first legal code in place to turn tribal customs into common law. The Code included standard interest rates.
Arsinoites nome, Egypt. 172 BC.
Aristokles: Can I borrow 3 talents and 780 drachma for 13 months?
Theokles: Sure, I charge 24% interest.
Aristokles: No problem.
Theokles: What happens if you don’t pay me back?
Aristokles: You get to have my wife!
Theokles: I’d… really rather have the money.
Aristokles: Nah, take my wife. Here, I’ll even put it writing for you:

A note in the right margin seems to indicate that (after some time?) both participants were dead, the affair had devolved to the sons of the contracting parties, and only the wife was still alive [4]
A note in the right margin seems to indicate that (after some time?) both participants were dead, the affair had devolved to the sons of the contracting parties, and only the wife was still alive. Source: Advanced Papyrological Information System [4]
Rome, Roman Republic. 100 AD.
Pontius: May I borrow 500 denarii? I’m gonna go invest in a company.
Titus: Sure. How do I know you’ll repay me?
Pontius: I’m a Jew! We’re the most honest businessmen in the world!
Titus: ಠ_ಠ
Pontius: It’s 100 AD, I’m allowed to say things like that.
Titus: Look, I just need you to make an oral promise that you’ll pay me back.
Pontius: That’s it?
Titus: Yeah, that’s how Roman law works. If I ask you to promise something, and you agree, that’s legally enforceable.
Pontius: What happens if I later deny making that promise?
Titus: Then the gods will smite you.
Pontius: Oh. It’s olden times so I take that super seriously.
Titus: Ready to promise? I’m gonna ask you to promise now.
Pontius: Yes ready!
Titus: Spondere tu dabis mihi?
Pontius: Spondeo.

This was called a stipulatio. Verbal agreement was essential to having a valid contract under Roman law. Written documents could provide evidence for the agreement, but the contract itself had to be oral [5].

Turfan, Silk Road, China. 661 AD.
龍: May I borrow 30 bolts of silk? I wanna buy some camels and apparently silk is the standard form of money around here.
陳: Yeah, but I better get this in writing.
龍: Ok.
陳: Hold up. What if you get killed by bandits on the way home?
龍: Well my wife better not remarry. If she does, I’ll come back and haunt her, that wench.
陳: No, what happens to your debt if you get killed by bandits?
龍: Oh, take it up with my wife. Go ahead, put that in the contract. Mrs. 龍 has to make good on my debts. God, she was probably the one who sent the bandits. She totally would.
陳: How will I even find your wife? I’m from Iran, all you people look the same to me.
龍: That’s kinda racist. But if you can’t find either of us, take it to 唐 court. We have a good legal system here.
陳: Pleasure doing business with you, sir.

Tang (唐) courts along the Silk Road were accustomed to hearing disputes from participants all over the land. They were friendly to creditors and would receive cases even after contracts had been lost.
Tang (唐) courts along the Silk Road were accustomed to hearing disputes from participants all over the land. They were friendly to creditors and would receive cases even after contracts had been lost [3]. This contract requires interest payments of 4 bolts of silk per month until the principal is due.
Oxford, England. 1250 AD.
Nigel #1: Say, chap, can I borrow fifty quid?
Nigel #2: Sure thing mate. You’ll pay me back?
Nigel #1: Of course! I’ll even make you a contract!
Nigel #2: Bloody hell! I can’t read or write!
Nigel #1: Blimey! Nor can I!
Nigel #2: No worries, I’ve got this pointed stick. We’ll mark off 50 tallies to show what you owe me.
Nigel #1: Brilliant!
Nigel #2: Here, let’s split it down the middle so we each have a piece. I’ll keep the stock, and you take the short end of the stick. Each time you pay back a quid, we’ll connect them together and cut off a tally.
Nigel #1: And if I should skive off?
Nigel #2: Well I’ve got this pointed stick!
Nigel #1: Cheers!

Tally stick 2

Antwerp, Netherlands. 1611 AD.
Hans: I would like to borrow 500 Flemish pounds.
Jan: And what do you have to offer as collateral?
Hans: I have two shares of the Dutch East India Company.
Jan: How do I know you aren’t already using those shares to collateralize another loan?
Hans: My notary here can guarantee that.
Jan: Are you going to use this loan to buy more Company shares?
Hans: Maybe.
Jan: We’re almost in the Early Modern Age. How bout we leave the private lending to poor people and create sophisticated financial instruments for the rest of us? What you really want here is a forward contract.

Handwritten contract for future delivery of two shares of Dutch East India Company [3]. An edict issued the States of Holland in 1623 to regulate forward trading in shares of the Dutch East and West India Companies mentioned not only the borrowing of money against company shares but also specified the procedure for foreclosure of shares in case borrowers defaulted.
According to GAD Capital, this is a handwritten contract for future delivery of two shares of Dutch East India Company [3]. An edict issued the States of Holland in 1623 to regulate forward trading in shares of the Dutch East and West India Companies mentioned not only the borrowing of money against company shares but also specified the procedure for foreclosure of shares in case borrowers defaulted [6].
California, USA. 1990 AD.
Alice: Can I borrow $100?
American Express: Of course. We’ll be charging 24% interest.
Alice: Aren’t there laws against usury?
American Express: Those are state laws. Your credit card is issued by a Federal bank. We can charge whatever we want. Here’s your cardholder agreement.
Alice: Why is it 50 pages? What the hell is in this thing?
American Express: Basically you agree to have your information sold to third parties. Also you consent to having our marketing associates call whenever they like, and they can record the call without telling you about it. Also we can change the rules whenever we want.
Alice: Why are you guys such assholes?
American Express: If you’re not happy with us, feel free to take your business to a payday loan shark.

credit-cards

California, USA. 2016 AD.
Alice: Bob, can I borrow 20 ether? I’ll put up 50 Alice tokens as collateral.
Bob: Okay sure. Can I get that on the blockchain?
Alice: Here’s a smart contract!

0x60606040526106ac806100126000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480632d09a6931461004f57806363485625146100705780637f012ab5146100b25761004d565b005b61006e60048080359060200190919080359060200190919050506100f4565b005b6100866004808035906020019091905050610178565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100c86004808035906020019091905050610234565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b8173ffffffffffffffffffffffffffffffffffffffff1663856904f782604051827c0100000000000000000000000000000000000000000000000000000000028152600401808273ffffffffffffffffffffffffffffffffffffffff1681526020019150506000604051808303816000876161da5a03f115610002575050505b5050565b600060006040516104408061026c833901809050604051809103906000f0905080600060005060008560001916815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908302179055508073ffffffffffffffffffffffffffffffffffffffff1683600019167fdaf0395472793138163780bf8abff89ef524f1a85823e066fd7b81121033d88260405180905060405180910390a380915061022e565b50919050565b600060005060205280600052604060002060009150909054906101000a900473ffffffffffffffffffffffffffffffffffffffff16815660606040525b33600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908302179055506000600260146101000a81548160ff021916908302179055505b6103e8806100586000396000f36060604052361561007f576000357c0100000000000000000000000000000000000000000000000000000000900480633fa4f2451461008157806341c0e1b5146100a457806349ce5393146100b357806366d003ac146100d6578063856904f71461010f5780638da5cb5b14610127578063f3a504f2146101605761007f565b005b61008e6004805050610185565b6040518082815260200191505060405180910390f35b6100b1600480505061018e565b005b6100c06004805050610222565b6040518082815260200191505060405180910390f35b6100e36004805050610280565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61012560048080359060200190919050506102a6565b005b61013460048050506103af565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61016d60048050506103d5565b60405180821515815260200191505060405180910390f35b60006000505481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561021f57600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b5b565b60006001600260146101000a81548160ff021916908302179055503073ffffffffffffffffffffffffffffffffffffffff16316000600050819055503073ffffffffffffffffffffffffffffffffffffffff1631905061027d565b90565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561030257610002565b6001801515600260149054906101000a900460ff16151514151561032557610002565b81600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff02191690830217905550600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166000600060005054604051809050600060405180830381858888f1935050505050505b50565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600260149054906101000a900460ff168156

Bob: Wait a minute. The market price of Alice tokens fluctuates like crazy. I need to be able to issue a capital call in the event that your collateral falls below the value of the loan.
Alice: Oh good point. Let’s add a function to the contract that queries a Price Oracle. Then my collateral can always be marked to market.
Bob: Who operates the Price Oracle?
Alice: This new exchange, it’s called Mt. Sox.
Bob: Sounds legit. How do I know I’ll be able to claim your collateral? What if you secretly drain it?
Alice: I can’t do that, it’s on the blockchain.
Bob: That happened to the DAO.
Alice: If the contract is exploited, then Vitalik will tell miners to adopt a fork that restores the ether to its rightful owner.
Bob: What if we disagree about the rightful owner? What if I claim that you exploited a vulnerability in the code, while you claim that that was the intended functionality of the contract?
Alice: Then we’ll turn to the decentralized Supreme Court.
Bob: Are you serious?
Alice:
Bob: This is dumb. How bout I just give you a hundred bucks and you send me a nude selfie as collateral?

References:

  1. 50-03-131, CUSAS 11, 056 (CUNES 50-03-131). Early Dynastic and Early Sargonic Tablets from Adab in the Cornell University Collections.
  2. W. Morgan. History and Economics of Suretyship. Cornell Law Review, Volume 12, Issue 2, Feb 1927.
  3. W. Goetzmann, K.G. Rouwenhorst. The Origins of Value: The Financial Innovations that Created Modern Capital Markets Hardcover. August 1, 2005
  4. U-M Library Digital Collections. Advanced Papyrological Information System (APIS UM).
  5. A. Watson. The Evolution of Law: The Roman System of Contracts (1984). Available at: http://digitalcommons.law.uga.edu/fac_artchop/496
  6. O. Gelderblom and J. Jonker. Completing a Financial Revolution: The Finance of the Dutch East India Trade and the Rise of the Amsterdam Capital Market, 1595-1612. The Journal of Economic History, Vol. 64, No. 3 (Sep., 2004), pp. 641-672

Contracts and Trust

Two nights ago, I was convinced to watch 50 Shades of Grey. Not the whole movie, thank god, just the contract negotiation scene.

I don’t get it, I said. Two adults are about to engage in sexual relations. Why do they need a contract? Don’t they trust each other? And if they don’t trust each other, why don’t they walk away?

The same question applies to pre-nups. Or even the institution of marriage! Unless one party poses a significant flight risk, why would willing participants need a legal contract to compel each other to stay?

To better understand this, let’s start with a simpler contract.

Loan contracts.

Suppose you apply for a mortgage with the best of intentions. The loan is approved thanks to your impeccable credit score and 10% down. It’s a large mortgage, but your salary is five times the monthly payment so you should pay it off no problem.

Fast-forward half a decade. The housing market has collapsed, your dog needs kidney dialysis, and to top it all off, a robot just took your job.

How motivated are you to continue paying that mortgage?

While you may be a trustworthy individual at time of loan application, it’s future-you that can’t be trusted. As long as the cost of defaulting on the contract (loss of home equity) is greater than the opportunity cost of mortgage payments, repayment can be coerced.

funny-wedding-cake-topper-remarkable-and-no-running-again-funny-wedding-cake-toppers-rwdreview-com

Much like a consumer loan agreement, marriage is an institution founded on mistrust. Sure, things are going great right now, but it is a cruel fact of nature that most humans do not age well.

What will compel you to stick around after she doubles in size and succumbs to the effects of gravity? And what happens after you become a balding couch ornament with the gut of a ruminant?

This is why marriage contracts were invented. Conjugal bliss can exist when both parties follow similar rates of decay, but this symmetry is rare. Discord arises when one party decays more rapidly than the other. Or, worse, when one party’s income substantially increases.

If the cost of terminating the marriage is less than the opportunity cost of remaining in the contract, it is inevitable that the contract will be breached. The key to a successful marriage is to ensure a sufficiently high cost of termination for both parties. Like, always keep a few thermonuclear warheads up your sleeve.

Back to 50 Shades.

If I understand correctly, the entire movie is about the process of contract negotiation. Christian Grey needs to protect himself from legal recourse if Ana decides to sue him for excessive shenanigans.

As a result, they arrive at an overly complex agreement detailing every possible activity or instrument that could possibly be employed. There’s an easier way.

Christian and Ana’s many pages of complexity can be reduced to a simple smart contract. Here’s how it works:

Each participant puts a valuable consideration (say, 10 ether) into escrow. The participants wear GPS tracking devices that continuously relay their location coordinates to the contract.

Just like in the movie, Ana has two safe words, yellow and red. After the first safe word is invoked, Christian has 10 minutes to move at least 1000 feet away from Ana. If the second safe word is invoked, and the contract detects that Christian is still within the stay-away radius, Ana gets all the money. If Christian is outside the radius and the red safe word is invoked, then Ana is being dishonest about her safety and Christian gets all the money.

Here’s a template, now all they have to do is put it on the blockchain.

import "math.sol";

contract FiftyShades {
    address dominant;     // contract participants
    address submissive;

    uint public value;    // deposit value
    uint public distance; // distance between dom and submissive

    int subCoordX;  // cartesian coordinates 
    int subCoordY;  // of participants
    int domCoordX;
    int domCoordY;

    // contract state. 
    // Green = no safe words yet.
    // Yellow = first safe word, Red = second safe word
    enum State { Dormant, Green, Yellow, Red }
    State public state;

    // when was first safe word used?
    uint public yellowStartTime;

    // submissive creates the contract
    function FiftyShades(int subCoordX_, int subCoordY_) {
        submissive = msg.sender;
        value = msg.value;      // submit deposit
        subCoordX = subCoordX_; // initialize location
        subCoordY = subCoordY_;
        state = State.Dormant;
    }

    // contract becomes active when dominant submits deposit
    function addDeposit(int domCoordX_, int domCoordY_) {
        // require an equal contribution
        if (msg.value < value) throw;

        dominant = msg.sender;
        domCoordX = domCoordX_; // init location
        domCoordY = domCoordY_;
        // deposits received, ready to go
        state = State.Green;
    }

    modifier onlySubmissive() {
        if (msg.sender != submissive) throw;
        _
    }

    modifier onlyDominant() {
        if (msg.sender != dominant) throw;
        _
    }

    modifier inState(State _state) {
        if (state != _state) throw;
        _
    }

    event aborted();  // cancel contract
    event yellowState();  // first safe word used
    event redState();     // second safe word used
    event falseAlarm();

    /// First Safe word used by submissive
    /// After first safe word, the dominant has 10 minutes
    /// to move at least 1000 feet away from the submissive
    function safeWordYellow(int subCoordX_, int subCoordY_)
        onlySubmissive
        inState(State.Green)
    {
        yellowState();
        subCoordX = subCoordX_;  // record location
        subCoordY = subCoordY_;
        yellowStartTime = now;   // record start time
        state = State.Yellow;
    }

    /// Second safe word used by submissive
    function safeWordRed(int subCoordX_, int subCoordY_)
        onlySubmissive
        inState(State.Yellow)
    {
        // has enough time elapsed?
        if (now >= yellowStart + 10 minutes) {
            state = State.Red;
            // TODO: check submissive's movement since last safe word
            // Ensure that submissive is not chasing after dominant
            subCoordX = subCoordX_;
            subCoordY = subCoordY_;

            // calculate distance beteen dominant and submissive
            distance = calcDistance();
            // is the dominant outside of the stay-away distance?
            if (distance < 1000) {
                paySubmissive();  // no: pay submissive 
            } else {
                payDominant();    // yes: submissive misused the safe word
            }
        }
    }

    function paySubmissive()
        inState(State.Red)
    {
        redState();
        suicide(submissive); // kill contract, everything goes to submissive
    }
    function payDominant()
        inState(State.Red)
    {
        falseAlarm();
        suicide(dominant); // kill contract, everything goes to dominant
    }
    /// Can only be called by the submissive
    /// before dominant deposit
    function abort()
        onlySubmissive
        inState(State.Dormant)
    {
        aborted();
        suicide(submissive); // kill contract, return initial deposit to submissive
    }

    function updateDomLocation(int domCoordX_, int domCoordY_)
        onlyDominant
    {
        domCoordX = domCoordX_;
        domCoordY = domCoordY_;
    }

    function updateSubLocation(int subCoordX_, int subCoordY_)
        onlySubmissive
    {
        subCoordX = subCoordX_;
        subCoordY = subCoordY_;
    }

    //pythagorean distance
    function calcDistance() returns (uint d) {
        int x = subCoordX - domCoordX;
        int y = subCoordY - domCoordY;
        int dist = Math.sqrt(x*x - y*y)
        return dist;
    }

    /// TODO: use Haversine distance, add trig fxns to Math lib

    function() {
        throw;
    }
}

For comparison, here is the 10-page entanglement the characters used in the movie.

Obfuscated Obfuscation

klout (1)

Remember Klout? Didn’t think so.

Klout was a social network that assigned you a score between 1 and 100 depending on what it thought you were worth as a human being.

For a while, American Airlines offered VIP lounge access to people with Klout scores above 55. One of my classmates was an intern at Klout, so I asked him to insert a few lines of server code for me:

if( username==”elaine” ) { 
     kloutScore = 60;
}


I’ll get fired,
he said.

Of course, you can’t put it in there just like that. It has to be nonobvious. Like this:

private String o = “656c61696e65”;
private StringBuilder O = new StringBuilder(username);
for( int j=0; j<o.length()-1; j+=2 ){	  
    String l = o.substring(i, (i+2));
    int i = Integer.parseInt(l, 16);
    if( O.charAt(j/2)!=(char)i ) {
        break;
    } else {
        kloutScore+=10;
    }
}

The two code examples achieve the same function. The difference is, the first one is inadmissibly honest in its intentions. The second is a code-reviewer’s nightmare.

Instead of building a stronger lock, hide the front door.

Software obfuscation was originally used to protect proprietary software from reverse engineers looking to bypass copy protection. If the debugger output is tortuous enough, maybe the engineer will get frustrated and go watch porn instead.

A simple transformation to source code can leave it logically opaque while functionally the same. For example:

AND EAX, 0x40    ;mask all but the 6th bit 
CMP EAX, 0x40    ;check if that bit was set

is logically equivalent to:

PUSH EAX 
XOR [ESP], 0xFFFFFFFF 
AND [ESP], 0x40 
POP EAX 
CMP EAX, 0

These methods worked against not just DRM-crackers, but company competitors seeking access to intellectual property. The cat-and-mouse game of software protection gave rise to a whole industry of obfuscation tools designed to chew up a program source file and spit out a snake pit.

Of course, as soon as reverse engineers encountered obfuscated code, they started building deobfuscation tools.

Thus came the impetus to obfuscate the obfuscation.

If you don’t want anyone to break your lock, convince them there is no lock.

Good obfuscation does not look obfuscated. For example, a programmer could hide her intentions by using machine instructions with hidden side effects [1]. Some innocuous string operations:

XCHG EAX, ESI   ;swap two registers
LODS            ;store the value pointed to by ESI
XCHG EAX, ESI   ;swap registers back

This result of those instructions is:

INC EAX

The LODS instruction has the side effect that it increments ESI to the next address after storing the value, because it works on continuous blocks of memory.

obfuscated code

Obfuscated obfuscation is even easier in high-level languages. The Underhanded C Contest is an annual challenge to write honest-looking code that secretly performs a nefarious function.

Common tactics include triggering an arithmetic overflow, pointer overwrites, and bad hash values. As a result, the code ends up doing the opposite of what a user might expect from a visual inspection.

Last year’s winning entry put this line in a single header file:

typedef double float_t; /* Desired precision for floating-point vectors */

By default, float_t is defined as single precision in math.h. The above file overrides the typedef as double precision. By #include-ing this header file in some C files but not others, the programmer passes an array of 8-byte numbers into a function that expects an array of 4-byte numbers. C interprets each 8-byte number as two 4-byte numbers, leading to an array where every other value is 0.

Submissions to the Underhanded C Contest would never pass formal verification, let alone a basic systems test. Far more interesting is the Underhanded Crypto Contest, which challenges programmers to submit cryptography implementations with hidden backdoors.

This one implements Stern’s zero-knowledge identification protocol [2], a scheme based on error-correcting codes where the public key is a parity check matrix and the cryptogram is a noisy codeword. The private key is the unencoded word. A backdoor was inserted by allowing an arithmetic overflow in part of the verification, making it possible for an attacker to pass off an incorrect key. (Note: My interpretation is grossly simplified and possibly flawed.)

I think the moral of the story is, try not to piss off your software engineers. If that can’t be avoided, confine them to a safe language like Ada.

References:
1. S. Schrittwieser, et al. Covert Computation — Hiding code in code through compile-time obfuscation. Computers & Security 42, 2014.
2. J. Stern. A new identification scheme based on syndrome decoding. CRYPTO, Volume 773, 1993.