Showing posts with label CAPTCHA. Show all posts
Showing posts with label CAPTCHA. Show all posts

Tuesday, 28 August 2018

A look at User Authentication Factors (Part 2/2)

An authentication system is made out of authentication factors. There may be multiple factors, but whether a system is Single-factor Authentication, Two-factor Authentication (2FA) or Three-factor Authentication (3FA), depends on the number of different authentication factor types. For example, a simple Login screen is Single-factor authentication, even though the user has to key in both a login id and a password.

Instagram login screen.
Why? There are two authentication factors. But both of them are the same authentication type - Knowledge. That means there is only one authentication factor type in play. Even if you had to key in five passwords to be allowed entry, that would still be Single-factor Authentication.

Examples of Single-factor Authentication

As previously stated, a typical login screen is Single-factor Authentication. So is any type of system that only uses one authentication factor type.

ActiveSG gantry.
Like the gantries in ActiveSG swimming complexes. You scan your NRIC (a Possession authentication factor type), and it opens up.

Unlocking your mobile phone can be done via thumbprint scan (Inherence), facial recognition (Inherence) or a PIN (Knowledge). That's Single-factor Authentication.

Examples of Two-factor Authentication (2FA)

As mentioned previously, using your SingPass is 2FA. You key in your login id and password (Knowledge), then the systems sends an OTP to your mobile phone (Possession) for you to continue the login process.

Automatic Teller Machine.
Using an Automated Teller Machine (ATM) requires you to have your ATM card (Possession) and your PIN number (Knowledge).

The gantries in Changi Airport (all terminals) are 2FA. First, you scan your passport (Possession) and then your thumbprint (Inherence).

Examples of Three-factor Authentication (3FA)

There are virtually no examples of 3FA on websites. Biometrics are all but impossible right now on browsers. (CAPTCHA doesn't count because while it does - kind of - verify that you're not a bot, it can't verify that you're you.) Therefore, we're limited to only two authentication factor types - Knowledge and Possession.

Hi-tech security.

However, advanced security systems might require an electronic pass, a biometric scan and a passcode. That would qualify as 3FA.

That's all...

I just really wanted to explain 2FA. This might be a little more information than required. Hope this was interesting enough!

Thanks for tuning in! I had a scan-dalously good time.
T___T

Tuesday, 21 July 2015

Web Tutorial: The CAPTCHA (Part 4/4)

And finally. We're going to distort the image that your tt_getcaptcha.php script sends to your front-end.

Usually this involves a graphics library, but that's too much like work. Instead, I'm going to generate three sets of digits from 0 to 9, using CSS shapes. You may recall that earlier this year, I put up a web tutorial detailing how to use CSS to simulate Chinese brush strokes. Well, we're going to use the same techniques here. This CSS code will be written right into the PHP script.

Confused yet? Or intimidated? Don't be. It'll all become clear presently. Open your tt_getcaptcha.php file, and add the following code to your existing code.

tt_getcaptcha.php
<?php
session_start();

$numbers=array();

for ($i=0;$i<=9;$i++)
{
    $numbers[$i]=array();

    for ($j=0;$j<=2;$j++)
    {
        $numbers[$i][$j]=array();
    }   
}


$_SESSION["captcha"]="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;
}

echo $_SESSION["captcha"];
?>


Here, I have 3 sets of numbers for 0 to 9. So I'm going to use a multi-dimensional array $numbers to store them. So I declare the number of numbers (0 to 9) as one dimension, Each element, from 0 to 9, has 3 variations, from 0 to 2. Here's a tabular representation of the array below.

Set 0 Set 1 Set 2
$numbers[0] [0][0] [0][1] [0][2]
$numbers[1] [1][0] [1][1] [1][2]
$numbers[2] [2][0] [2][1] [2][2]
$numbers[3] [3][0] [3][1] [3][2]
$numbers[4] [4][0] [4][1] [4][2]
$numbers[5] [5][0] [5][1] [5][2]
$numbers[6] [6][0] [6][1] [6][2]
$numbers[7] [7][0] [7][1] [7][2]
$numbers[8] [8][0] [8][1] [8][2]
$numbers[9] [9][0] [9][1] [9][2]

Now, each number of each set requires a certain number of strokes to represent it. For instance, element $numbers[3][2] is the number "3" in set 2.

We'll require 2 strokes to render the number "3". So do this:

<?php
session_start();

$numbers=array();

for ($i=0;$i<=9;$i++)
{
    $numbers[$i]=array();

    for ($j=0;$j<=2;$j++)
    {
        $numbers[$i][$j]=array();
    }   
}

$numbers[3][2][0]=array();
$numbers[3][2][0]["width"]="20px";
$numbers[3][2][0]["height"]="20px";
$numbers[3][2][0]["box-shadow"]="5px 2px 0 0px";
$numbers[3][2][0]["margin"]="5px auto 0px 5px";
$numbers[3][2][0]["rotate"]=0;

$numbers[3][2][1]=array();
$numbers[3][2][1]["width"]="20px";
$numbers[3][2][1]["height"]="20px";
$numbers[3][2][1]["box-shadow"]="5px 2px 0 0px";
$numbers[3][2][1]["margin"]="22px auto 0px -4px";
$numbers[3][2][1]["rotate"]=0;


$_SESSION["captcha"]="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;
}

echo $_SESSION["captcha"];
?>

OK, what I did here was to create yet another array inside each array element to store the strokes. $numbers[3][2][0] stores the first stroke, and $numbers[3][2][0] stores the second stroke. These two strokes make up the number "3".

See?

And each stroke is also an array which stores the CSS properties and values of that stroke so we can render them later. That makes $numbers a four-dimensional array.

Wow.

Anyway. there's the entire set. See the number "3" on the bottom row? That's the one we just drew. Number "3", set 2 ($numbers[3][2]).


I've done the same with all the other numbers in all the sets. The code is here, and I'm not about to replicate them on-screen in this blogpost. The good news is, you can just go and copy-paste from the link without having to listen to any more of this drivel. I agree that it's a bit more complicated than it needed to be here.

Let's get on with it!

So I assume you've copied the contents of the entire four-dimensional array. What next? Why, outputting the relevant numbers on the screen, of course! Make the following changes.

<?php
.
.
.
(for the rest of the code, click here)
.
.
.
$_SESSION["captcha"]="";
$captcha_content="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;

    $random_set=rand(0,2);

    $random_degree=rand(-25,25);

}

echo $captcha_content;
?>

Here, we define a new variable $captcha_content which will hold all the HTML codes that we'll be generating. And we'll output $captcha_content in place of $_SESSION["captcha"].

$random_set defines which set of numbers you'll use.

$random_degree is a number that will cause your number to be rotated by that many degrees, randomly.

Next, we'll begin adding data to $captcha_content. It begins with an outer div for each number, which will be totated by $random_degree degrees.
<?php
for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;

    $random_set=rand(0,2);

    $random_degree=rand(-25,25);

    $captcha_content.="<div style=\"display:inline-block;width:30px;height:50px;margin-left:-5px;-ms-transform: rotate(".$random_degree."deg);-webkit-transform: rotate(".$random_degree."deg);transform: rotate(".$random_degree."deg);\">";

    $captcha_content.="</div>";
}

echo $captcha_content;
?>

And the last segment of code, in a Foreach Loop. For each stroke in each selected digit, the HTML and CSS will be written into the containing outer div.
<?php
for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;

    $random_set=rand(0,2);

    $random_degree=rand(-25,25);

    $captcha_content.="<div style=\"display:inline-block;width:30px;height:50px;margin-left:-5px;-ms-transform: rotate(".$random_degree."deg);-webkit-transform: rotate(".$random_degree."deg);transform: rotate(".$random_degree."deg);\">";

    foreach($numbers[$captcha_char][$random_set] as $stroke)
    {
        $captcha_content.="<div style=\"position:absolute;-webkit-border-radius: 63px 63px 63px 63px / 108px 108px 72px 72px;border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;";
        $captcha_content.="width:".$stroke["width"].";";
        $captcha_content.="height:".$stroke["height"].";";
        $captcha_content.="box-shadow:".$stroke["box-shadow"].";";
        $captcha_content.="margin:".$stroke["margin"].";";
        $captcha_content.="-ms-transform: rotate(".$stroke["rotate"]."deg);";
        $captcha_content.="-webkit-transform: rotate(".$stroke["rotate"]."deg);";
        $captcha_content.="transform: rotate(".$stroke["rotate"]."deg);";
        $captcha_content.="\">";
        $captcha_content.="</div>";
    }


    $captcha_content.="</div>";
}

echo $captcha_content;
?>


Now run your code again. This is what you should see.

And that completes your web tutorial. There's a lot more you could do with this - introduce wavy lines or circles to further confuse any bots that hackers might try to sneak past you. But in essence, this is the CAPTCHA.

That was a lot to digest. Sorry to have CAPT you waiting!
T___T

Saturday, 18 July 2015

Web Tutorial: The CAPTCHA (Part 3/4)

You've put up the front-end. You've written a back-end script to output a random 6-digit sequence to your front-end. It's now time to write the next part of your CAPTCHA - the comparison script.

Add the following JavaScript code to your front-end, in the head tag.
        <script>
        function compareCaptcha()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    alert(xmlhttp.responseText);
                    getCaptcha();
                }
            }

            xmlhttp.open("POST","tt_comparecaptcha.php",true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("captcha="+document.getElementById("txtCaptcha").value);
        }


        function getCaptcha()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("lblCaptcha").innerHTML=xmlhttp.responseText;
                }
            }

            xmlhttp.open("POST","tt_getcaptcha.php",true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send();
        }
        </script>


The compareCaptcha() function takes input from the txtCaptcha text box and sends it to the back-end script tt_comparecaptcha.php. If there's a match, or not, it will announce the result via the command alert(xmlhttp.responseText). It will then regenerate the CAPTCHA.

Now modify your front-end with this little nugget, so the compareCaptcha() function will fire off once you click the submit button.
    <body onload="getCaptcha();">
        Please enter the numbers you see below:    <input maxlength="6" id="txtCaptcha" /><input type="button" value="Send" onclick="compareCaptcha();">
        <br />
        <div id="lblCaptcha" style="height:50px;width:160px;border:1px solid #AAAAAA;overflow:hidden;padding-left:20px;"></div>
        <a href="#" onclick="getCaptcha();">Get a new image</a>
    </body>


All done? Excellent. We're going to write the script next. Create a new file and fill it in as follows:

tt_comparecaptcha.php
<?php
session_start();
?>


Again, we have the session_start() line to ensure that we're still running the session. This means that the $_SESSION["captcha"] variable is still active, and still holds the same value as the last time you generated it.

So all we need to do now is the following. This gets the value that the user entered into the text box.
<?php
session_start();

$captcha=$_POST["captcha"];
?>


And this compares it with the $_SESSION["captcha"] variable, then outputs a result message which the earlier JavaScript is supposed to pick up.
<?php
session_start();

$captcha=$_POST["captcha"];

if ($captcha==$_SESSION["captcha"])
{
    echo "Captcha successful!";
}
else
{
    echo "Value did not match.";
}

?>


Now, run your front-end. Type in a correct sequence. What happens?


How about an incorrect sequence?


And there we are! A functioning CAPTCHA. Give yourself a pat on the back!

But hold up - there's something off about this CAPTCHA. It's too neat. A robot could read that sequence easily. So what do we do about that?

Next

Obfuscating your CAPTCHA. We're going to write some code that garbles up the display a bit so it's readable only to a human being. We hope!

Wednesday, 15 July 2015

Web Tutorial: The CAPTCHA (Part 2/4)

You've created the front-end for your CAPTCHA. And also added a getCaptcha() function to call a PHP script tt_getcaptcha.php.

And today, we'll be creating the script for this little sucker. It will be incomplete and we'll need to come back to it sometime in the later parts of this tutorial.

First off, let's start by creating the file in a text editor.

tt_getcaptcha.php
<?php
session_start();
?>


This is important! The session_start() line creates  a session. We need to maintain a session in order to store the value for the CAPTCHA.

More on session_start(): (http://php.net/manual/en/function.session-start.php)
More on session variables in general:  (http://www.w3schools.com/php/php_sessions.asp)

<?php
session_start();

$_SESSION["captcha"]="";
?>


Here, we declare a key captcha in the system-defined array $_SESSION, which was in turn created with session_start(). This is initialized to an empty string.

<?php
session_start();

$_SESSION["captcha"]="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;

}
?>


Now, we have a For loop! It iterates 6 times, as you can see. That's because we're going to generate a 6-dignit CAPTCHA sequence. You can fiddle with this number if you want, but this may mean you have to increase the length of your lblCaptcha div.

So here we generate a random number from 0 to 9, and assign it to the variable $captcha_char. $captcha_char is then appended to the $_SESSION["captcha"] variable.

One last line and we're ready to test!
<?php
session_start();

$_SESSION["captcha"]="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;
}

echo $_SESSION["captcha"];
?>


This basically is the content that the getCaptcha() function is supposed to retrieve.

So run your code. When you load the page, do you see a random set of numbers in the box? Does the same happen if you click the "Get a new image" link?



There you go!

We now have a CAPTCHA generator. But it's still rather primitive, and there's a fair amount of work left to be done. In fact, after we complete the next bit of code, we'll need to improve this further.

Next

Comparing the CAPTCHA to user input. Another script coming right up.



Sunday, 12 July 2015

Web Tutorial: The CAPTCHA (Part 1/4)

Howdy!

Today, your friendly neighborhood web geek will be showing you how to implement a CAPTCHA.

The CAPTCHA's nothing new. You've probably run into it while filling up the odd web form. CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart" and is more or less what it says - there's a distorted sequence of letters and/or numbers, a text box for you to enter that text in, and a button which, if clicked, will compare your input against the sequence to determine if you're human or bot.

For more background, follow this link. (http://en.wikipedia.org/wiki/CAPTCHA)

There are a lot of free CAPTCHA plugins floating around the web that you can implement, but it's important that you know how it works. And really, it's not all that difficult to figure out, and implement your own.

What do I need?

That's the spirit! Now, the CAPTCHA we'll be making is made out of AJAX code, using a combination of HTML, CSS, JavaScript and PHP. Here are the components.

- a front-end layout comprising of a placeholder for your CAPTCHA sequence,a textbox for user input, a button for submission, and a button to reload the CAPTCHA.
- a back-end PHP script to randomly generate a sequence of letters and/or numbers
- a back-end PHP script to compare user input to that sequence.
- a distorter to visually warp the sequence so that it's not easily machine-readable. Some guys like to use a graphics library for this. We'll just be using good old CSS.
- front-end AJAX scripts to send user input to the back-end PHP scripts mentioned above.

Do note that this is not instant code - you'll need to run this setup on a web server.

To begin...

Here's the easiest part: The front-end layout. use the HTML/CSS code below:

tt_captcha.html
<!DOCTYPE html>
<html>
    <head>
        <title>CSS Captcha</title>
    </head>

    <body>
        Please enter the numbers you see below:    <input maxlength="6" id="txtCaptcha" /><input type="button" value="Send">
        <br />
        <div id="lblCaptcha" style="height:50px;width:160px;border:1px solid #AAAAAA;overflow:hidden;padding-left:20px;"></div>
        <a href="#">Get a new image</a>
    </body>
</html>


The HTML code is straightforward. You have a text box, and then you have a button labelled Send which does nothing at the moment. Then below it, you have a lblCaptcha div which holds the CAPTCHA sequence. And below that is a link which, when clicked, is supposed to generate a new sequence. At this moment, this link does nothing either.


Here's what the CSS does for the lblCaptcha div.

border:1px solid #AAAAAA - gives it a nice grey border.
overflow:hidden - makes sure any overlapping stuff is trimmed off.

Now we're going to add an AJAX script to call a PHP script. Add the following JavaScript to your head tag.
    <head>
        <title>CSS Captcha</title>

        <script>
        function getCaptcha()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("lblCaptcha").innerHTML=xmlhttp.responseText;
                }
            }

            xmlhttp.open("POST","tt_getcaptcha.php",true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send();
        }
        </script>

    </head>

    <body>
        Please enter the numbers you see below:    <input maxlength="6" id="txtCaptcha" /><input type="button" value="Send">
        <br />
        <div id="lblCaptcha" style="height:50px;width:160px;border:1px solid #AAAAAA;overflow:hidden;padding-left:20px;"></div>
        <a href="#">Get a new image</a>
    </body>
</html>


The getCaptcha() function calls the tt_getcaptcha.php script without any arguments, signalling to the script to generate a CAPTCHA sequence, and then display the sequence in the lblCaptcha div.

So now add the following snippets to your HTML
    <body onload="getCaptcha();">
        Please enter the numbers you see below:    <input maxlength="6" id="txtCaptcha" /><input type="button" value="Send">
        <br />
        <div id="lblCaptcha" style="height:50px;width:160px;border:1px solid #AAAAAA;overflow:hidden;padding-left:20px;"></div>
        <a href="#" onclick="getCaptcha();">Get a new image</a>
    </body>


This ensures that the page calls the getCaptcha() function to generate a CAPTCHA sequence as soon as the page loads. The same function is called when you hit the "Get a new image" link.

In this function, document.getElementById("lblCaptcha").innerHTML=xmlhttp.responseText is the line that fills the lblCaptcha div with the results returned from the tt_getcaptcha.php script.

Next

Nothing works yet, sparky! We still need to write and test some PHP scripts. Stay tuned!