Click here to Skip to main content
6,822,123 members and growing! (14,824 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Building ASP.NET Bot protection (CAPTCHA-like)

By Dmitry Salko

Shows how to build captcha like protection from spam and other bots.
C#2.0, Windows, .NET2.0, ASP.NET, WebForms, VS2005, Dev
Posted:7 Oct 2007
Updated:15 Oct 2007
Views:36,391
Bookmarked:56 times
Unedited contribution
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
20 votes for this article.
Popularity: 5.23 Rating: 4.02 out of 5

1
4 votes, 20.0%
2
2 votes, 10.0%
3
2 votes, 10.0%
4
12 votes, 60.0%
5
Screenshot - captcha.jpg

Introduction

One day I've decided to build own CAPTCHA for my project. Why? First of all I need quite strong bot protection. Second reason � I want to make my contribution for the community. That's why I decided to make this project completely free for use.

Why I'm thinking that result of my work is a real strong protection? First of all it's new � so there are no ready OCR's for this one. Also, you can change it by yourself � and receive completely different CAPTCHA. I'm calling my CAPTCHA "ADSS AntiBot". I've a friend, he breaking such security using OCR. He said � not very bad.

You can make your own protection based on this (link to us greatly appreciated, ADSS).

Background

Everybody knows that world wide web filled up with spam bots. And webmaster (usually using developers) fight against this problem. Because every webmaster dreams about real visitors, not about thousands of bots that using some service and even resell it on another web site. So, the things known as CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") were made to fight against bots. I'm using term AntiBot for my application.


Using the code

How to use downloaded source? Very easy. Just put some image on your asp.net page with ImageURL set to captcha.ashx. This handler generates new image each time it accessed, and stores right value into the session.

string number_server_side = (string)Session[ADSSAntiBot.SESSION_CAPTCHA];
if (number_server_side == TextBox_number.Text)
            {
// The code entered is valid

            }
            else
            {
// The code entered invalid

            }

This way you can use created HTTP handler.

Another thing, I want to note, the image size. You can easily set it using ADSSAntiBot public constructor inside ProcessRequest function of handler.

     public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";
        ADSSAntiBot captcha = new ADSSAntiBot(300,80); // Set size using constructor

        string str = captcha.DrawNumbers(5);
        if (context.Session[ ADSSAntiBot.SESSION_CAPTCHA] == null) context.Session.Add(ADSSAntiBot.SESSION_CAPTCHA, str);
        else
        {
            context.Session[ ADSSAntiBot.SESSION_CAPTCHA] = str;
        }
        Bitmap bmp = captcha.Result;
        bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
 

Next picture shows result of this code. Sometimes you want large image, sometimes smaller.


Screenshot - large_captcha.jpg

Points of Interest

So, how we are creating this "hard to OCR" image? And how to improve it?

We are using GraphicsPath to warp image. Basically transformations is sin wave, regular random noise and some rotation. What is the goal? To create text that can be read by the human, not by the bot. How we are making this? We are "shaking" subpaths of our text.

So, what is the goal of transform? First of all, we need to change it to make a letter separation hard. For this we are adding line through all the number displayed. Second thing, we need to remember, our numbers should be hard to OCR using a neural network. By moving path points randomly and by sin wave we are making line very think in some places. On the sample image, you can see this effect on "9" and "6".

The following function is the heart of our transformation:

    public GraphicsPath RandomWarp(GraphicsPath path)
    {
        // Add line //

        int PsCount = 10;
        PointF[] curvePs = new PointF[PsCount * 2];
        for (int u = 0; u < PsCount; u++)
        {
            curvePs[u].X = u * (Width / PsCount);
            curvePs[u].Y = Height / 2;
        }
        for (int u = PsCount; u < (PsCount * 2); u++)
        {
            curvePs[u].X = (u - PsCount) * (Width / PsCount);
            curvePs[u].Y = Height / 2 + 2;
        }
        path.AddLines(curvePs);
       
        double eps = Height * 0.05;
        double amp = rnd.NextDouble() * (double)(Height / 3);
        double size = rnd.NextDouble() * (double)(Width / 4) + Width / 8;
        double offset = (double)(Height / 3);

        PointF[] pn = new PointF[path.PointCount];
        byte[] pt = new byte[path.PointCount];

        GraphicsPath np2 = new GraphicsPath();

        GraphicsPathIterator iter = new GraphicsPathIterator(path);
        for (int i = 0; i < iter.SubpathCount; i++)
        {
            GraphicsPath sp = new GraphicsPath();
            bool closed;
            iter.NextSubpath(sp, out closed);

            Matrix m = new Matrix();
            m.RotateAt(Convert.ToSingle(rnd.NextDouble() * 30 - 15), sp.PathPoints[0]);
            m.Translate(-1 * i, 0);
            sp.Transform(m);
            np2.AddPath(sp, true);
        }
        for (int i = 0; i < np2.PointCount; i++)
        {
            pn[i] = Wave(np2.PathPoints[i], amp, size);
            pt[i] = np2.PathTypes[i];
        }
        GraphicsPath newpath = new GraphicsPath(pn, pt);
        return newpath;
    }  

We are not using lot of fonts like others do, not using colors. Color model only helps OCRing many captchas, font is not an obstacle too. But here we are making "random" font using this warp. I just wanted to show that .net framework makes it possible to protect site from Bots much better then other web languages. Also, I'm interesting in your suggestions about non-captcha bot protections. I'm going to continue my research in this direction.

History

The code described in this article is complete freeware. You can try it online.

Also, you can download the last version on ADSS Web Site.

Feel free to create your CAPTCHAs based on this one to fight against spam.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Dmitry Salko


Member

Occupation: Web Developer
Location: Ukraine Ukraine

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 19 of 19 (Total in Forum: 19) (Refresh)FirstPrevNext
GeneralVery Very Nice Pinmemberblagoja22:44 30 Jul '09  
GeneralI used in my project and convert it into vb Thanks for your code Pinmemberjefferycxl17:56 20 Jan '09  
GeneralHelp please! PinmemberPatrik Svitek12:26 11 Mar '08  
GeneralCaptcha not working with UpdatePanel PinmemberMember 32361030:15 11 Feb '08  
GeneralRe: Captcha not working with UpdatePanel Pinmembermacload10:24 14 Dec '09  
GeneralBrowser incompatibility? Pinmembernemopeti10:02 15 Oct '07  
GeneralRe: Browser incompatibility? PinmemberDmitry Salko10:09 15 Oct '07  
General4 out of 5 Bad Pinmembercrb90005:49 9 Oct '07  
GeneralRe: 4 out of 5 Bad PinmemberDmitry Salko6:23 9 Oct '07  
GeneralNice code, but nothing new PinmemberSire4045:44 9 Oct '07  
GeneralRe: Nice code, but nothing new PinmemberDmitry Salko6:01 9 Oct '07  
GeneralRe: Nice code, but nothing new PinmemberSire4046:09 9 Oct '07  
QuestionWhat about vision impaired surfers? PinmemberBcouch2:51 9 Oct '07  
AnswerRe: What about vision impaired surfers? PinmemberDmitry Salko4:36 9 Oct '07  
GeneralVery Nice Pinmembermerlin9815:31 8 Oct '07  
GeneralRe: Very Nice PinmemberDmitry Salko5:37 8 Oct '07  
GeneralNice PinmemberBen Daniel13:51 7 Oct '07  
GeneralRe: Nice PinmemberDmitry Salko23:14 7 Oct '07  
GeneralRe: Nice PinmemberBen Daniel21:42 15 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 15 Oct 2007
Editor:
Copyright 2007 by Dmitry Salko
Everything else Copyright © CodeProject, 1999-2010
Web10 | Advertise on the Code Project