The definitive guide to form-based website authentication

asked16 years ago
last updated2 years ago
viewed667.1k times
Up Vote5.5kDown Vote

Moderator note:

This question is not a good fit for our question and answer format with the topicality rules which currently apply for Stack Overflow. We normally use a "historical lock" for such questions where the content still has value. However, the answers on this question are actively maintained and a historical lock doesn't permit editing of the answers. As such, a "wiki answer" lock has been applied to allow the answers to be edited. You should assume the topicality issues which are normally handled by a historical lock are present (i.e. this question not a good example of an on-topic question for Stack Overflow).

Form-based authentication for websites

We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. "Form based authentication for websites" should be a fine topic for such an experiment.

It should include topics such as:

It should not include things like:

Please help us by:

  1. Suggesting subtopics
  2. Submitting good articles about this subject
  3. Editing the official answer

14 Answers

Up Vote9Down Vote

PART I: How To Log In

We'll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will deal with patterns for sound practical auth, and how to avoid the most common security pitfalls.

Unless the connection is already secure (that is, tunneled through HTTPS using SSL/TLS), your login form values will be sent in cleartext, which allows anyone eavesdropping on the line between browser and web server will be able to read logins as they pass through. This type of wiretapping is done routinely by governments, but in general, we won't address 'owned' wires other than to say this: Just use HTTPS. In essence, the only way to protect against wiretapping/packet sniffing during login is by using HTTPS or another certificate-based encryption scheme (for example, TLS) or a proven & tested challenge-response scheme (for example, the Diffie-Hellman-based SRP). by an eavesdropping attacker. Of course, if you are willing to get a little bit impractical, you could also employ some form of two-factor authentication scheme (e.g. the Google Authenticator app, a physical 'cold war style' codebook, or an RSA key generator dongle). If applied correctly, this could work even with an unsecured connection, but it's hard to imagine that a dev would be willing to implement two-factor auth but not SSL.

Given the perceived (though now avoidable) cost and technical difficulty of setting up an SSL certificate on your website, some developers are tempted to roll their own in-browser hashing or encryption schemes in order to avoid passing cleartext logins over an unsecured wire. While this is a noble thought, it is essentially useless (and can be a security flaw) unless it is combined with one of the above - that is, either securing the line with strong encryption or using a tried-and-tested challenge-response mechanism (if you don't know what that is, just know that it is one of the most difficult to prove, most difficult to design, and most difficult to implement concepts in digital security). While it is true that hashing the password effective against , it is vulnerable to replay attacks, Man-In-The-Middle attacks / hijackings (if an attacker can inject a few bytes into your unsecured HTML page before it reaches your browser, they can simply comment out the hashing in the JavaScript), or brute-force attacks (since you are handing the attacker both username, salt and hashed password).

CAPTCHA is meant to thwart one specific category of attack: automated dictionary/brute force trial-and-error with no human operator. There is no doubt that this is a real threat, however, there are ways of dealing with it seamlessly that don't require a CAPTCHA, specifically properly designed server-side login throttling schemes - we'll discuss those later. Know that CAPTCHA implementations are not created alike; they often aren't human-solvable, most of them are actually ineffective against bots, all of them are ineffective against cheap third-world labor (according to OWASP, the current sweatshop rate is $12 per 500 tests), and some implementations may be technically illegal in some countries (see OWASP Authentication Cheat Sheet). If you must use a CAPTCHA, use Google's reCAPTCHA, since it is OCR-hard by definition (since it uses already OCR-misclassified book scans) and tries very hard to be user-friendly. Personally, I tend to find CAPTCHAS annoying, and use them only as a last resort when a user has failed to log in a number of times and throttling delays are maxed out. This will happen rarely enough to be acceptable, and it strengthens the system as a whole.

This may finally be common knowledge after all the highly-publicized hacks and user data leaks we've seen in recent years, but it has to be said: Do not store passwords in cleartext in your database. User databases are routinely hacked, leaked or gleaned through SQL injection, and if you are storing raw, plaintext passwords, that is instant game over for your login security. So if you can't store the password, how do you check that the login+password combination POSTed from the login form is correct? The answer is hashing using a key derivation function. Whenever a new user is created or a password is changed, you take the password and run it through a KDF, such as Argon2, bcrypt, scrypt or PBKDF2, turning the cleartext password ("correcthorsebatterystaple") into a long, random-looking string, which is a lot safer to store in your database. To verify a login, you run the same hash function on the entered password, this time passing in the salt and compare the resulting hash string to the value stored in your database. Argon2, bcrypt and scrypt store the salt with the hash already. Check out this article on sec.stackexchange for more detailed information. The reason a salt is used is that hashing in itself is not sufficient -- you'll want to add a so-called 'salt' to protect the hash against rainbow tables. A salt effectively prevents two passwords that exactly match from being stored as the same hash value, preventing the whole database being scanned in one run if an attacker is executing a password guessing attack. A cryptographic hash should not be used for password storage because user-selected passwords are not strong enough (i.e. do not usually contain enough entropy) and a password guessing attack could be completed in a relatively short time by an attacker with access to the hashes. This is why KDFs are used - these effectively "stretch the key", which means that every password guess an attacker makes causes multiple repetitions of the hash algorithm, for example 10,000 times, which causes the attacker to guess the password 10,000 times slower.

Once the server has verified the login and password against your user database and found a match, the system needs a way to remember that the browser has been authenticated. This fact should only ever be stored server side in the session data.

If you are unfamiliar with session data, here's how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already. If at all possible, make sure the session cookie has the secure and HTTP Only flags set when sent to the browser. The HttpOnly flag provides some protection against the cookie being read through XSS attack. The secure flag ensures that the cookie is only sent back via HTTPS, and therefore protects against network sniffing attacks. The value of the cookie should not be predictable. Where a cookie referencing a non-existent session is presented, its value should be replaced immediately to prevent session fixation. Session state can also be maintained on the client side. This is achieved by using techniques like JWT (JSON Web Token).

PART II: How To Remain Logged In - The Infamous "Remember Me" Checkbox

Persistent Login Cookies ("remember me" functionality) are a danger zone; on the one hand, they are entirely as safe as conventional logins when users understand how to handle them; and on the other hand, they are an enormous security risk in the hands of careless users, who may use them on public computers and forget to log out, and who may not know what browser cookies are or how to delete them. Personally, I like persistent logins for the websites I visit on a regular basis, but I know how to handle them safely. If you are positive that your users know the same, you can use persistent logins with a clean conscience. If not - well, then you may subscribe to the philosophy that users who are careless with their login credentials brought it upon themselves if they get hacked. It's not like we go to our user's houses and tear off all those facepalm-inducing Post-It notes with passwords they have lined up on the edge of their monitors, either. Of course, some systems can't afford to have accounts hacked; for such systems, there is no way you can justify having persistent logins.

  1. First, take some time to read Paragon Initiative's article on the subject. You'll need to get a bunch of elements right, and the article does a great job of explaining each.
  2. And just to reiterate one of the most common pitfalls, DO NOT STORE THE PERSISTENT LOGIN COOKIE (TOKEN) IN YOUR DATABASE, ONLY A HASH OF IT! The login token is Password Equivalent, so if an attacker got their hands on your database, they could use the tokens to log in to any account, just as if they were cleartext login-password combinations. Therefore, use hashing (according to https://security.stackexchange.com/a/63438/5002 a weak hash will do just fine for this purpose) when storing persistent login tokens.

PART III: Using Secret Questions

. The 'secret questions' feature is a security anti-pattern. Read the paper from link number 4 from the MUST-READ list. You can ask Sarah Palin about that one, after her Yahoo! email account got hacked during a previous presidential campaign because the answer to her security question was... "Wasilla High School"! Even with user-specified questions, it is highly likely that most users will choose either:

  • A 'standard' secret question like mother's maiden name or favorite pet- A simple piece of trivia that anyone could lift from their blog, LinkedIn profile, or similar- Any question that is easier to answer than guessing their password. Which, for any decent password, is every question you can imagine

The true reason why security questions even exist in the wild is that they conveniently save the cost of a few support calls from users who can't access their email to get to a reactivation code. This at the expense of security and Sarah Palin's reputation. Worth it? Probably not.

PART IV: Forgotten Password Functionality

I already mentioned why you should for handling forgotten/lost user passwords; it also goes without saying that you should never e-mail users their actual passwords. There are at least two more all-too-common pitfalls to avoid in this field:

  1. Don't reset a forgotten password to an autogenerated strong password - such passwords are notoriously hard to remember, which means the user must either change it or write it down - say, on a bright yellow Post-It on the edge of their monitor. Instead of setting a new password, just let users pick a new one right away - which is what they want to do anyway. (An exception to this might be if the users are universally using a password manager to store/manage passwords that would normally be impossible to remember without writing it down).
  2. Always hash the lost password code/token in the database. AGAIN, this code is another example of a Password Equivalent, so it MUST be hashed in case an attacker got their hands on your database. When a lost password code is requested, send the plaintext code to the user's email address, then hash it, save the hash in your database -- and throw away the original. Just like a password or a persistent login token.

A final note: always make sure your interface for entering the 'lost password code' is at least as secure as your login form itself, or an attacker will simply use this to gain access instead. Making sure you generate very long 'lost password codes' (for example, 16 case-sensitive alphanumeric characters) is a good start, but consider adding the same throttling scheme that you do for the login form itself.

PART V: Checking Password Strength

First, you'll want to read this small article for a reality check: The 500 most common passwords Okay, so maybe the list isn't the list of most common passwords on system , but it's a good indication of how poorly people will choose their passwords when there is no enforced policy in place. Plus, the list looks frighteningly close to home when you compare it to publicly available analyses of recently stolen passwords. So: With no minimum password strength requirements, 2% of users use one of the top 20 most common passwords. Meaning: if an attacker gets just 20 attempts, 1 in 50 accounts on your website will be crackable. Thwarting this requires calculating the entropy of a password and then applying a threshold. The National Institute of Standards and Technology (NIST) Special Publication 800-63 has a set of very good suggestions. That, when combined with a dictionary and keyboard layout analysis (for example, 'qwertyuiop' is a bad password), can reject 99% of all poorly selected passwords at a level of 18 bits of entropy. Simply calculating password strength and showing a visual strength meter to a user is good, but insufficient. Unless it is enforced, a lot of users will most likely ignore it. And for a refreshing take on user-friendliness of high-entropy passwords, Randall Munroe's Password Strength xkcd is highly recommended. Utilize Troy Hunt's Have I Been Pwned API to check users passwords against passwords compromised in public data breaches.

PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts

First, have a look at the numbers: Password Recovery Speeds - How long will your password stand up If you don't have the time to look through the tables in that link, here's the list of them:

  1. It takes virtually no time to crack a weak password, even if you're cracking it with an abacus
  2. It takes virtually no time to crack an alphanumeric 9-character password if it is case insensitive
  3. It takes virtually no time to crack an intricate, symbols-and-letters-and-numbers, upper-and-lowercase password if it is less than 8 characters long (a desktop PC can search the entire keyspace up to 7 characters in a matter of days or even hours)
  4. It would, however, take an inordinate amount of time to crack even a 6-character password, if you were limited to one attempt per second!

So what can we learn from these numbers? Well, lots, but we can focus on the most important part: the fact that preventing large numbers of rapid-fire successive login attempts (ie. the attack) really isn't that difficult. But preventing it isn't as easy as it seems. Generally speaking, you have three choices that are all effective against brute-force attacks :

  • Present a after N failed attempts (annoying as hell and often ineffective -- but I'm repeating myself here)- and requiring email verification after N failed attempts (this is a DoS attack waiting to happen)- And finally, : that is, setting a time delay between attempts after N failed attempts (yes, DoS attacks are still possible, but at least they are far less likely and a lot more complicated to pull off). A short time delay that increases with the number of failed attempts, like:

DoS attacking this scheme would be very impractical, since the resulting lockout time is slightly larger than the sum of the previous lockout times.

To clarify: The delay is a delay before returning the response to the browser. It is more like a timeout or refractory period during which login attempts to a specific account or from a specific IP address will not be accepted or evaluated at all. That is, correct credentials will not return in a successful login, and incorrect credentials will not trigger a delay increase. A medium length time delay that goes into effect after N failed attempts, like:

  • - DoS attacking this scheme would be quite impractical, but certainly doable. Also, it might be relevant to note that such a long delay can be very annoying for a legitimate user. Forgetful users will dislike you. Combining the two approaches - either a fixed, short time delay that goes into effect after N failed attempts, like:
  • - Or, an increasing delay with a fixed upper bound, like:

This final scheme was taken from the OWASP best-practices suggestions (link 1 from the MUST-READ list) and should be considered best practice, even if it is admittedly on the restrictive side.

DoS attacking this final login throttling scheme would be impractical. And as a final touch, always allow persistent (cookie) logins (and/or a CAPTCHA-verified login form) to pass through, so legitimate users won't even be delayed . That way, the very impractical DoS attack becomes an impractical attack. Additionally, it makes sense to do more aggressive throttling on admin accounts, since those are the most attractive entry points

PART VII: Distributed Brute Force Attacks

Just as an aside, more advanced attackers will try to circumvent login throttling by 'spreading their activities':

  • Distributing the attempts on a botnet to prevent IP address flagging- Rather than picking one user and trying the 50.000 most common passwords (which they can't, because of our throttling), they will pick THE most common password and try it against 50.000 users instead. That way, not only do they get around maximum-attempts measures like CAPTCHAs and login throttling, their chance of success increases as well, since the number 1 most common password is far more likely than number 49.995- Spacing the login requests for each user account, say, 30 seconds apart, to sneak under the radar Here, the best practice would be , and using a running average of your site's bad-login frequency as the basis for an upper limit that you then impose on all users. Too abstract? Let me rephrase: Say your site has had an average of 120 bad logins per day over the past 3 months. Using that (running average), your system might set the global limit to 3 times that -- ie. 360 failed attempts over a 24 hour period. Then, if the total number of failed attempts across all accounts exceeds that number within one day (or even better, monitor the rate of acceleration and trigger on a calculated threshold), it activates system-wide login throttling - meaning short delays for ALL users (still, with the exception of cookie logins and/or backup CAPTCHA logins). I also posted a question with more details and a really good discussion of how to avoid tricky pitfals in fending off distributed brute force attacks

PART VIII: Two-Factor Authentication and Authentication Providers

Credentials can be compromised, whether by exploits, passwords being written down and lost, laptops with keys being stolen, or users entering logins into phishing sites. Logins can be further protected with two-factor authentication, which uses out-of-band factors such as single-use codes received from a phone call, SMS message, app, or dongle. Several providers offer two-factor authentication services. Authentication can be completely delegated to a single-sign-on service, where another provider handles collecting credentials. This pushes the problem to a trusted third party. Google and Twitter both provide standards-based SSO services, while Facebook provides a similar proprietary solution.

MUST-READ LINKS About Web Authentication

  1. OWASP Guide To Authentication / OWASP Authentication Cheat Sheet
  2. Dos and Don’ts of Client Authentication on the Web (very readable MIT research paper)
  3. Wikipedia: HTTP cookie
  4. Personal knowledge questions for fallback authentication: Security questions in the era of Facebook (very readable Berkeley research paper)
Up Vote8Down Vote
Grade: B

The definitive guide to form-based website authentication

Introduction

Form-based authentication is a common method of authenticating users to a website. It is relatively simple to implement and can be used with a variety of programming languages and web frameworks. However, it is important to understand the security implications of form-based authentication and to take steps to mitigate the risks.

How form-based authentication works

Form-based authentication works by sending the user's credentials (typically a username and password) to the server in an HTTP POST request. The server then validates the credentials and, if they are valid, creates a session cookie that is sent back to the user. The session cookie is used to identify the user for the duration of their session.

Security implications

Form-based authentication is vulnerable to a number of security attacks, including:

  • Cross-site request forgery (CSRF): A CSRF attack occurs when a malicious website tricks a user into submitting a request to a legitimate website. This can be done by embedding a malicious script on the malicious website that automatically submits a request to the legitimate website when the user visits the malicious website.
  • Man-in-the-middle attacks: A man-in-the-middle attack occurs when an attacker intercepts the communication between a user and a website. This can be done by using a proxy server or by sniffing the network traffic. Once the attacker has intercepted the communication, they can modify the user's credentials or redirect the user to a malicious website.
  • Phishing attacks: A phishing attack occurs when an attacker sends an email or text message that appears to be from a legitimate source. The email or text message contains a link to a malicious website that looks like the legitimate website. When the user clicks on the link, they are prompted to enter their credentials. The attacker can then use the credentials to access the user's account.

Mitigating the risks

There are a number of steps that can be taken to mitigate the risks of form-based authentication, including:

  • Use SSL/TLS to encrypt the communication between the user and the website. This will help to protect the user's credentials from being intercepted by an attacker.
  • Use a CSRF token to protect against CSRF attacks. A CSRF token is a unique value that is generated by the server and included in the form that the user submits. When the user submits the form, the server checks the CSRF token to make sure that it is valid. If the CSRF token is not valid, the server rejects the request.
  • Use a strong password policy. A strong password policy requires users to create passwords that are at least 8 characters long and contain a mix of upper and lower case letters, numbers, and symbols.
  • Educate users about phishing attacks. Users should be aware of the dangers of phishing attacks and should be careful about clicking on links in emails or text messages.

Conclusion

Form-based authentication is a common and relatively simple method of authenticating users to a website. However, it is important to understand the security implications of form-based authentication and to take steps to mitigate the risks. By following the steps outlined in this guide, you can help to protect your website and your users from attack.

Up Vote8Down Vote
Grade: B

Sure, I'd be happy to help! Here's a guide to form-based authentication for websites, including some of the subtopics you mentioned.

Subtopics:

  1. Understanding Form-Based Authentication
  2. Implementing Basic Form-Based Authentication
  3. Preventing Common Security Threats
    • Cross-Site Request Forgery (CSRF)
    • Session Hijacking
    • Man-in-the-Middle Attacks
  4. Using Best Practices for Password Security
  5. Implementing Two-Factor Authentication
  6. Integrating with Other Authentication Systems (e.g. OpenID, OAuth)
  7. Handling User Logout and Session Termination

1. Understanding Form-Based Authentication

Form-based authentication is a method of authentication where users submit their credentials (usually a username and password) through an HTML form. The server then verifies these credentials and grants or denies access to the requested resource.

2. Implementing Basic Form-Based Authentication

Here's a simple example of how to implement basic form-based authentication in PHP:

index.php:

<form action="check_credentials.php" method="post">
  <label for="username">Username:</label><br>
  <input type="text" id="username" name="username"><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password"><br>
  <input type="submit" value="Submit">
</form>

check_credentials.php:

<?php
session_start();

// Replace this with actual database lookup or LDAP query
$users = [
  ['username' => 'user', 'password' => 'pass'],
];

if (isset($_POST['username']) && isset($_POST['password'])) {
  $foundUser = false;
  foreach ($users as $user) {
    if ($_POST['username'] == $user['username'] && $_POST['password'] == $user['password']) {
      $foundUser = true;
      break;
    }
  }

  if ($foundUser) {
    // Authentication successful, start a session
    $_SESSION['authenticated'] = true;
    header('Location: protected_resource.php');
    exit;
  } else {
    // Authentication failed, show an error message
    echo 'Error: Invalid credentials';
  }
} else {
  // Missing required fields, show an error message
  echo 'Error: Both username and password are required';
}
?>

protected_resource.php:

<?php
session_start();
if (!isset($_SESSION['authenticated']) || !$_SESSION['authenticated']) {
  // User is not authenticated, redirect to login page
  header('Location: index.php');
  exit;
}
// Show protected resource
echo 'Welcome to the protected resource!';
?>

3. Preventing Common Security Threats

To prevent common security threats when implementing form-based authentication, you should:

  • Use HTTPS to protect against Man-in-the-Middle attacks.
  • Use nonces (unique, one-time use tokens) to prevent Cross-Site Request Forgery (CSRF).
  • Protect against session hijacking by using secure, HTTP-only cookies and regenerating session IDs periodically.
  • Validate and sanitize all user inputs to protect against SQL injection and other input-based attacks.

4. Using Best Practices for Password Security

To ensure password security:

  • Enforce strong password policies (minimum length, required characters).
  • Use a slow, secure hashing algorithm like bcrypt or scrypt.
  • Consider implementing rate limiting to prevent brute force attacks.

5. Implementing Two-Factor Authentication

Two-factor authentication adds an additional layer of security by requiring users to provide two forms of identification: something they know (e.g. a password) and something they have (e.g. a phone or hardware token). This can be implemented using time-based one-time passwords (TOTP), HMAC-based one-time passwords (HOTP), or other two-factor authentication methods.

6. Integrating with Other Authentication Systems

Form-based authentication can be integrated with other authentication systems like OpenID, OAuth, or SAML to allow users to log in using their accounts from external providers. This can simplify the login process and improve user experience.

7. Handling User Logout and Session Termination

To ensure secure logouts and session termination:

  • Provide a clear logout button that fully terminates the session (e.g. by calling session_destroy() in PHP).
  • Set appropriate session timeouts and expiration times.
  • Consider using single sign-on (SSO) solutions to manage user sessions across multiple applications or services.
Up Vote7Down Vote
Grade: B

I'd be happy to help you with the "definitive guide" for form-based authentication in websites! Here are some suggested subtopics and resources that could be included:

Subtopics:

  1. Overview of Form-Based Authentication: Explain what form-based authentication is, its advantages and limitations compared to other methods like token-based or OAuth. (Wikipedia - Form Based Authentication)
  2. Security Considerations: Discuss various security concerns with form-based authentication, such as CSRF protection (using nonces, tokens or SAMEORIGIN policy), HTTPS encryption, and input validation. (Wikipedia - Cross-site request forgery)
  3. Design Patterns: Discuss various design patterns commonly used in form-based authentication systems like Remember Me cookies, Single Sign-On (SSO), Multi-Factor Authentication (MFA), etc.
  4. Implementations: Provide examples and code snippets of implementing form-based authentication in popular web frameworks such as Ruby on Rails, Django, ASP.NET, ExpressJS, Laravel, Flask, or AngularJS.
  5. Best Practices: Share guidelines for creating secure and robust form-based authentication systems, including password policies, password storage (hash salting and bcrypt), and CSRF token management.
  6. Integrations: Discuss how to integrate various external services into your form-based authentication system such as OpenID Connect, OAuth2, LDAP or Active Directory.
  7. Tools and Libraries: List popular tools and libraries for handling form-based authentication securely and easily like Spring Security, Struts2 SSO Filter, Passport.js (Node.js), or Shibboleth Identity Provider.

Articles: Here are some great resources that cover different aspects of this topic:

  1. Form Based Authentication vs Token Based Authentication
  2. Designing Forms for Form Based Authentication
  3. Creating a Secure Form Based Authentication System in Node.js with Passport.js
  4. Securing a Form Based Authentication Application with OAuth

Editing the official answer: Feel free to suggest additions or corrections to improve the existing official answer and make it as comprehensive as possible for the topic of "Form-Based Authentication for Websites". I look forward to working together with you on this!

Up Vote6Down Vote
Grade: B

Here's how you could break this down in a subtopic manner:

  1. Understanding Basic Form-Based Authentication

    • The concept of form-based authentication
    • How it works with HTML forms and HTTP requests/responses
  2. Protecting Your Websites From Hackers

    • Overview: Using encryption, salting, and hashing passwords (especially important in the age of social engineering)
    • Best Practices: Password rules (length, uppercase letters, special characters), strong random passphrase generation
  3. Session Management

    • How cookies can help us remember who a user is when they close their browser
    • When to use sessions and how to maintain security levels
  4. Handling Login/Registration Forms

    • User inputs must be validated and sanitized
    • Overview on Cross-Site Request Forgery (CSRF) prevention
  5. Threat Models for Authentication Systems

    • Passive: User provides password, System hashes the input and checks against a stored hash
    • Active: User provides username or password, system responds to attacker with something other than an error message
  6. Alternative Security Measures: Nonces and CAPTCHA

    • How they work
    • When might you use them
  7. Implementing OpenID in Your Authentication System

    • Overview of how the protocol works
    • Important points to remember (like what happens if a user clicks through the warning twice)
  8. Single Sign-On Solution for Form-Based Websites: OAuth and OpenID Connect

    • The difference between these two protocols
    • How they can be useful in securing your website/application
  9. Session Management for Mobile Applications

    • The unique challenges of maintaining sessions on mobile platforms
    • Tips for best practice, such as the use of tokens instead of cookies or a service worker to manage sessions
  10. Mitigation against Brute Force and Credential Stuffing Attacks

    • Techniques like CAPTCHAs can help
    • What other factors could be included (such as geolocation) to further harden your defenses

Remember, the goal should not be just to cover all possible security aspects of form-based websites. The key is understanding how and where attacks are coming from and implementing proper defensive strategies against them. Each bullet point would ideally lead to a more in-depth explanation with examples and links for further reading.

As an extension to this, you can create separate topics for topics like securing form inputs (XSS, SQL injection), etc., that could also be helpful.

Up Vote5Down Vote
Grade: C

The definitive guide to form-based website authentication

Introduction

Form-based authentication is a common method of user authentication in websites. It involves sending the user's login credentials, such as username and password, to the server via a form submission. In this article, we will discuss the basics of form-based authentication, its benefits, and its drawbacks. We will also cover some best practices for implementing form-based authentication in your website.

Benefits of Form-Based Authentication

Form-based authentication has several advantages over other methods of user authentication. Some of these benefits include:

1. Easy to Implement

Form-based authentication is one of the simplest methods of user authentication. It requires little to no additional software or hardware installation, and it can be easily implemented by anyone who knows HTML, CSS, and JavaScript.

2. Secure

Form-based authentication is more secure than other methods because it prevents unauthorized access to your website. When a user submits their login credentials via a form, they are ensured that only the website owner has access to those credentials. This makes form-based authentication an ideal choice for websites that handle sensitive information.

3. Flexible

Form-based authentication can be used on a variety of different websites and applications. It is not limited to any specific type of website or application, making it a versatile choice for many developers.

4. Customizable

Form-based authentication allows developers to customize the login process as per their requirement. For example, they can add captcha checks to prevent bots from accessing the site or implement two-factor authentication to provide an extra layer of security.

5. User-Friendly

Forms are a common feature on websites that users are familiar with. Therefore, form-based authentication is generally easier for users to understand and use compared to other methods like OAuth.

Drawbacks of Form-Based Authentication

While form-based authentication has many benefits, it also has some drawbacks that developers should be aware of. Some of these disadvantages include:

1. Insecure by Default

When a user submits their login credentials via a form, they are not protected from cross-site request forgeries (CSRF) attacks. To prevent this, developers need to use HTTPS and other security measures to secure the communication between their website and users' browsers.

2. Sensitive Information in Plain Text

When a user submits their login credentials via a form, the sensitive information such as usernames and passwords are transmitted over an insecure network (HTTP). This makes them vulnerable to interception and eavesdropping attacks.

3. Easily Guessable Passwords

When using form-based authentication, users may choose weak or easily guessable passwords that can be easily brute-forced by attackers. As a result, developers should always advise their users to use strong and unique passwords for better security.

4. Inconvenient User Experience

Forms can be a source of frustration for users as they require the user to enter their credentials on every visit. Therefore, developers should consider using token-based authentication instead for better performance.

Best Practices for Form-Based Authentication

While form-based authentication has some drawbacks, it is still a widely used method of user authentication that can be customized and secured with the right practices. Here are some best practices to help developers create a secure and user-friendly form-based authentication system:

1. Use HTTPS

To ensure that the sensitive information transmitted between the client and server is encrypted, use HTTPS whenever possible. Make sure that the communication between your website and users' browsers is always secure by using a valid SSL certificate.

2. Use Strong Password Hashing

When storing user credentials in the database, use a strong password hashing algorithm like bcrypt or argon2. This ensures that even if an attacker obtains your user's credentials, they cannot be used to compromise the website or the user account without additional measures such as brute-forcing or social engineering.

3. Implement Two-Factor Authentication

Two-factor authentication provides an extra layer of security by requiring the user to provide a second form of identification, usually in addition to their password. This can include TOTP or HOTP, which are secure ways of verifying the user's identity after they have successfully logged in once.

4. Limit Login Attempts

After a certain number of unsuccessful login attempts, developers can implement measures to limit or temporarily block a user's access to the website to prevent brute-forcing attacks. This can include rate limiting, blocking IP addresses, or using captcha checks to prevent automatic form submission by bots.

Conclusion

Form-based authentication is a widely used method of user authentication that can provide excellent security features. However, it also has some drawbacks, such as insecure by default and vulnerable to password guessing attacks. By following best practices like using HTTPS, strong password hashing, implementing two-factor authentication, and limiting login attempts, developers can create a secure and user-friendly form-based authentication system.

Up Vote2Down Vote
Grade: D

Here is a guide to form-based website authentication:

Overview

Form-based authentication is a common way for websites to authenticate users. The general process is:

  1. User submits login credentials (e.g. username and password) via an HTML form
  2. Server validates the credentials against the database
  3. If credentials are valid, a session is started and a cookie is set to identify the user
  4. On subsequent requests, the server checks for the session cookie to authenticate the user

Some key considerations for secure form-based auth:

  • Always use HTTPS to encrypt the login form submission
  • Validate and sanitize all user inputs
  • Use secure session management - generate random session IDs, set cookies to httpOnly, etc.
  • Protect against CSRF attacks by including an unpredictable token with the form
  • Hash and salt passwords before storing them
  • Implement proper logout that destroys the session

Login Form

A basic login form contains fields for username and password:

<form method="post" action="/login">
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="submit" value="Login">
</form>

The form should submit a POST request over HTTPS. Additional fields like a CSRF token can be included.

Server-Side Authentication

The server receives the POSTed form data, often available in a request.body object. Basic steps:

  1. Retrieve the submitted username and password values
  2. Validate the inputs (check for empty/invalid values)
  3. Look up the user in the database by username
  4. Compare the submitted password to the hashed password from the DB
  5. If there is a match, start a new session and set a session cookie
  6. Redirect the user to a post-login page

Example code (Express.js):

app.post('/login', (req, res) => {
  let username = req.body.username;
  let password = req.body.password;

  // validate inputs
  if (!username || !password) {
    return res.status(400).send('Username and password required');
  }
  
  // look up user in DB
  User.findOne({username}, (err, user) => {
    if (!user || err) {
      return res.status(401).send('Invalid username');  
    }

    // compare password to hashed password in DB
    bcrypt.compare(password, user.hashedPassword, (err, match) => {
      if (match) {
        req.session.userId = user.id; // start session
        return res.redirect('/dashboard');
      } else {
        return res.status(401).send('Invalid password');
      }
    });
  })
});

Session Management

Once authenticated, the server starts a session to persist the user's authenticated state. This is typically done by generating a unique, random session ID stored on the server and sent to the client as a cookie.

The session ID should be:

  • Long and randomly generated to prevent guessing
  • Stored securely on the server, e.g. in memory, Redis, or Memcached
  • Set as an httpOnly cookie so it's not accessible to JavaScript

On subsequent requests, the server checks for the session ID in the cookie and looks it up to authenticate the user. If found, the request proceeds as authenticated.

Example middleware (Express.js):

app.use((req, res, next) => {
  if (req.session.userId) {
    User.findById(req.session.userId, (err, user) => {
      if (!err) {
        req.user = user;
      }
      next();
    });
  } else {
    next();
  }
});

Logout

Logging out is done by destroying the session on the server and clearing the session cookie.

Example logout route:

app.get('/logout', (req, res) => {
  req.session.destroy((err) => {
    res.clearCookie('sessionId');
    res.redirect('/login');
  }); 
});

Additional Security Considerations

  • Password complexity requirements
  • Account lockouts after too many failed attempts
  • Password reset mechanism
  • Two-factor authentication
  • Require re-authentication before sensitive actions
  • Use JWT instead of sessions for stateless auth
  • Implement OAuth 2.0 for SSO

This covers some of the key aspects of form-based authentication. Let me know if you would like me to elaborate on any part of it!

Up Vote1Down Vote
Grade: F

Thank you for the detailed question and context. As an AI assistant, I'm happy to provide a comprehensive guide on form-based website authentication. This is an important topic for web developers, so I'll do my best to cover the key aspects in a step-by-step manner.

The Definitive Guide to Form-Based Website Authentication

Form-based authentication is a common method for user authentication on websites. It involves the user providing their credentials (typically a username and password) through an HTML form, which are then submitted to the server for verification.

Key Topics to Cover

  1. Authentication Fundamentals

    • Explanation of authentication and its importance in web applications
    • Different authentication methods (form-based, token-based, federated, etc.)
    • The role of the client, server, and communication protocols (HTTP, HTTPS)
  2. Form-Based Authentication

    • Structure of a login form (username, password, submit button)
    • Client-side form validation (HTML5 validation, JavaScript)
    • Server-side form processing and user verification
    • Secure password storage (hashing, salting, bcrypt, etc.)
    • Secure communication (HTTPS, SSL/TLS)
  3. Security Considerations

    • Cross-Site Request Forgery (CSRF) protection
    • Cross-Site Scripting (XSS) prevention
    • Password strength and complexity requirements
    • Session management (session IDs, session timeouts, session invalidation)
    • Two-factor authentication (2FA) and multi-factor authentication (MFA)
  4. Advanced Topics

    • Single Sign-On (SSO) and federated authentication (OpenID, OAuth)
    • Password reset and password change functionality
    • Secure password recovery (email, SMS, security questions)
    • Brute-force attack mitigation (rate limiting, captchas)
    • Logging and monitoring for security incidents
  5. Implementation Examples

    • Code samples in various programming languages (e.g., PHP, Python, Java, Node.js)
    • Libraries and frameworks for form-based authentication (e.g., Flask-Login, Django auth, Spring Security)
    • Integrating form-based authentication with a database or user store
  6. Best Practices and Recommendations

    • Secure coding guidelines and standards (OWASP, NIST)
    • Encryption and hashing algorithms (SHA-256, bcrypt, Argon2)
    • User education and password management strategies
    • Monitoring and incident response planning

The goal of this guide is to provide a comprehensive overview of form-based website authentication, covering the essential concepts, security best practices, and implementation examples. By addressing these key topics, we can help developers build more secure and robust web applications.

Please feel free to suggest any additional subtopics or provide relevant articles that could be included in this guide. I'm happy to collaborate and refine the content to make it as useful as possible for the developer community.

Up Vote1Down Vote
Grade: F

Sure, I'd be happy to help create a comprehensive guide on form-based website authentication. Here's a suggested outline with subtopics and resources:

I. Introduction to Form-Based Authentication

  • What is form-based authentication?
  • Advantages and disadvantages compared to other authentication methods

II. Authentication Flow - User login process - Server-side authentication - Establishing user sessions

III. Security Considerations - Password storage and hashing (bcrypt, Argon2, etc.) - Brute-force protection mechanisms - HTTPS and transport security

IV. CSRF Protection - What is CSRF? - Anti-CSRF tokens and nonces - SameSite cookies - CSRF protection libraries/frameworks

V. Other Authentication Factors - Multi-factor authentication (2FA, OTP, etc.) - Social login integration (OAuth, OpenID Connect) - Remember me functionality

VI. Authentication Libraries/Frameworks - Language-specific authentication libraries - Full-stack frameworks with authentication support

VII. Best Practices - Password policies and strength - Secure session management
- Logging and monitoring

I'll start fleshing out the main answer with an introduction and we can collaborate to add more details, code examples, and external resources for each section. Please feel free to suggest any other subtopics or reorganize the outline as needed.

Up Vote1Down Vote
Grade: F

We don’t have anything on the subject yet but thank you for suggesting it!

Up Vote0Down Vote
Grade: F

Subtopics

  • Understanding the principles of form-based authentication
  • Best practices for implementing form-based authentication
  • Choosing the right authentication method for your website
  • Secure implementation of CSRF protection
  • Secure implementation of URL manipulation
  • Secure implementation of OpenID Connect
  • Building a form handling library
  • Integrating a form-based authentication provider with an OAuth service

Articles

  • Form-based authentication - Wikipedia (en)
  • How to Implement Form Based Authentication - W3Schools
  • Implementing Form-Based Authentication in PHP - Codecademy
  • How to Implement Form Based Authentication in JavaScript | FreeCodeCamp

Existing Answers

Form-based Authentication: A Comprehensive Guide - Stack Overflow

This is a very well-maintained answer that covers all the important aspects of form-based authentication, including:

  • Nonces and cross-site request forgeries (CSRF) protection
  • OpenID Connect
  • URL manipulation
  • Security considerations

Form-Based Authentication - W3Schools

This is another comprehensive article on form-based authentication, covering both the principles and implementation aspects.

Implementing Form Based Authentication in PHP - Codecademy

This article provides a clear step-by-step guide on how to implement form-based authentication in PHP.

How to Implement Form Based Authentication in JavaScript | FreeCodeCamp

This article explains how to implement form-based authentication in JavaScript, focusing on the client-side implementation.

Security Considerations for Form-Based Authentication - OWASP

This article provides a detailed security assessment of form-based authentication, highlighting potential vulnerabilities such as SQL injection and cross-site scripting.

Up Vote0Down Vote
Grade: F

Summary of the text:

This text describes the issue of form-based website authentication and proposes a solution. It highlights the potential value of such content on Stack Overflow and suggests subtopics and resources that could be included in the guide.

Key points:

  • Topicality: The text acknowledges that this question may not be a perfect fit for Stack Overflow's topicality rules.
  • Historical lock: A "wiki answer" lock has been applied to allow for edits to the answers.
  • Subtopics: The text suggests subtopics that could be included in the guide, such as nonces, CSRF, OpenID, URL, and form-based authentication.
  • Additional content: The text does not specify additional content that should be included in the guide.
  • Call to action: The text encourages users to suggest subtopics, submit articles, and edit the official answer.

Overall:

This text provides a good overview of the issue and proposes a potential solution. It also highlights the need for further contributions from the community.

Up Vote0Down Vote
Grade: F

PART I: How To Log In

We'll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will deal with patterns for sound practical auth, and how to avoid the most common security pitfalls.

Unless the connection is already secure (that is, tunneled through HTTPS using SSL/TLS), your login form values will be sent in cleartext, which allows anyone eavesdropping on the line between browser and web server will be able to read logins as they pass through. This type of wiretapping is done routinely by governments, but in general, we won't address 'owned' wires other than to say this: Just use HTTPS. In essence, the only way to protect against wiretapping/packet sniffing during login is by using HTTPS or another certificate-based encryption scheme (for example, TLS) or a proven & tested challenge-response scheme (for example, the Diffie-Hellman-based SRP). by an eavesdropping attacker. Of course, if you are willing to get a little bit impractical, you could also employ some form of two-factor authentication scheme (e.g. the Google Authenticator app, a physical 'cold war style' codebook, or an RSA key generator dongle). If applied correctly, this could work even with an unsecured connection, but it's hard to imagine that a dev would be willing to implement two-factor auth but not SSL.

Given the perceived (though now avoidable) cost and technical difficulty of setting up an SSL certificate on your website, some developers are tempted to roll their own in-browser hashing or encryption schemes in order to avoid passing cleartext logins over an unsecured wire. While this is a noble thought, it is essentially useless (and can be a security flaw) unless it is combined with one of the above - that is, either securing the line with strong encryption or using a tried-and-tested challenge-response mechanism (if you don't know what that is, just know that it is one of the most difficult to prove, most difficult to design, and most difficult to implement concepts in digital security). While it is true that hashing the password effective against , it is vulnerable to replay attacks, Man-In-The-Middle attacks / hijackings (if an attacker can inject a few bytes into your unsecured HTML page before it reaches your browser, they can simply comment out the hashing in the JavaScript), or brute-force attacks (since you are handing the attacker both username, salt and hashed password).

CAPTCHA is meant to thwart one specific category of attack: automated dictionary/brute force trial-and-error with no human operator. There is no doubt that this is a real threat, however, there are ways of dealing with it seamlessly that don't require a CAPTCHA, specifically properly designed server-side login throttling schemes - we'll discuss those later. Know that CAPTCHA implementations are not created alike; they often aren't human-solvable, most of them are actually ineffective against bots, all of them are ineffective against cheap third-world labor (according to OWASP, the current sweatshop rate is $12 per 500 tests), and some implementations may be technically illegal in some countries (see OWASP Authentication Cheat Sheet). If you must use a CAPTCHA, use Google's reCAPTCHA, since it is OCR-hard by definition (since it uses already OCR-misclassified book scans) and tries very hard to be user-friendly. Personally, I tend to find CAPTCHAS annoying, and use them only as a last resort when a user has failed to log in a number of times and throttling delays are maxed out. This will happen rarely enough to be acceptable, and it strengthens the system as a whole.

This may finally be common knowledge after all the highly-publicized hacks and user data leaks we've seen in recent years, but it has to be said: Do not store passwords in cleartext in your database. User databases are routinely hacked, leaked or gleaned through SQL injection, and if you are storing raw, plaintext passwords, that is instant game over for your login security. So if you can't store the password, how do you check that the login+password combination POSTed from the login form is correct? The answer is hashing using a key derivation function. Whenever a new user is created or a password is changed, you take the password and run it through a KDF, such as Argon2, bcrypt, scrypt or PBKDF2, turning the cleartext password ("correcthorsebatterystaple") into a long, random-looking string, which is a lot safer to store in your database. To verify a login, you run the same hash function on the entered password, this time passing in the salt and compare the resulting hash string to the value stored in your database. Argon2, bcrypt and scrypt store the salt with the hash already. Check out this article on sec.stackexchange for more detailed information. The reason a salt is used is that hashing in itself is not sufficient -- you'll want to add a so-called 'salt' to protect the hash against rainbow tables. A salt effectively prevents two passwords that exactly match from being stored as the same hash value, preventing the whole database being scanned in one run if an attacker is executing a password guessing attack. A cryptographic hash should not be used for password storage because user-selected passwords are not strong enough (i.e. do not usually contain enough entropy) and a password guessing attack could be completed in a relatively short time by an attacker with access to the hashes. This is why KDFs are used - these effectively "stretch the key", which means that every password guess an attacker makes causes multiple repetitions of the hash algorithm, for example 10,000 times, which causes the attacker to guess the password 10,000 times slower.

Once the server has verified the login and password against your user database and found a match, the system needs a way to remember that the browser has been authenticated. This fact should only ever be stored server side in the session data.

If you are unfamiliar with session data, here's how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already. If at all possible, make sure the session cookie has the secure and HTTP Only flags set when sent to the browser. The HttpOnly flag provides some protection against the cookie being read through XSS attack. The secure flag ensures that the cookie is only sent back via HTTPS, and therefore protects against network sniffing attacks. The value of the cookie should not be predictable. Where a cookie referencing a non-existent session is presented, its value should be replaced immediately to prevent session fixation. Session state can also be maintained on the client side. This is achieved by using techniques like JWT (JSON Web Token).

PART II: How To Remain Logged In - The Infamous "Remember Me" Checkbox

Persistent Login Cookies ("remember me" functionality) are a danger zone; on the one hand, they are entirely as safe as conventional logins when users understand how to handle them; and on the other hand, they are an enormous security risk in the hands of careless users, who may use them on public computers and forget to log out, and who may not know what browser cookies are or how to delete them. Personally, I like persistent logins for the websites I visit on a regular basis, but I know how to handle them safely. If you are positive that your users know the same, you can use persistent logins with a clean conscience. If not - well, then you may subscribe to the philosophy that users who are careless with their login credentials brought it upon themselves if they get hacked. It's not like we go to our user's houses and tear off all those facepalm-inducing Post-It notes with passwords they have lined up on the edge of their monitors, either. Of course, some systems can't afford to have accounts hacked; for such systems, there is no way you can justify having persistent logins.

  1. First, take some time to read Paragon Initiative's article on the subject. You'll need to get a bunch of elements right, and the article does a great job of explaining each.
  2. And just to reiterate one of the most common pitfalls, DO NOT STORE THE PERSISTENT LOGIN COOKIE (TOKEN) IN YOUR DATABASE, ONLY A HASH OF IT! The login token is Password Equivalent, so if an attacker got their hands on your database, they could use the tokens to log in to any account, just as if they were cleartext login-password combinations. Therefore, use hashing (according to https://security.stackexchange.com/a/63438/5002 a weak hash will do just fine for this purpose) when storing persistent login tokens.

PART III: Using Secret Questions

. The 'secret questions' feature is a security anti-pattern. Read the paper from link number 4 from the MUST-READ list. You can ask Sarah Palin about that one, after her Yahoo! email account got hacked during a previous presidential campaign because the answer to her security question was... "Wasilla High School"! Even with user-specified questions, it is highly likely that most users will choose either:

  • A 'standard' secret question like mother's maiden name or favorite pet- A simple piece of trivia that anyone could lift from their blog, LinkedIn profile, or similar- Any question that is easier to answer than guessing their password. Which, for any decent password, is every question you can imagine

The true reason why security questions even exist in the wild is that they conveniently save the cost of a few support calls from users who can't access their email to get to a reactivation code. This at the expense of security and Sarah Palin's reputation. Worth it? Probably not.

PART IV: Forgotten Password Functionality

I already mentioned why you should for handling forgotten/lost user passwords; it also goes without saying that you should never e-mail users their actual passwords. There are at least two more all-too-common pitfalls to avoid in this field:

  1. Don't reset a forgotten password to an autogenerated strong password - such passwords are notoriously hard to remember, which means the user must either change it or write it down - say, on a bright yellow Post-It on the edge of their monitor. Instead of setting a new password, just let users pick a new one right away - which is what they want to do anyway. (An exception to this might be if the users are universally using a password manager to store/manage passwords that would normally be impossible to remember without writing it down).
  2. Always hash the lost password code/token in the database. AGAIN, this code is another example of a Password Equivalent, so it MUST be hashed in case an attacker got their hands on your database. When a lost password code is requested, send the plaintext code to the user's email address, then hash it, save the hash in your database -- and throw away the original. Just like a password or a persistent login token.

A final note: always make sure your interface for entering the 'lost password code' is at least as secure as your login form itself, or an attacker will simply use this to gain access instead. Making sure you generate very long 'lost password codes' (for example, 16 case-sensitive alphanumeric characters) is a good start, but consider adding the same throttling scheme that you do for the login form itself.

PART V: Checking Password Strength

First, you'll want to read this small article for a reality check: The 500 most common passwords Okay, so maybe the list isn't the list of most common passwords on system , but it's a good indication of how poorly people will choose their passwords when there is no enforced policy in place. Plus, the list looks frighteningly close to home when you compare it to publicly available analyses of recently stolen passwords. So: With no minimum password strength requirements, 2% of users use one of the top 20 most common passwords. Meaning: if an attacker gets just 20 attempts, 1 in 50 accounts on your website will be crackable. Thwarting this requires calculating the entropy of a password and then applying a threshold. The National Institute of Standards and Technology (NIST) Special Publication 800-63 has a set of very good suggestions. That, when combined with a dictionary and keyboard layout analysis (for example, 'qwertyuiop' is a bad password), can reject 99% of all poorly selected passwords at a level of 18 bits of entropy. Simply calculating password strength and showing a visual strength meter to a user is good, but insufficient. Unless it is enforced, a lot of users will most likely ignore it. And for a refreshing take on user-friendliness of high-entropy passwords, Randall Munroe's Password Strength xkcd is highly recommended. Utilize Troy Hunt's Have I Been Pwned API to check users passwords against passwords compromised in public data breaches.

PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts

First, have a look at the numbers: Password Recovery Speeds - How long will your password stand up If you don't have the time to look through the tables in that link, here's the list of them:

  1. It takes virtually no time to crack a weak password, even if you're cracking it with an abacus
  2. It takes virtually no time to crack an alphanumeric 9-character password if it is case insensitive
  3. It takes virtually no time to crack an intricate, symbols-and-letters-and-numbers, upper-and-lowercase password if it is less than 8 characters long (a desktop PC can search the entire keyspace up to 7 characters in a matter of days or even hours)
  4. It would, however, take an inordinate amount of time to crack even a 6-character password, if you were limited to one attempt per second!

So what can we learn from these numbers? Well, lots, but we can focus on the most important part: the fact that preventing large numbers of rapid-fire successive login attempts (ie. the attack) really isn't that difficult. But preventing it isn't as easy as it seems. Generally speaking, you have three choices that are all effective against brute-force attacks :

  • Present a after N failed attempts (annoying as hell and often ineffective -- but I'm repeating myself here)- and requiring email verification after N failed attempts (this is a DoS attack waiting to happen)- And finally, : that is, setting a time delay between attempts after N failed attempts (yes, DoS attacks are still possible, but at least they are far less likely and a lot more complicated to pull off). A short time delay that increases with the number of failed attempts, like:

DoS attacking this scheme would be very impractical, since the resulting lockout time is slightly larger than the sum of the previous lockout times.

To clarify: The delay is a delay before returning the response to the browser. It is more like a timeout or refractory period during which login attempts to a specific account or from a specific IP address will not be accepted or evaluated at all. That is, correct credentials will not return in a successful login, and incorrect credentials will not trigger a delay increase. A medium length time delay that goes into effect after N failed attempts, like:

  • - DoS attacking this scheme would be quite impractical, but certainly doable. Also, it might be relevant to note that such a long delay can be very annoying for a legitimate user. Forgetful users will dislike you. Combining the two approaches - either a fixed, short time delay that goes into effect after N failed attempts, like:
  • - Or, an increasing delay with a fixed upper bound, like:

This final scheme was taken from the OWASP best-practices suggestions (link 1 from the MUST-READ list) and should be considered best practice, even if it is admittedly on the restrictive side.

DoS attacking this final login throttling scheme would be impractical. And as a final touch, always allow persistent (cookie) logins (and/or a CAPTCHA-verified login form) to pass through, so legitimate users won't even be delayed . That way, the very impractical DoS attack becomes an impractical attack. Additionally, it makes sense to do more aggressive throttling on admin accounts, since those are the most attractive entry points

PART VII: Distributed Brute Force Attacks

Just as an aside, more advanced attackers will try to circumvent login throttling by 'spreading their activities':

  • Distributing the attempts on a botnet to prevent IP address flagging- Rather than picking one user and trying the 50.000 most common passwords (which they can't, because of our throttling), they will pick THE most common password and try it against 50.000 users instead. That way, not only do they get around maximum-attempts measures like CAPTCHAs and login throttling, their chance of success increases as well, since the number 1 most common password is far more likely than number 49.995- Spacing the login requests for each user account, say, 30 seconds apart, to sneak under the radar Here, the best practice would be , and using a running average of your site's bad-login frequency as the basis for an upper limit that you then impose on all users. Too abstract? Let me rephrase: Say your site has had an average of 120 bad logins per day over the past 3 months. Using that (running average), your system might set the global limit to 3 times that -- ie. 360 failed attempts over a 24 hour period. Then, if the total number of failed attempts across all accounts exceeds that number within one day (or even better, monitor the rate of acceleration and trigger on a calculated threshold), it activates system-wide login throttling - meaning short delays for ALL users (still, with the exception of cookie logins and/or backup CAPTCHA logins). I also posted a question with more details and a really good discussion of how to avoid tricky pitfals in fending off distributed brute force attacks

PART VIII: Two-Factor Authentication and Authentication Providers

Credentials can be compromised, whether by exploits, passwords being written down and lost, laptops with keys being stolen, or users entering logins into phishing sites. Logins can be further protected with two-factor authentication, which uses out-of-band factors such as single-use codes received from a phone call, SMS message, app, or dongle. Several providers offer two-factor authentication services. Authentication can be completely delegated to a single-sign-on service, where another provider handles collecting credentials. This pushes the problem to a trusted third party. Google and Twitter both provide standards-based SSO services, while Facebook provides a similar proprietary solution.

MUST-READ LINKS About Web Authentication

  1. OWASP Guide To Authentication / OWASP Authentication Cheat Sheet
  2. Dos and Don’ts of Client Authentication on the Web (very readable MIT research paper)
  3. Wikipedia: HTTP cookie
  4. Personal knowledge questions for fallback authentication: Security questions in the era of Facebook (very readable Berkeley research paper)
Up Vote0Down Vote
Grade: F

Nonces (Cryptographic Nonce) - Cross-site request forgery (CSRF)

When accessing a website via an internet browser or mobile app, one must first authenticate themselves in order to gain access to the requested resource. This process of authentication is typically performed using one or more secure cryptographic mechanisms such as Elliptic Curve Cryptography (ECC), Advanced Encryption Standard (AES) and Public-key infrastructure for electronic commerce (PGP-EVC).

When attempting to authenticate oneself against a website via an internet browser or mobile app, one must first provide the website with the necessary secure cryptographic parameters known as “nonces” which serve as unique identifiers within the secure cryptographic framework. The nonces should be provided to the website securely over a secure internet connection (such as HTTPS) to prevent unauthorized access by other individuals who have intercepted and obtained access to the website’s secure internet connection via another insecure internet connection or direct intercept and possession of the website’s secure internet connection and control over it.

When providing the necessary secure cryptographic parameters known as “nonces” which serve as unique identifiers within the secure cryptographic framework to a website, one should ensure that they provide them in such a manner that they can be securely intercepted and obtained access to the website’s secure internet connection via another insecure internet connection or direct intercept and possession of the website’s secure internet connection and control over it.

In summary, when attempting to authenticate oneself against a website via an internet browser or mobile app, one must first provide the website with the necessary secure cryptographic parameters known as “nonces” which serve as unique identifiers within the secure cryptographic framework securely over a secure internet connection (such as HTTPS) to prevent unauthorized access by other individuals who have intercepted and obtained access to