Code Monkey home page Code Monkey logo

politecaptcha's Introduction

PoliteCaptcha is a spam prevention library for use with ASP.NET MVC 3 forms.

Forcing humans to fill in forms with hard-to-read images because we can't tell them apart from maliciously-crafted computer programs is rude. PoliteCaptcha attempts to verify that the user's agent is a real web browser (via JavaScript and DOM manipulation, using a technique adapted from Sam Saffron) before falling back to the use of a rude CAPTCHA (by default, reCAPTCHA--if you're going to be rude, at least do some good while you're at it). Very few spam programs run within a full web browser or have full support for JavaScript and the DOM, so this thwarts nearly all automated spam programs from exploiting your ASP.NET MVC app's forms.

A live demo of PoliteCaptcha is available at http://politecaptcha.apphb.com.

Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Installing PoliteCaptcha

Install PoliteCaptcha via NuGet: Install-Package PoliteCaptcha. If you cannot use NuGet for some reason, you can build the source yourself by cloning this repository, then running the Build-Solution.ps1 script in the repo's root, and then getting the PoliteCaptcha.dll from the _build folder.

Configuring PoliteCaptcha

reCAPTCHA requires a public and private API key. You must specify these keys in your app's configuration, as follows:

<appSettings>
  <add key="reCAPTCHA::PublicKey" value="6LehOM0SAAAAAPgsjOy-6_grqy1JiB_W_jJa_aCw" />
  <add key="reCAPTCHA::PrivateKey" value="6LehOM0SAAAAAC5LsEpHoyyMqJcz7f_zEfqm66um" />
</appSettings>

PoliteCaptcha uses default API keys for reCAPTCHA that only work for requests to http://localhost. If the API key app settings aren't configured when generating or validating reCAPTCHA for non-local requests, an invalid operation exception will be thrown.

Using PoliteCaptcha

Using PoliteCaptcha is very similar to using ASP.NET MVC's built-in anti-forgery support. First, invoke the Html.SpamPreventionFields() and Html.SpamPreventionScript() HTML helpers in your views that have forms needing spam prevention, to render the required form fields and JavaScript. Next, add the [ValidateSpamPrevention] attribute to the controller actions that process those forms. For example:

// in your controller, add the ValidateSpamPrevention attribute to actions that handle forms
[HttpPost, ValidateSpamPrevention]
public ActionResult RegisterMember(RegisterMemberRequest request)
{
	// ...
}
@* in your view's form, invoke the SpamPreventionFields() HTML helper *@
@using (Html.BeginForm())
{
    @Html.EditorForModel()
    @Html.SpamPreventionFields()
    <input type="submit" value="Submit" />
}

@* in your view's scripts section (or in the layout), invoke the SpamPreventionScript() HTML helper *@
@section PostFooter {
	<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    @Html.SpamPreventionScript()
}

Falling Back to CAPTCHA

You don't have to add any code to trigger the fallback to a CAPTCHA when the polite spam prevention fails; it's all handled through ASP.NET MVC model state. If your controller action follows the typical patterns for using model state, the spam prevention will just work.

Q & A

How do I bypass the CAPTCHA during development or test automation? PoliteCaptcha includes a BypassCaptchaGenerator and BypassCaptchaValidator which bypass all CAPTCHA generation and validation. You can selectively register these implementations of the ICaptchaGenerator and ICaptchaValidator interfaces in the current dependency resolver as needed; see Bypassing the Fallback CAPTCHA for more information.

What happens if JavaScript is disabled? The polite spam prevention requires JavaScript; if it is disabled, spam prevention falls back to a rude CAPTCHA so that the user can still use the form.

I don't use jQuery; can I still use PoliteCaptcha? We plan to remove the dependency on jQuery eventually, but for now, it is required.

I use a different CAPTCHA (i.e., not reCAPTCHA); can I make it more polite? PoliteCaptcha uses two interfaces for CAPTCHA: one to get the CAPTCHA's form fields (and associated HTML), and one to validate the user agent's response. Concrete implementations for these interfaces are located through ASP.NET MVC's dependency resolver (and if one doesn't exist, a default reCAPTCHA implementation is used). So, if you can make your CAPTCHA work through these two interfaces, you can use it with PoliteCaptcha. (If you can't make your captcha work with these interfaces, please let us know.)

Can I change the error message that is displayed when PoliteCaptcha falls back to CAPTCHA? Yes, the Html.SpamPreventionFields() HTML helper takes an optional fallback message.

Can I change the surrounding HTML (e.g., the DIV and SPAN elements) that is generated along with the reCAPTCHA? Not at this time. If there is sufficient interest, we can investigate using ASP.NET MVC's editor templates, or look for other means to support templating the HTML that's generated with reCAPTCHA. In the meantime, if this is critically important to you, implement your own ICaptchaGenerator and use ReCaptchaGenerator as a starting-point.

Ask questions not answered here by creating an issue.

politecaptcha's People

Contributors

haacked avatar half-ogre avatar timlovellsmith avatar xavierdecoster avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

politecaptcha's Issues

Generate required keys in web.config

As stated the default keys work only for local requests. can you please let me know how will I generate keys so that this mechanism will work from my web server

Does it work?

This simple thing always passes
using (IWebDriver driver = TestHelper.CreateDriver())
{
//var url = @"http://politecaptcha.apphb.com/Home/WithBypass";
//var url = @"http://politecaptcha.apphb.com/Home/WithFallback";
var url = @"http://politecaptcha.apphb.com/Home/WithoutFallback";
driver.Navigate().GoToUrl(url);
var email = driver.FindElement(By.Id("EmailAddress"));
email.SendKeys("[email protected]");

            var feedback = driver.FindElement(By.Id("Feedback"));
            feedback.SendKeys("Test feedback for [email protected]");

            var submit = driver.FindElement(By.CssSelector("input[type=submit]"));
            submit.Click();

        }

Implemented "Session Hacks" and another improvement suggestion

Hi there,

This is a nice plugin here, I was planning to do one for myself and open-source it later, but it seems there's no need while PoliteCaptcha is here. I've implemented and pushed a quick hack for a problem which many spam prevention libraries have.

The fact: There are tools out there to brute-force forms especially if you want to harm "a specific website". You can assign values into forms, assign random values, use a text-list etc.

The problem: PoliteCaptcha only prevents bots randomly brute-forcing forms on the internet. If an attacker comes to your website and attacks specifically your form, PoliteCaptcha is very easy to crack by just putting a string, and its reverse.

The solution: Save the randomly generated guid into the session, validate it also from the session and (!) don't forget to reset the guid in the session after a successful validation, otherwise the method I describe at the bottom of this post can break it.

Now with this solution, the attacker has to request the first page first, parse the form and generate the form values. This is harder.

The solution is here: atas@2b0293f and if you like that I can tidy up the codes a little bit, make it optional with a parameter and we can merge it.

Step 2 - Better prevention: Output a guid into the form named "RequestKey" and make the form request the NoCaptchaChallengeField by ajax with the RequestKey from the server on 10 seconds after user generates the form. This way, the server can actually prevent giving Guid before 10 seconds, and each attacker IP address can only brute-force within 10 second intervals most frequently. I'm not even saying that this requires a very advanced or specially-coded brute force tool which should also work on a distributed network across servers because attacking every 10 seconds from a single IP address will not do a real harm.

Now I intend to implement the Step 2 also as an option to users, but first I want your opinions. If you are not open to merge them, I may go and implement may own from the scratch.

**A method to crack many prevention libraries_: use the form manually for the first time, get posted values and put it into the brute-force tool. Change email randomly everytime, send other information always unchanged like NoCaptchaChallengeField (which you can generate any random numbers) or session cookie (if needed)._

Status of this project?

There hasn't been an update to this project for over a year. This looks like an ideal solution to me.

Is there a different project that ended up filling this role?

Is there a security issue or some other reason why this isn't more popular?

Clean theme for recaptcha

I am using Politecaptcha and I want to use the clean theme for the recaptcha control. Can you please outline the steps that I need to follow

jQuery Ajax POST

Hi

Is it possible to add validation to a form submitted via jQuery Ajax post (without leaving the current page)?
Are there examples?

Thanks

Configurable API keys that is not from ConfigurationManager.AppSettings

We're moving away from web.config as the source of configuration for nuget.org. We have a config abstraction used internally. However, there is no way for us to bridge out abstraction to PoliteCaptcha 0.3.0.0 to act as source of config for recaptcha API keys - PoliteCaptcha is determined to look at AppSettings. Which is hard to override without private reflection.

Object reference not set to an instance of an object.

Using VS2012, created new MVC4 Internet app, followed PoliteCaptcha instructions:

  • keys in the web.config
  • @Html.SpamPreventionFields(), @Html.SpamPreventionScript() in the view
  • [ValidateSpamPrevention] on the POST controller action.

The GET request view seems to render properly, with appropriate captcha html & script.
Upon post the error occurs, seems to be coming from the [ValidateSpamPrevention] attribute.

Stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
PoliteCaptcha.ReCaptchaValidator.Validate(HttpContextBase httpContext) +159
PoliteCaptcha.ValidateSpamPreventionAttribute.Authorize(HttpContextBase httpContext, ModelStateDictionary modelState, ICaptchaValidator captchaValidator) +272
PoliteCaptcha.ValidateSpamPreventionAttribute.OnAuthorization(AuthorizationContext filterContext) +498
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor) +96 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446 System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382 System.Web.Mvc.Async.WrappedAsyncResult1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

HTTPS support

It doesnt appear that the this package doesnt handle forms served on an https page in chrome 31, ie 11, and firefox 26. If I go to "httpS://politecaptcha.apphb.com/Home/WithFallback" and fill out the form, it correctly displays the error message but does not display the captcha code.

Looking at the console in Chrome, I get the following error: "[blocked] The page at 'https://politecaptcha.apphb.com/Home/WithFallback' was loaded over HTTPS, but ran insecure content from 'http://www.google.com/recaptcha/api/challenge?k=6LdKUM0SAAAAAElj7yWg8oNJKKtkrBsM8jPM-6Pp': this content should also be loaded over HTTPS."

It appears that this is due to the package trying to load insecure content from "http://www.google.com/recaptcha/api/challenge..." instead of secure content from "httpS://www.google.com/recaptcha/api/challenge...".

I am on Windows 7 64bit Professional (although I dont think this matters).

No styling for reCaptcha

Just installed v0.4.0.1 and everything seems to work except the theming for reCaptcha. Here is the code that PoliteCaptcha is generating for me:

<div class="PoliteCaptcha editor-field">
    <span class="field-validation-error" data-valmsg-for="PoliteCaptcha"><span htmlfor="PoliteCaptcha">Your request failed spam prevention. You must complete the CAPTCHA form below to proceed.</span></span>
    <script type="text/javascript">
        var RecaptchaOptions = {
            theme : '',
            tabindex : 0
        };
    </script>

    <script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LehOM0SAAAAAPgsjOy-6_grqy1JiB_W_jJa_aCw"></script>

    <noscript>
        <iframe src="http://www.google.com/recaptcha/api/noscript?k=6LehOM0SAAAAAPgsjOy-6_grqy1JiB_W_jJa_aCw" width="500" height="300" frameborder="0">
        </iframe><br /><textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea><input name="recaptcha_response_field" value="manual_challenge" type="hidden" />
    </noscript>
</div>

I'm pretty sure the issue has to do with this bit of code:

    <script type="text/javascript">
        var RecaptchaOptions = {
            theme : '',
            tabindex : 0
        };
    </script>

If Javascript is turned off, how is the theme supposed to be set using this script block? Am I missing something here?

PoliteCaptcha's NuGet packages will install jQuery 2.0.0.0 for now

Hi,

Due to your PoliteCaptcha NuGet packages set a dependecy on "jQuery", which the latest jQuery version is 2.0.0 for now. If I try to install PoliteCaptcha in my current ASP.NET MVC project. It will be fail to install due to jQuery is unable to upgrade to version 2.0.0. Here is the error message:


PM> install-Package -id PoliteCaptcha
Attempting to resolve dependency 'jQuery'.
Attempting to resolve dependency 'recaptcha'.
Successfully installed 'jQuery 2.0.0'.
Successfully installed 'PoliteCaptcha 0.4.0.1'.
Install failed. Rolling back...
install-Package : Updating 'jQuery 1.8.2' to 'jQuery 2.0.0' failed. Unable to find a version of 'Microsoft.jQuery.Unobtrusive.Ajax' that is compatible with 'jQuery 2.0.0'.
At line:1 char:1

  • install-Package -id PoliteCaptcha
  • - CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    - FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
    
    

My suggestion is that your package may set to more specific jQuery version on your NuGet package.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.