afl-fuzz: nobody expects CDATA sections in XML

I made a very explicit, pragmatic design decision with afl-fuzz: for performance and reliability reasons, I did not want to get into static analysis or symbolic execution to understand what the program is actually doing with the data we are feeding to it. The basic algorithm for the fuzzer can be just summed up as randomly mutating the input files, and gently nudging the process toward new state transitions discovered in the targeted binary. That discovery part is done with the help of lightweight and extremely simple instrumentation injected by the compiler.



I had a working theory that this would make the fuzzer a bit smarter than a potato, but I wasn't expecting any fireworks. So, when the algorithm managed to not only find some useful real-world bugs, but to successfully synthesize a JPEG file out of nothing, I was genuinely surprised by the outcome.



Of course, while it was an interesting result, it wasn't an impossible one. In the end, the fuzzer simply managed to wiggle its way through a long and winding sequence of conditionals that operated on individual bytes, making them well-suited for the guided brute-force approach. What seemed perfectly clear, though, is that the algorithm wouldn't be able to get past "atomic", large-search-space checks such as:



if (strcmp(header.magic_password, "h4ck3d by p1gZ")) goto terminate_now;



...or:



if (header.magic_value == 0x12345678) goto terminate_now;



This constraint made the tool less useful for properly exploring extremely verbose, human-readable formats such as HTML or JavaScript.



Some doubts started to set in when afl-fuzz effortlessly pulled out four-byte magic values and synthesized ELF files when testing programs such as objdump or file. As I later found out, this particular example is often used as a benchmark for complex static analysis or symbolic execution frameworks.

But still, guessing four bytes could have been just a happy accident. With fast targets, the fuzzer can pull off billions of execs per day on a single machine, so it could have been dumb luck.



(As an aside: to deal with strings, I had this very speculative idea of special-casing memory comparison functions such as strcmp() and memcmp() by replacing them with non-optimized versions that can be instrumented easily. I have one simple demo of that principle bundled with the fuzzer in experimental/instrumented_cmp/, but I never got around to actually implementing it in the fuzzer itself.)



Anyway, nothing quite prepared me for what the recent versions were capable of doing with libxml2. I seeded the session with:



<a b="c">d</a>



...and simply used that as the input for a vanilla copy of xmllint. I was merely hoping to stress-test the very basic aspects of the parser, without getting into any higher-order features of the language. Yet, after two days on a single machine, I found this buried in test case #4641 in the output directory:



...<![<CDATA[C%Ada b="c":]]]>...



What the heck?!



As most of you probably know, CDATA is a special, differently parsed section within XML, separated from everything else by fairly complex syntax - a nine-character sequence of bytes that can't be realistically discovered by just randomly flipping bits.



The finding is actually not magic; there are two possible explanations:





  • As a recent "well, it's cheap, so let's see what happens" optimization, AFL automatically sets -O3 -funroll-loops when calling the compiler for instrumented binaries, and some of the shorter fixed-string comparisons will be actually just expanded inline. For example, if the stars align just right, strcmp(buf, "foo") may be unrolled to:


    cmpb $0x66,0x200c32(%rip) # 'f'
    jne 4004b6
    cmpb $0x6f,0x200c2a(%rip) # 'o'
    jne 4004b6
    cmpb $0x6f,0x200c22(%rip) # 'o'
    jne 4004b6
    cmpb $0x0,0x200c1a(%rip) # NUL
    jne 4004b6


    ...which, by the virtue of having a series of explicit and distinct branch points, can be readily instrumented on a per-character basis by afl-fuzz.



  • If that fails, it just so happens that some of the string comparisons in libxml2 in parser.c are done using a bunch of macros that will compile to similarly-structured code (as spotted by Ben Hawkes). This is presumably done so that the compiler can optimize this into a tree-style parser - whereas a linear sequence of strcmp() calls would lead to repeated and unnecessary comparisons of the already-examined chars.


    (Although done by hand in this particular case, the pattern is fairly common for automatically generated parsers of all sorts.)


The progression of test cases seems to support both of these possibilities:




<![

<![C b="c">

<![CDb m="c">

<![CDAĹĹ@

<![CDAT<!

...




I find this result a bit spooky because it's an example of the fuzzer defiantly and secretly working around one of its intentional and explicit design limitations - and definitely not something I was aiming for =)



Of course, treat this first and foremost as a novelty; there are many other circumstances where similar types of highly verbose text-based syntax would not be discoverable to afl-fuzz - or where, even if the syntax could be discovered through some special-cased shims, it would be a waste of CPU time to do it with afl-fuzz, rather than a simple syntax-aware, template-based tool.


(Coming up with an API to make template-based generators pluggable into AFL may be a good plan.)



By the way, here are some other gems from the randomly generated test cases:



<!DOCTY.

<?xml version="2.666666666666666666667666666">

<?xml standalone?>

Bitcoiners: Surely we can do Buiter than this?

Willem Buiter has a very nice piece critiquing the Swiss Gold Initiative; see here.

Unfortunately, Buiter starts talking about Bitcoin, making false analogies between the cryptocurrency and gold. He should have just focused on gold.

As it turns out, both gold and Bitcoin do share some important characteristics. I've written about this here: Why Gold and Bitcoin Make Lousy Money.

The false analogy is in equating the mining of gold with the mining of bitcoin. Paul Krugman made the same mistake here: Adam Smith Hates Bitcoin. Here is the offending passage in Buiter's notes:
John Maynard Keynes once described the Gold Standard as a “barbarous relic”. From a social perspective, gold held by central banks as part of their foreign exchange reserves merits the same label, in our view. The same holds for gold held idle in private vaults as a store of value. The cost and waste involved in getting the gold out of the ground only to but it back under ground in secure vaults is considerable. Mining the ore is environmentally damaging, especially if it involves open pit mining. Refining the gold causes further environmental risks. Historically, gold was extracted from its ores by using mercury, a toxic heavy metal, much of which was released into the atmosphere. Today, cyanide is used instead. While cyanide, another toxic substance, is broken down in the environment, cyanide spills (which occur regularly) can wipe out life in the affected bodies of water. Runoff from the mine or tailing piles can occur long after mining has ceased. 
Even though, from a social efficiency perspective, the mining of new gold and the costly storage of existing gold for investment purposes are wasteful activities, they may be individually rational. The same applies to Bitcoin. Its mining is socially wasteful and environmentally damaging.
No, no, no and no. This analogy is all wrong.

Let me be clear about this. Bitcoin costs zero to produce. If one had control over the protocol, one could instantly and costlessly create as many bitcoins as one wanted. No environmental waste, no effort needed. The same is not true of gold.

But wait a minute, you might say. Doesn't mining for bitcoins require effort, consume resources, etc.? The answer is, yes, it does. But this fact does not make the analogy correct (though one can certainly understand why the analogy seems to be correct). Let me explain.

The purpose of gold miners is to prospect for gold. The purpose of Bitcoin miners is not to prospect for bitcoins. The purpose of Bitcoin miners is to process payment requests. A bank teller also processes payment requests. To say that miners are mining for bitcoin is like saying that tellers are mining for dollars. Understand? Let me try again.

Gold miners prospect for gold. But they do not necessarily get paid in gold. In fact, if they work for gold companies, they are likely to get paid in dollars. But they could get paid in gold, or anything else, for that matter. How they get paid does not take away their basic function, which is to discover new gold.

Bitcoin miners, like bank tellers, process payments. Miners, like tellers, want to get paid for the service they provide. It really does not matter how they are paid. As it turns out, miners are paid in the form of newly-issued bitcoins (as well as old bitcoins offered as service fees by transactors). But this does not mean that they are "mining for bitcoin" any more than a bank teller is "mining for dollars."

But isn't mining for bitcoin "wasteful?" In a sense, yes, but again, the "waste" here is not the same as the waste associated with commodity money. Again, let me explain.

We live in a "second-best" world, where people lie and cheat. In a first-best world, money would not even be necessary (see my post here: Evil is the Root of All Money). It is unfortunate that we need Bitcoin miners (and tellers) to process payments. But the resources consumed in this process are necessary, given the safeguards that have to enforced to ensure the integrity of the payment system.

The waste associated with mining gold is that in principle, gold money can be replaced by paper money (and please, do not give some weird "out of thin air" argument; see here.) Paper money, like Bitcoin, and unlike gold, is (near) costless to produce.

Note: Of course, the limit on the supply of bitcoin is determined by a community consensus on following the protocol that adopts the 21M limit. Bitcoin advocates argue that this "hardwired" protocol that governs the supply of bitcoin is more reliable and less prone to political manipulation relative to existing central banking systems. This all may be true, but does not take away from my argument above concerning the false analogy between gold and bitcoin.


afl-fuzz: crash exploration mode

One of the most labor-intensive portions of any fuzzing project is the work needed to determine if a particular crash poses a security risk. A small minority of all fault conditions will have obvious implications; for example, attempts to write or jump to addresses that clearly come from the input file do not need any debate. But most crashes are more ambiguous: some of the most common issues are NULL pointer dereferences and reads from oddball locations outside the mapped address space. Perhaps they are a manifestation of an underlying vulnerability; or perhaps they are just harmless non-security bugs. Even if you prefer to err on the side of caution and treat them the same, the vendor may not share your view.



If you have to make the call, sifting through such crashes may require spending hours in front of a debugger - or, more likely, rejecting a good chunk of them based on not much more than a hunch. To help triage the findings in a more meaningful way, I decided to add a pretty unique and nifty feature to afl-fuzz: the brand new crash exploration mode, enabled via -C.



The idea is very simple: you take a crashing test case and give it to afl-fuzz as a starting point for the automated run. The fuzzer then uses its usual feedback mechanisms and genetic algorithms to see how far it can get within the instrumented codebase while still keeping the program in the crashing state. Mutations that stop the crash from happening are thrown away; so are the ones that do not alter the execution path in any appreciable way. The occasional mutation that makes the crash happen in a subtly different way will be kept and used to seed subsequent fuzzing rounds later on.



The beauty of this mode is that it very quickly produces a small corpus of related but somewhat different crashes that can be effortlessly compared to pretty accurately estimate the degree of control you have over the faulting address, or to figure out whether you can get past the initial out-of-bounds read by nudging it just the right way (and if the answer is yes, you probably get to see what happens next). It won't necessarily beat thorough code analysis, but it's still pretty cool: it lets you make a far more educated guess without having to put in any work.



As an admittedly trivial example, let's take a suspect but ambiguous crash in unrtf, found by afl-fuzz in its normal mode:



unrtf[7942]: segfault at 450 ip 0805062b sp bf957e60 error 4 in unrtf[8048000+1c000]


When fed to the crash explorer, the fuzzer took just several minutes to notice that by changing {\cb-44901990 in the converted RTF file to printable representations of other negative integers, it could quickly trigger faults at arbitrary addresses of its choice, corresponding mostly-linearly to the integer set:




unrtf[28809]: segfault at 88077782 ip 0805062b sp bff00210 error 4 in unrtf[8048000+1c000]

unrtf[26656]: segfault at 7271250 ip 0805062b sp bf957e60 error 4 in unrtf[8048000+1c000]



Given a bit more time, it would also almost certainly notice that choosing values within the mapped address space get it past the crashing location and permit even more fun. So, automatic exploit writing next?

Swift UIScrollView with Auto-Layout and Size Classes

UIScrollView with Auto-Layout and Size Classes

A simple tutorial on making scrollable view that can accommodate any screen sizes. Download Link.




1.) First, of course we need a scrollview. So, drag a scrollview inside the storyboard and make sure that its distance from every side is zero.


2.) To make sure that it will accommodate any screen sizes; we have to pin all of its side to its superview.  Click the newly added scrollview (just in case you click somewhere) and go to "Editor" -> "Pin" -> "Leading Space to SuperView". Repeat the same process for trailing, top and bottom.

3.) Now we need a container to display our UI's. So, drag a simple view and make sure that all of its distance to every side it zero, similar to scrollview.

4.) To make sure that it will accommodate any screen sizes the same process (2) must be done.

5.) Since we just need to be able to scroll up and down, we need to fix its width. Select the newly added view and and "control-drag" it to scroll view, and then select "Equal Widths".

6.) For the height, select the view and "control-drag" it to itself, then select "Height". You will be given a height of 580. You can change its value by clicking the height constraint then going to attribute inspector and then changing the "constant" to any value you want.

 And that is it. You can now build and run the project to see how it works.

Japan: Some Perspective

So Japan is in recession.  And it's all so unexpected. Ring the alarm bells!

Well, hold on for a moment. Take a look at the following diagram, which tracks the Japanese real GDP per capita since 1995 (normalized to equal 100 in that year). I also decompose the GDP into its expenditure components: private consumption, government consumption, private investment, and government investment (I ignore net exports). The GDP numbers go up to the 3rd quarter, the other series go up to only the 2nd quarter.



In terms of what we should have expected, I think it's fair to say that most economists would have predicted the qualitative nature of the observed dynamic in response to an anticipated tax hike. That is, we'd expect people to substitute economic activity intertemporally--front loading activity ahead of the tax hike, then curtailing it just after. And qualitatively, that's exactly what we see in the graph above. But does the drop off in real per capita GDP really deserve all the attention it's getting? I don't think so. The fact that the economy was a little weaker in the 3rd quarter than expected (the two consecutive quarters of GDP contraction is what justified labeling the event a "recession") is not really something to justify wringing one's hand over. Not yet, at least.

By the way, if you're interested in reading more about the Koizumi boom era, see my earlier post here: Another look at the Koizumi boom.

Roger Farmer on labor market clearing.

While I'm a huge fan of Roger Farmer's work, I think he gets this one a little wrong:  Repeat After Me: The Quantity of Labor Demanded is Not Always Equal to the Quantity Supplied. I am, however, sympathetic to the substantive part of his message. Let me explain.

The idea of "supply" and "demand" is rooted in Marshall's scissors (a partial equilibrium concept). The supply and demand framework is an extremely useful and powerful way of organizing our thinking on a great many matters. And it is easy to understand. (I have a pet theory that if you really want to have an idea take hold, you have to be able to represent it in the form of a cross. The Marshallian cross. The Keynesian cross. Maybe even the Christian cross.)

The Marshallian perspective is one in which commodities are traded on impersonal markets--anonymous agents trading corn and human labor alike in sequences of spot trades. Everything that you would ever need to buy or sell is available (absence intervention) at a market-clearing price. The idea that you may want to seek out and form long-lasting relationships with potential trading partners (and that such relationships are difficult to form) plays no role in the exchange process--an abstraction that is evidently useful in some cases, but not in others.

I think what Roger means to say is that (repeat after me) the abstraction of anonymity, when describing the exchange for labor services, is a bad one. And on this, I would wholeheartedly agree (I've discussed some of these issues in an earlier post here).

Once one takes seriously the notion of relationship formation, as is done in the labor market search literature, then the whole concept of "supply and demand" analysis goes out the window. That's because these well-defined supply and demand schedules do not exist in decentralized search environments. Wage rates are determined through bargaining protocols, not S = D. To say, as Roger does, that demand does not always equal supply, presupposes the existence of Marshall's scissors in the first place (or,  more generally, of a complete set of Arrow-Debreu markets).

And in any case, how can we know whether labor markets do not "clear?" The existence of unemployment? I don't think so. The neoclassical model is one in which all trade occurs in centralized locations. In the context of the labor market, workers are assumed to know the location of their best job opportunity. In particular, there is no need to search (the defining characteristic of unemployment according to standard labor force surveys). The model is very good at explaining the employment and non-employment decision, or how many hours to work and leisure over a given time frame. The model is not designed to explain search. Hence it is not designed to explain unemployment. (There is even a sense in which the neoclassical model can explain "involuntary" employment and non-employment. What is "involuntary" are the parameters that describe an individuals' skill, aptitude, etc. Given a set of unfortunate attributes, a person may (reluctantly) choose to work or not. Think of the working poor, or those who are compelled to exit the labor market because of an illness.)

Having said this, there is nothing inherent in the neoclassical model which says that labor market outcomes are always ideal. A defining characteristic of Rogers' work has been the existence of multiple equilibria. It is quite possible for competitive labor markets to settle on sub-optimal outcomes where all markets clear. See Roger's paper here, for example.

The notion that supply might not equal demand may not have anything to do with understanding macroeconomic phenomena like unemployment. I think this important to understand because if we phrase things the way Roger does, people accustomed to thinking of the world through the lens of Marshall's scissors are automatically going to look for ways in which the price mechanism fails (sticky wages, for example). And then, once the only plausible inefficiency is so (wrongly) identified, the policy implication follows immediately: the government needs to tax/subsidize/control wage rates. In fact, the correct policy action may take a very different form (e.g., skills retraining programs, transportation subsidies, job finding centers, etc.)

Kunsten å velge tall som passer

Det finnes ikke grunnlag for å hevde at Statlige selskaper vil gi bedre avkastning enn oljefondet. Av ukjent grunn hevder likevel arbeiderbevegelsen stadig vekk det motsatte.

Siste ute er andre nestleder i LO Hans-Christian Gabrielsen i et innlegg i Klassekampen. Gabrielsen har lett etter eksempler på et selskap som i en eller annen periode har slått indeksen, og jammen har han ikke funnet det også!

Kirsebæret som Gabrielsen har plukket er Kongsberg Gruppen i perioden 2006-2011. I denne spesielle perioden gav selskapet en avkastning på hele 26 %!

Problemet er at det finnes andre eksempler som viser det motsatte. Norsk Hydro gav tap i denne perioden. DNB gav nesten ikke noen avkastning i det hele tatt.

Dersom vi leter vil det være veldig enkelt å finne selskaper i oljefondets portefølje som har gjort det bra. Siden 1998 har Apple gitt en årlig avkastning på 33 %. Ikke nok med det, velger vi perioden 11. mars 2009 til 17. oktober 2012 så får vi den årlige avkastningen opp i hele 78 %!

Kan vi da konkludere med at investeringer i oljefondet gir mye bedre avkastning enn statlige selskap? Jeg vil påstå at svaret er nei. Dette er bare én av mange investeringer i oljefondet. Jeg lurer på hva Gabrielsen mener.

En diskusjon der debattantene slår hverandre i hodet med tall som er møysommelig valgt for å passe egen argumentasjon er egentlig ganske uinteressant. Statlige selskaper ser ut til å gjøre det omtrent like bra eller dårlig som andre selskaper. Avkastning er ikke et argument for statlig eierskap.

Uriktige påstander fra Arbeiderpartiet og LO om meravkastningen for statlige selskaper har begynt å bli hyppig. Det er synd fordi det går utover troverdigheten til arbeiderbevegelsen, som ellers er ganske etterrettelig og ansvarlig. Tidligere har Arbeiderpartiets Else-May Botten, Marianne Martinsen og Jonas Gahr Støre plukket sine favoritteksempler. Det blir spennende å se hvem som blir nestemann ut.