Songo has been researching the source code of Spring Security recently, and has found a lot of interesting code.

Many people joke that Spring Security has more weight than Shiro. This weight does not come from nothing. Weight has the advantage of weight, but it provides more protection.

Take this code Songo recently saw:

protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
		throws AuthenticationException {
	prepareTimingAttackProtection();
	try {
		UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
		if (loadedUser == null) {
			throw new InternalAuthenticationServiceException(
					"UserDetailsService returned null, which is an interface contract violation");
		}
		return loadedUser;
	}
	catch (UsernameNotFoundException ex) {
		mitigateAgainstTimingAttack(authentication);
		throw ex;
	}
	catch (InternalAuthenticationServiceException ex) {
		throw ex;
	}
	catch (Exception ex) {
		throw newInternalAuthenticationServiceException(ex.getMessage(), ex); }}Copy the code

This code is located in the DaoAuthenticationProvider class, in order to facilitate everybody understanding, I simply said under the context of this code.

After the user submits the username and password to log in, Spring Security needs to query the user in the database based on the username submitted by the user. If you are not familiar with this, please refer to songo’s previous article:

  1. How does Spring Security store user data into the database?
  2. Spring Security+Spring Data Jpa, Security management is only easier!

Once the user object is found, compare the difference between the user password retrieved from the database and the password submitted by the user. For specific comparison work, you can refer to the two postures of password encryption in Spring Boot! The article.

Spring Security queries the user in the database based on the user name passed in when the user logs in, and returns the found user. There is also an authentication parameter in the method, which holds the username/password information passed in when the user logs in.

So what’s so amazing about this code?

Let’s do it line by line.

The source code to comb

1

Calling the first method came prepareTimingAttackProtection method, it can be seen from the method name, this is in preparation for the timing attack, defense, so what is timing attack? Don’t worry, Songo will explain later. Let’s go through the process first. Execution of prepareTimingAttackProtection method is very simple, as follows:

private void prepareTimingAttackProtection(a) {
	if (this.userNotFoundEncodedPassword == null) {
		this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD); }}Copy the code

You can do this by encoding the constant USER_NOT_FOUND_PASSWORD using the passwordEncoder. ), the coding results assigned to userNotFoundEncodedPassword variables.

2

Then call the loadUserByUsername method to query the user in the database according to the user name passed in by the logged-in user. If found, the object found will be returned.

3

If thrown in the process of query UsernameNotFoundException abnormalities, arguably, an exception is thrown directly, don’t have to do the following code, because, according to the users don’t find the login is failed, surely there is no need for password comparison operation!

But attention, call the mitigateAgainstTimingAttack method before throwing an exception. This method, by its name, is meant to mitigate timed attacks.

Let’s take a look at the execution flow of this method:

private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
	if(authentication.getCredentials() ! =null) {
		String presentedPassword = authentication.getCredentials().toString();
		this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword); }}Copy the code

PresentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: presentedPassword: matches So the second parameter userNotFoundEncodedPassword instead, userNotFoundEncodedPassword is our assignment when call prepareTimingAttackProtection method at the beginning of the variable. This cipher match was doomed from the start, so why do it at all?

Timing attacks

This brings us to today’s topic — timed attacks.

Timing attack is a kind of bypass attack. In cryptography, side-channel attack is also called side-channel attack or side-channel attack.

This attack does not exploit a theoretical weakness in the encryption algorithm, nor does it brute force, but rather takes information from the physical implementation of the cryptosystem. For example: time information, power consumption, electromagnetic leakage and other additional sources of information, which can be used to further crack the system.

There are different categories of bypass attacks:

  • Cache side-channel Attacks are used to obtain sensitive information in the Cache by obtaining access rights to the Cache. For example, an attacker accesses the physical host of a cloud host and accesses the storage device.
  • Timing attacks determine the operation based on the operation time, determine the storage device where the data is located by comparing the operation time, or steal data based on the communication time difference.
  • In the bypass attack based on power monitoring, the power consumption of different hardware circuit units on the same device is also different. Therefore, the power consumption of a program will change with the hardware circuit unit used by the program. Based on this, the hardware unit in which the data output is located can be inferred to steal data.
  • Electromagnetic attack, or Electromagnetic attack, is a method used for non-cryptographic eavesdropping as well as cryptological attacks, in which devices emit Electromagnetic radiation that can be analyzed to determine whether text, sound or images are being transmitted. Such as TEMPEST attack.
  • Acoustic cryptanalysis, which captures information by capturing the Acoustic signals leaked by the device as it performs calculations (similar to power analysis).
  • Differential error analysis, hidden data is detected when the program runs in error and output error messages.
  • Data remanence enables sensitive Data to be read that should be deleted (such as a cold start attack).
  • The Row hammer attack is an example of this type of attack. In this attack, the memory space next to the forbidden memory location is at risk of state retention loss if it is frequently accessed.
  • Optical mode, that is, hidden data is captured by some visual optical instruments (such as high definition cameras, high definition cameras and other equipment).

All types of attacks take advantage of the fact that the encryption/decryption system performs an encryption/decryption operation in which the algorithmic logic is not detected, but provides useful additional information (hence the name “bypass”) through physical effects that often contain secret data such as keys, passwords, ciphertext, etc.

The code in Spring Security above is designed to prevent timing attacks.

How do you do that? Assuming that Spring Security from the database to the user information directly throw an exception, did not go to perform mitigateAgainstTimingAttack method, then the hacker after a lot of testing, again through the statistical analysis, you will find there are some login validation takes significantly less than the other login, Then it is inferred that the users with short login authentication time are non-existent, while the users with long login time are existing in the database.

Now, in the Spring Security by performing mitigateAgainstTimingAttack method, no matter the user exists or does not exist, log on to check the time will not have obvious difference, thus avoiding the timing attacks.

How long does it take to execute the passwordEncoder. Matches method? It depends on how you time it, but the smaller the units, the greater the difference: milliseconds (ms), microseconds (µs), nanoseconds (NS), picoseconds (PS), femtoseconds (FS), attoseconds (As), oblique seconds (ZS).

In addition, Spring Security introduces a concept called adaptive one-way functions in passwordEncoder for Security purposes. These functions are deliberately slow to execute and consume a lot of system resources, so it is necessary to defend against timed attacks.

As for adaptive one-way functions, this is a story for another time, songo and friends to talk about ~

Well, today is the first and small friends chat so much, small friends decided to harvest, remember to point to see the next songge oh ~

The Spring Security series is now 49 installments in length. If you’re interested, check out the rest of the series:

  1. Dig a big hole and Spring Security will do it!
  2. How to decrypt the password
  3. A step-by-step guide to customizing form logins in Spring Security
  4. Spring Security does front and back separation, so don’t do page jumps! All JSON interactions
  5. Authorization in Spring Security used to be so simple
  6. How does Spring Security store user data into the database?
  7. Spring Security+Spring Data Jpa, Security management is only easier!
  8. Spring Boot + Spring Security enables automatic login
  9. Spring Boot automatic login. How to control security risks?
  10. How is Spring Security better than Shiro in microservices projects?
  11. Two ways for SpringSecurity to customize authentication logic (advanced play)
  12. How can I quickly view information such as the IP address of the login user in Spring Security?
  13. Spring Security automatically kicks out the previous login user.
  14. How can I kick out a user who has logged in to Spring Boot + Vue?
  15. Spring Security comes with a firewall! You have no idea how secure your system is!
  16. What is a session fixed attack? How do I defend against session fixation attacks in Spring Boot?
  17. How does Spring Security handle session sharing in a clustered deployment?
  18. Songgo hand in hand to teach you in SpringBoot CSRF attack! So easy!
  19. Learn to learn thoroughly! Spring Security CSRF defense source code parsing
  20. Two poses for password encryption in Spring Boot!
  21. How to learn Spring Security? Why must we study systematically?
  22. Spring Security has two different resource release policies. Do not use them incorrectly.
  23. Spring Boot + CAS single sign-on
  24. Spring Boot is the third way to implement single sign-on!
  25. How do I Connect to the Database in Spring Boot+CAS SINGLE Sign-on?
  26. Spring Boot+CAS default login page is too ugly, how to do?
  27. How to carry Token in request header with Swagger
  28. Summary of three cross-domain scenarios in Spring Boot
  29. How to implement HTTP authentication in Spring Boot?
  30. Four types of permission control in Spring Security
  31. Spring Security multiple encryption solutions coexist, old and old system integration sharp tools!
  32. Magic! New objects can also be managed by the Spring container!
  33. What is the meaning of and in Spring Security configuration?
  34. Spring Security exception handling
  35. I’ve never seen a login like this before in years of writing code!
  36. Can Spring Security have multiple filter chains at the same time?
  37. Can Spring Security interwork with multiple user tables simultaneously?
  38. In Spring Security, I want to get user login information from the child thread. What do I do?
  39. FilterChainProxy
  40. Learn more about SecurityConfigurer
  41. Understanding HttpSecurity
  42. Deep understanding of AuthenticationManagerBuilder [source article]
  43. Play With Spring Security in a user-defined way you probably haven’t seen before!
  44. Deep understanding of WebSecurityConfigurerAdapter [source article]
  45. Here are eight classic design patterns from the Spring Security framework
  46. Spring Security initialization process
  47. Why is the Spring Security OAuth you are using expired? Songo’s got a word for everyone!
  48. A weird login problem