cc - Dave's Blog


Where the best designers go to find photos and graphics

Jan 5, 3:09

List of useful free or CC licensed photography and icon sites.

PermalinkCommentsfree cc photo photography icon

Serializing JavaScript Promise Execution

2013 Aug 10, 3:07
Occasionally I have need to run a set of unrelated promises in series, for instance an object dealing with a WinRT camera API that can only execute one async operation at a time, or an object handling postMessage message events and must resolve associated async operations in the same order it received the requests. The solution is very simply to keep track of the last promise and when adding a new promise in serial add a continuation of the last promise to execute the new promise and point the last promise at the result. I encapsulate the simple solution in a�simple constructor:

    function PromiseExecutionSerializer() {
var lastPromise = WinJS.Promise.wrap(); // Start with an empty fulfilled promise.

this.addPromiseForSerializedExecution = function(promiseFunction) {
lastPromise = lastPromise.then(function () {
// Don't call directly so next promise doesn't get previous result parameter.
return promiseFunction();

The only thing to watch out for is to ensure you don't pass the result of a previous promise onto a subsequent promise that is unrelated.
PermalinkCommentsasync javascript promise technical

Considerate MessagePort Usage

2013 Aug 7, 7:14
Sharing by leezie5. Two squirrels sharing food hanging from a bird feeder. Used under Creative Commons license Attribution-NonCommercial-NoDerivs 2.0 Generic.When writing a JavaScript library that uses postMessage and the message event, I must be considerate of other JS code that will be running along side my library. I shouldn't assume I'm the only sender and receiver on a caller provided MessagePort object. This means obviously I should use addEventListener("message" rather than the onmessage property (see related What if two programs did this?). But considering the actual messages traveling over the message channel I have the issue of accidentally processing another libraries messages and having another library accidentally process my own message. I have a few options for playing nice in this regard:
Require a caller provided unique MessagePort
This solves the problem but puts a lot of work on the caller who may not notice nor follow this requirement.
Uniquely mark my messages
To ensure I'm acting upon my own messages and not messages that happen to have similar properties as my own, I place a 'type' property on my postMessage data with a value of a URN unique to me and my JS library. Usually because its easy I use a UUID URN. There's no way someone will coincidentally produce this same URN. With this I can be sure I'm not processing someone else's messages. Of course there's no way to modify my postMessage data to prevent another library from accidentally processing my messages as their own. I can only hope they take similar steps as this and see that my messages are not their own.
Use caller provided MessagePort only to upgrade to new unique MessagePort
I can also make my own unique MessagePort for which only my library will have the end points. This does still require the caller to provide an initial message channel over which I can communicate my new unique MessagePort which means I still have the problems above. However it clearly reduces the surface area of the problem since I only need once message to communicate the new MessagePort.
The best solution is likely all of the above.
Photo is Sharing by leezie5. Two squirrels sharing food hanging from a bird feeder. Used under Creative Commons license Attribution-NonCommercial-NoDerivs 2.0 Generic.
PermalinkCommentsDOM html javascript messagechannel postMessage programming technical

URI functions in Windows Store Applications

2013 Jul 25, 1:00


The Modern SDK contains some URI related functionality as do libraries available in particular projection languages. Unfortunately, collectively these APIs do not cover all scenarios in all languages. Specifically, JavaScript and C++ have no URI building APIs, and C++ additionally has no percent-encoding/decoding APIs.
WinRT (JS and C++)
JS Only
C++ Only
.NET Only
Relative resolution
Encode data for including in URI property
Decode data extracted from URI property
Build Query
Parse Query
The Windows.Foudnation.Uri type is not projected into .NET modern applications. Instead those applications use System.Uri and the platform ensures that it is correctly converted back and forth between Windows.Foundation.Uri as appropriate. Accordingly the column marked WinRT above is applicable to JS and C++ modern applications but not .NET modern applications. The only entries above applicable to .NET are the .NET Only column and the WwwFormUrlDecoder in the bottom left which is available to .NET.



This functionality is provided by the WinRT API Windows.Foundation.Uri in C++ and JS, and by System.Uri in .NET.
Parsing a URI pulls it apart into its basic components without decoding or otherwise modifying the contents.
var uri = new Windows.Foundation.Uri("");
console.log(uri.path);// /path%20segment1/path%20segment2

WsDecodeUrl (C++)

WsDecodeUrl is not suitable for general purpose URI parsing. Use Windows.Foundation.Uri instead.

Build (C#)

URI building is only available in C# via System.UriBuilder.
URI building is the inverse of URI parsing: URI building allows the developer to specify the value of basic components of a URI and the API assembles them into a URI.
To work around the lack of a URI building API developers will likely concatenate strings to form their URIs. This can lead to injection bugs if they don’t validate or encode their input properly, but if based on trusted or known input is unlikely to have issues.
����������� Uri originalUri = new Uri("");
����������� UriBuilder uriBuilder = new UriBuilder(originalUri);
����������� uriBuilder.Path = "/path2/";
����������� Uri newUri = uriBuilder.Uri; //

WsEncodeUrl (C++)

WsEncodeUrl, in addition to building a URI from components also does some encoding. It encodes non-US-ASCII characters as UTF8, the percent, and a subset of gen-delims based on the URI property: all :/?#[]@ are percent-encoded except :/@ in the path and :/?@ in query and fragment.
Accordingly, WsEncodeUrl is not suitable for general purpose URI building. It is acceptable to use in the following cases:
- You’re building a URI out of non-encoded URI properties and don’t care about the difference between encoded and decoded characters. For instance you’re the only one consuming the URI and you uniformly decode URI properties when consuming – for instance using WsDecodeUrl to consume the URI.
- You’re building a URI with URI properties that don’t contain any of the characters that WsEncodeUrl encodes.


This functionality is provided by the WinRT API Windows.Foundation.Uri in C++ and JS and by System.Uri in .NET. Normalization is applied during construction of the Uri object.
URI normalization is the application of URI normalization rules (including DNS normalization, IDN normalization, percent-encoding normalization, etc.) to the input URI.
������� var normalizedUri = new Windows.Foundation.Uri("HTTP://EXAMPLE.COM/p%61th foo/");
������� console.log(normalizedUri.absoluteUri); //
This is modulo Win8 812823 in which the Windows.Foundation.Uri.AbsoluteUri property returns a normalized IRI not a normalized URI. This bug does not affect System.Uri.AbsoluteUri which returns a normalized URI.


This functionality is provided by the WinRT API Windows.Foundation.Uri in C++ and JS and by System.Uri in .NET.
URI equality determines if two URIs are equal or not necessarily equal.
����������� var uri1 = new Windows.Foundation.Uri("HTTP://EXAMPLE.COM/p%61th foo/"),
��������������� uri2 = new Windows.Foundation.Uri("");
����������� console.log(uri1.equals(uri2)); // true

Relative resolution

This functionality is provided by the WinRT API Windows.Foundation.Uri in C++ and JS and by System.Uri in .NET
Relative resolution is a function that given an absolute URI A and a relative URI B, produces a new absolute URI C. C is the combination of A and B in which the basic components specified in B override or combine with those in A under rules specified in RFC 3986.
������� var baseUri = new Windows.Foundation.Uri(""),
��� ��������relativeUri = "/path?query#fragment",
��� ��������absoluteUri = baseUri.combineUri(relativeUri);
������� console.log(baseUri.absoluteUri);������ //
������� console.log(absoluteUri.absoluteUri);�� //

Encode data for including in URI property

This functionality is available in JavaScript via encodeURIComponent and in C# via System.Uri.EscapeDataString. Although the two methods mentioned above will suffice for this purpose, they do not perform exactly the same operation.
Additionally we now have Windows.Foundation.Uri.EscapeComponent in WinRT, which is available in JavaScript and C++ (not C# since it doesn’t have access to Windows.Foundation.Uri). This is also slightly different from the previously mentioned mechanisms but works best for this purpose.
Encoding data for inclusion in a URI property is necessary when constructing a URI from data. In all the above cases the developer is dealing with a URI or substrings of a URI and so the strings are all encoded as appropriate. For instance, in the parsing example the path contains “path%20segment1” and not “path segment1”. To construct a URI one must first construct the basic components of the URI which involves encoding the data. For example, if one wanted to include “path segment / example” in the path of a URI, one must percent-encode the ‘ ‘ since it is not allowed in a URI, as well as the ‘/’ since although it is allowed, it is a delimiter and won’t be interpreted as data unless encoded.
If a developer does not have this API provided they can write it themselves. Percent-encoding methods appear simple to write, but the difficult part is getting the set of characters to encode correct, as well as handling non-US-ASCII characters.
������� var uri = new Windows.Foundation.Uri("" +
����������� "/" + Windows.Foundation.Uri.escapeComponent("path segment / example") +
����������� "?key=" + Windows.Foundation.Uri.escapeComponent("=&?#"));
������� console.log(uri.absoluteUri); //

WsEncodeUrl (C++)

In addition to building a URI from components, WsEncodeUrl also percent-encodes some characters. However the API is not recommend for this scenario given the particular set of characters that are encoded and the convoluted nature in which a developer would have to use this API in order to use it for this purpose.
There are no general purpose scenarios for which the characters WsEncodeUrl encodes make sense: encode the %, encode a subset of gen-delims but not also encode the sub-delims. For instance this could not replace encodeURIComponent in a C++ version of the following code snippet since if ‘value’ contained ‘&’ or ‘=’ (both sub-delims) they wouldn’t be encoded and would be confused for delimiters in the name value pairs in the query:
"" + Windows.Foundation.Uri.escapeComponent(value)
Since WsEncodeUrl produces a string URI, to obtain the property they want to encode they’d need to parse the resulting URI. WsDecodeUrl won’t work because it decodes the property but Windows.Foundation.Uri doesn’t decode. Accordingly the developer could run their string through WsEncodeUrl then Windows.Foundation.Uri to extract the property.

Decode data extracted from URI property

This functionality is available in JavaScript via decodeURIComponent and in C# via System.Uri.UnescapeDataString. Although the two methods mentioned above will suffice for this purpose, they do not perform exactly the same operation.
Additionally we now also have Windows.Foundation.Uri.UnescapeComponent in WinRT, which is available in JavaScript and C++ (not C# since it doesn’t have access to Windows.Foundation.Uri). This is also slightly different from the previously mentioned mechanisms but works best for this purpose.
Decoding is necessary when extracting data from a parsed URI property. For example, if a URI query contains a series of name and value pairs delimited by ‘=’ between names and values, and by ‘&’ between pairs, one must first parse the query into name and value entries and then decode the values. It is necessary to make this an extra step separate from parsing the URI property so that sub-delimiters (in this case ‘&’ and ‘=’) that are encoded will be interpreted as data, and those that are decoded will be interpreted as delimiters.
If a developer does not have this API provided they can write it themselves. Percent-decoding methods appear simple to write, but have some tricky parts including correctly handling non-US-ASCII, and remembering not to decode .
In the following example, note that if unescapeComponent were called first, the encoded ‘&’ and ‘=’ would be decoded and interfere with the parsing of the name value pairs in the query.
����������� var uri = new Windows.Foundation.Uri("");
����������� uri.query.substr(1).split("&").forEach(
��������������� function (keyValueString) {
������������������� var keyValue = keyValueString.split("=");
������������������� console.log(Windows.Foundation.Uri.unescapeComponent(keyValue[0]) + ": " + Windows.Foundation.Uri.unescapeComponent(keyValue[1]));
������������������� // foo: bar
������������������� // array: ['','&','=','#']
��������������� });

WsDecodeUrl (C++)

Since WsDecodeUrl decodes all percent-encoded octets it could be used for general purpose percent-decoding but it takes a URI so would require the dev to construct a stub URI around the string they want to decode. For example they could prefix “http:///#” to their string, run it through WsDecodeUrl and then extract the fragment property. It is convoluted but will work correctly.

Parse Query

The query of a URI is often encoded as application/x-www-form-urlencoded which is percent-encoded name value pairs delimited by ‘&’ between pairs and ‘=’ between corresponding names and values.
In WinRT we have a class to parse this form of encoding using Windows.Foundation.WwwFormUrlDecoder. The queryParsed property on the Windows.Foundation.Uri class is of this type and created with the query of its Uri:
��� var uri = Windows.Foundation.Uri("");
��� uri.queryParsed.forEach(
������� function (pair) {
����������� console.log("name: " + + ", value: " + pair.value);
����������� // name: foo, value: bar
����������� // name: array, value: ['','&','=','#']
������� });
��� console.log(uri.queryParsed.getFirstValueByName("array")); // ['','&','=','#']
The QueryParsed property is only on Windows.Foundation.Uri and not System.Uri and accordingly is not available in .NET. However the Windows.Foundation.WwwFormUrlDecoder class is available in C# and can be used manually:
����������� Uri uri = new Uri("");
����������� WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query);
���� �������foreach (IWwwFormUrlDecoderEntry entry in decoder)
����������� {
��������������� System.Diagnostics.Debug.WriteLine("name: " + entry.Name + ", value: " + entry.Value);
��������������� // name: foo, value: bar
��������������� // name: array, value: ['','&','=','#']
����������� }

Build Query

To build a query of name value pairs encoded as application/x-www-form-urlencoded there is no WinRT API to do this directly. Instead a developer must do this manually making use of the code described in “Encode data for including in URI property”.
In terms of public releases, this property is only in the RC and later builds.
For example in JavaScript a developer may write:
������� ����var uri = new Windows.Foundation.Uri(""),
��������������� query = "?" + Windows.Foundation.Uri.escapeComponent("array") + "=" + Windows.Foundation.Uri.escapeComponent("['','&','=','#']");
����������� console.log(uri.combine(new Windows.Foundation.Uri(query)).absoluteUri); //'%E3%84%93'%2C'%26'%2C'%3D'%2C'%23'%5D
PermalinkCommentsc# c++ javascript technical uri windows windows-runtime windows-store

App Developer Agreement (Windows)

2013 Jun 21, 4:20

The Windows Store supports refunds and as the developer you are responsible for fulfilling those refunds even after Microsoft pays you. That seems reasonable I suppose but there’s no time limit mentioned…

"g. Reconciliation and Offset. You are responsible for all costs and expenses for returns and chargebacks of your app, including the full refund and chargeback amounts paid or credited to customers. Refunds processed after you receive the App Proceeds will be debited against your account. Microsoft may offset any amounts owed to Microsoft (including the refund and chargeback costs described in this paragraph) against amounts Microsoft owes you. Refunds processed by Microsoft can only be initiated by Microsoft; if you wish to offer a customer a refund, directly, you must do so via your own payment processing tools."

PermalinkCommentsmicrosoft developement software windows money

laughingsquid: ‘Veronica Mars’ TV Show Attempts to Make a Film...

2013 Mar 13, 11:38


‘Veronica Mars’ TV Show Attempts to Make a Film Via Crowdfunding

PermalinkCommentsveronica-mars movie kickstarter

math - What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision? - Stack Overflow

2013 Feb 5, 11:23

In JavaScript numbers are 64bit floating point numbers which have 53 bits of mantissa. That means you can accurately represent [-2^53, 2^53] as integers in JavaScript. Aka [-9007199254740992, 9007199254740992].

PermalinkCommentsjavascript math integer technical programming

Stripe CTF - Level 8

2012 Dec 7, 2:07
Level 8 of the Stripe CTF is a password server that returns success: true if and only if the password provided matches the password stored directly via a RESTful API and optionally indirectly via a callback URI. The solution is side channel attack like a timing attack but with ports instead of time.

(I found this in my drafts folder and had intended to post a while ago.)


    def nextServerCallback(self, data):
parsed_data = json.loads(data)
# Chunk was wrong!
if not parsed_data['success']:
# Defend against timing attacks
remaining_time = self.expectedRemainingTime()
self.log_info('Going to wait %s seconds before responding' %
reactor.callLater(remaining_time, self.sendResult, False)



The password server breaks the target password into four pieces and stores each on a different server. When a password request is sent to the main server it makes requests to the sub-servers for each part of the password request. It does this in series and if any part fails, then it stops midway through. Password requests may also be made with corresponding URI callbacks and after the server decides on the password makes an HTTP request on the provided URI callbacks saying if the password was success: true or false.
A timing attack looks at how long it took for a password to be rejected and longer times could mean a longer prefix of the password was correct allowing for a directed brute force attack. Timing attacks are prevented in this case by code on the password server that attempts to wait the same amount of time, even if the first sub-server responds with false. However, the server uses sequential outgoing port numbers shared between the requests to the sub-servers and the callback URIs. Accordingly, we can examine the port numbers on our callback URIs to direct a brute force attack.
If the password provided is totally incorrect then the password server will contact one sub-server and then your callback URI. So if you see the remote server's port number go up by two when requesting your callback URI, you know the password is totally incorrect. If by three then you know the first fourth of the password is correct and the rest is incorrect. If by four then two fourths of the password is correct. If by five then four sub-servers were contacted so you need to rely on the actual content of the callback URI request of 'success: true' or 'false' since you can't tell from the port change if the password was totally correct or not.
The trick in the real world is false positives. The port numbers are sequential over the system, so if the password server is the only thing making outgoing requests then its port numbers will also be sequential, however other things on the system can interrupt this. This means that the password server could contact three sub-servers and normally you'd see the port number increase by four, but really it could increase by four or more because of other things running on the system. To counteract this I ran in cycles: brute forcing the first fourth of the password and removing any entry that gets a two port increase and keeping all others. Eventually I could remove all but the correct first fourth of the password. And so on for the next parts of the password.
I wrote my app to brute force this in Python. This was my first time writing Python code so it is not pretty.
PermalinkCommentsbrute-force password python side-channel technical web

Windows Remote Desktop via Internet

2012 Dec 7, 2:04
To setup my home Windows�dev box to be accessible from outside I followed two main steps:
Last time I had to do this there was a service named which seems to still exist but no longer appears to be free. Instead I used which is free and has a web API as well as links to and instructions for setting up native tools to dynamically update my IP address.

A Slower Speed of Light Official Trailer — MIT Game Lab (by...

2012 Nov 13, 7:41

A Slower Speed of Light Official Trailer — MIT Game Lab (by Steven Schirra)

“A Slower Speed of Light is a first-person game in which players navigate a 3D space while picking up orbs that reduce the speed of light in increments. A custom-built, open-source relativistic graphics engine allows the speed of light in the game to approach the player’s own maximum walking speed. Visual effects of special relativity gradually become apparent to the player, increasing the challenge of gameplay. These effects, rendered in realtime to vertex accuracy, include the Doppler effect; the searchlight effect; time dilation; Lorentz transformation; and the runtime effect.

A production of the MIT Game Lab.

Play now for Mac and PC!

PermalinkCommentsscience game video-game mit 3d light-speed

DSL modem hack used to infect millions with banking fraud malware | Ars Technica

2012 Oct 1, 6:33

According to the links within this article, although the root URI of the router requires authentication, the /password.cgi URI doesn’t and the resulting returned HTML contains (but does not display) the plaintext of the password, as well as an HTML FORM to modify the password that is exploitable by CSRF.

The attack… infected more than 4.5 million DSL modems… The CSRF (cross-site request forgery) vulnerability allowed attackers to use a simple script to steal passwords required to remotely log in to and control the devices. The attackers then configured the modems to use malicious domain name system servers that caused users trying to visit popular websites to instead connect to booby-trapped imposter sites.

PermalinkCommentstechnical security html router web dns csrf

Ben Goldacre’s TED talk on publication bias, drug...

2012 Sep 28, 3:55

drug companies hiding the results of clinical trials.

(via I did a new talk at TED, on drug companies and hidden data.)

PermalinkCommentsscience video ted

theatlantic: How the 8.5” x 11” Piece of Paper Got Its...

2012 Sep 19, 6:37


How the 8.5” x 11” Piece of Paper Got Its Size

Why do we use a paper size that is so unfriendly for the basic task of reading? According to a very interesting post by Paul Stanley, the rough dimensions of office paper evolved to accommodate handwriting and typewriters with monospaced fonts, both of which rendered many fewer characters per line. “Typewriters,” he explains, “produced 10 or 12 characters per inch: so on (say) 8.5 inch wide paper, with 1 inch margins, you had 6.5 inches of type, giving … around 65 to 78 characters.” This, he says, is “pretty close to ideal.”

Read more. [Image: Picsfive/Shutterstock]

PermalinkCommentstechnical paper history

AbleGamers creates how-to accessibility guide for devs, publishers | Joystiq

2012 Sep 14, 4:20

A howto on making your video game accessible to those with disabilities (blind, color blind, deaf, etc)

The AbleGamers Foundation has created a 48-page document it hopes will serve as a how-to guide for game developers and publishers on how to create more accessible games. The in-depth guide by the disability non-profit covers in great detail how to make games available to those with varying degrees of mobility, hearing, visual and cognitive issues.

PermalinkCommentsgame technical video-game programming accessibility howto

Stripe CTF - Level 5

2012 Sep 11, 5:00

Level 5 of the Stripe CTF revolved around a design issue in an OpenID like protocol.


    def authenticated?(body)
body =~ /[^\w]AUTHENTICATED[^\w]*$/


if authenticated?(body)
session[:auth_user] = username
session[:auth_host] = host
return "Remote server responded with: #{body}." \
" Authenticated as #{username}@#{host}!"


This level is an implementation of a federated identity protocol. You give it an endpoint URI and a username and password, it posts the username and password to the endpoint URI, and if the response is 'AUTHENTICATED' then access is allowed. It is easy to be authenticated on a server you control, but this level requires you to authenticate from the server running the level. This level only talks to stripe CTF servers so the first step is to upload a document to the level 2 server containing the text 'AUTHENTICATED' and we can now authenticate on a level 2 server. Notice that the level 5 server will dump out the content of the endpoint URI and that the regexp it uses to detect the text 'AUTHENTICATED' can match on that dump. Accordingly I uploaded an authenticated file to
Using that as my endpoint URI means authenticating as level 2. I can then choose the following endpoint URI to authenticate as level 5.
Navigating to that URI results in the level 5 server telling me I'm authenticated as level 2 and lists the text of the level 2 file 'AUTHENTICATED'. Feeding this back into the level 5 server as my endpoint URI means level 5 seeing 'AUTHENTICATED' coming back from a level 5 URI.


I didn't see any particular code review red flags, really the issue here is that the regular expression testing for 'AUTHENTICATED' is too permisive and the protocol itself doesn't do enough. The protocol requires only a set piece of common literal text to be returned which makes it easy for a server to accidentally fall into authenticating. Having the endpoint URI have to return variable text based on the input would make it much harder for a server to accidentally authenticate.

PermalinkCommentsinternet openid security stripe-ctf technical web

Stripe CTF - XSS, CSRF (Levels 4 & 6)

2012 Sep 10, 4:43

Level 4 and level 6 of the Stripe CTF had solutions around XSS.

Level 4


> Registered Users 

  • <% @registered_users.each do |user| %>
    <% last_active = user[:last_active].strftime('%H:%M:%S UTC') %>
    <% if @trusts_me.include?(user[:username]) %>

  • <%= user[:username] %>
    (password: <%= user[:password] %>, last active <%= last_active %>)
  • Issue

    The level 4 web application lets you transfer karma to another user and in doing so you are also forced to expose your password to that user. The main user page displays a list of users who have transfered karma to you along with their password. The password is not HTML encoded so we can inject HTML into that user's browser. For instance, we could create an account with the following HTML as the password which will result in XSS with that HTML:

    This HTML runs script that uses jQuery to post to the transfer URI resulting in a transfer of karma from the attacked user to the attacker user, and also the attacked user's password.


    Code review red flags in this case included lack of encoding when using user controlled content to create HTML content, storing passwords in plain text in the database, and displaying passwords generally. By design the web app shows users passwords which is a very bad idea.

    Level 6



    def self.safe_insert(table, key_values)
    key_values.each do |key, value|
    # Just in case people try to exfiltrate
    # level07-password-holder's password
    if value.kind_of?(String) &&
    (value.include?('"') || value.include?("'"))
    raise "Value has unsafe characters"



    This web app does a much better job than the level 4 app with HTML injection. They use encoding whenever creating HTML using user controlled data, however they don't use encoding when injecting JSON data into script (see post_data initialization above). This JSON data is the last five most recent messages sent on the app so we get to inject script directly. However, the system also ensures that no strings we write contains single or double quotes so we can't get out of the string in the JSON data directly. As it turns out, HTML lets you jump out of a script block using no matter where you are in script. For instance, in the middle of a value in some JSON data we can jump out of script. But we still want to run script, so we can jump right back in. So the frame so far for the message we're going to post is the following:

PermalinkCommentscsrf encoding html internet javascript percent-encoding script security stripe-ctf technical web xss

Stripe CTF - Input validation (Levels 1 & 2)

2012 Sep 6, 5:00

Stripe's web security CTF's Level 1 and level 2 of the Stripe CTF had issues with missing input validation solutions described below.

Level 1


          $filename = 'secret-combination.txt';
if (isset($attempt)) {
$combination = trim(file_get_contents($filename));
if ($attempt === $combination) {


The issue here is the usage of the extract php method which extracts name value pairs from the map input parameter and creates corresponding local variables. However this code uses $_GET which contains a map of name value pairs passed in the query of the URI. The expected behavior is to get an attempt variable out, but since no input validation is done I can provide a filename variable and overwrite the value of $filename. Providing an empty string gives an empty string $combination which I can match with an empty string $attempt. So without knowing the combination I can get past the combination check.


Code review red flag in this case was the direct use of $_GET with no validation. Instead of using extract the developer could try to extract specifically the attempt variable manually without using extract.

Level 2


    $dest_dir = "uploads/";
$dest = $dest_dir . basename($_FILES["dispic"]["name"]);
$src = $_FILES["dispic"]["tmp_name"];
if (move_uploaded_file($src, $dest)) {
$_SESSION["dispic_url"] = $dest;
chmod($dest, 0644);
echo "

Successfully uploaded your display picture.



This code accepts POST uploads of images but with no validation to ensure it is not an arbitrary file. And even though it uses chmod to ensure the file is not executable, things like PHP don't require a file to be executable in order to run them. Accordingly, one can upload a PHP script, then navigate to that script to run it. My PHP script dumped out the contents of the file we're interested in for this level:


Code review red flags include manual file management, chmod, and use of file and filename inputs without any kind of validation. If this code controlled the filename and ensured that the extension was one of a set of image extensions, this would solve this issue. Due to browser mime sniffing its additionally a good idea to serve a content-type that starts with "image/" for these uploads to ensure browsers treat these as images and not sniff for script or HTML.

PermalinkCommentsinput-validation php security technical

Stripe CTF - SQL injections (Levels 0 & 3)

2012 Sep 5, 9:10

Stripe's web security CTF's level 0 and level 3 had SQL injection solutions described below.

Level 0


app.get('/*', function(req, res) {
var namespace = req.param('namespace');

if (namespace) {
var query = 'SELECT * FROM secrets WHERE key LIKE ? || ".%"';
db.all(query, namespace, function(err, secrets) {


There's no input validation on the namespace parameter and it is injected into the SQL query with no encoding applied. This means you can use the '%' character as the namespace which is the wildcard character matching all secrets.


Code review red flag was using strings to query the database. Additional levels made this harder to exploit by using an API with objects to construct a query rather than strings and by running a query that only returned a single row, only ran a single command, and didn't just dump out the results of the query to the caller.

Level 3


@app.route('/login', methods=['POST'])
def login():
username = flask.request.form.get('username')
password = flask.request.form.get('password')

if not username:
return "Must provide username\n"

if not password:
return "Must provide password\n"

conn = sqlite3.connect(os.path.join(data_dir, 'users.db'))
cursor = conn.cursor()

query = """SELECT id, password_hash, salt FROM users
WHERE username = '{0}' LIMIT 1""".format(username)

res = cursor.fetchone()
if not res:
return "There's no such user {0}!\n".format(username)
user_id, password_hash, salt = res

calculated_hash = hashlib.sha256(password + salt)
if calculated_hash.hexdigest() != password_hash:
return "That's not the password for {0}!\n".format(username)


There's little input validation on username before it is used to constrcut a SQL query. There's no encoding applied when constructing the SQL query string which is used to, given a username, produce the hashed password and the associated salt. Accordingly one can make username a part of a SQL query command which ensures the original select returns nothing and provide a new SELECT via a UNION that returns some literal values for the hash and salt. For instance the following in blue is the query template and the red is the username injected SQL code:

SELECT id, password_hash, salt FROM users WHERE username = 'doesntexist' UNION SELECT id, ('5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8') AS password_hash, ('word') AS salt FROM users WHERE username = 'bob' LIMIT 1
In the above I've supplied my own salt and hash such that my salt (word) plus my password (pass) hashed produce the hash I provided above. Accordingly, by providing the above long and interesting looking username and password as 'pass' I can login as any user.


Code review red flag is again using strings to query the database. Although this level was made more difficult by using an API that returns only a single row and by using the execute method which only runs one command. I was forced to (as a SQL noob) learn the syntax of SELECT in order to figure out UNION and how to return my own literal values.

PermalinkCommentssecurity sql sql-injection technical web-security

When they went to the Moon, they received the same per diem...

2012 Aug 28, 4:38

When they went to the Moon, they received the same per diem compensation as they would have for being away from base in Bakersfield: eight dollars a day, before various deductions (like for accommodation, because the government was providing the bed in the spaceship).


Apollo 11’s Astronauts Received an $8 Per Diem for the Mission to the Moon

The astronauts of Apollo 11: Intrepid explorers. Inspirational heroes. Government employees.

Read more. [Image: Reuters]

PermalinkCommentshumor space nasa moon government

Web Security Contest - Stripe CTF

2012 Aug 27, 4:18

Stripe is running a web security capture the flag - a series of increasingly difficult web security exploit challenges. I've finished it and had a lot of fun. Working on a web browser I knew the theory of these various web based attacks, but this was my first chance to put theory into practice with:

  • No adverse consequences
  • Knowledge that there is a fun security exploit to find
  • Access to the server side source code

Here's a blog post on the CTF behind the scenes setup which has many impressive features including phantom users that can be XSS/CSRF'ed.

I'll have another post on my difficulties and answers for the CTF levels after the contest is over on Wed, but if you're looking for hints, try out the CTF chatroom or the level specific CTF chatroom.

PermalinkCommentscontest security technical
Older Entries Creative Commons License Some rights reserved.