Heim  >  Artikel  >  Java  >  Fallstricke bei der Autorisierung: Was verschleiert Keycloak?

Fallstricke bei der Autorisierung: Was verschleiert Keycloak?

WBOY
WBOYOriginal
2024-07-19 17:25:20574Durchsuche

Autor: Valerii Filatov

Benutzerautorisierung und -registrierung sind wichtige Bestandteile jeder Anwendung, nicht nur für Benutzer, sondern auch aus Sicherheitsgründen. Welche Fallstricke birgt der Quellcode einer beliebten Open-Source-Lösung für das Identitätsmanagement? Wie wirken sie sich auf die Anwendung aus?

Authorization pitfalls: what does Keycloak cloak?

Wenn Sie jemals eine Autorisierung für Web-Apps implementiert haben, kennen Sie wahrscheinlich alle frustrierenden Probleme, die auftreten können. Ich bin auch keine Ausnahme.

Einmal habe ich die Messenger-basierte Autorisierung im Frontend-Teil eines Projekts implementiert. Es schien die einfachste Aufgabe der Welt zu sein, aber es stellte sich heraus, dass das Gegenteil der Fall war: Fristen rückten näher, Code stolperte über Messenger-APIs und die Leute um mich herum schrien.

Nach diesem Fall zeigte mir mein Kollege ein cooles Tool, das die Implementierung der Autorisierung in unseren zukünftigen Projekten optimieren würde. Bei diesem Projekt handelte es sich um Keycloak, eine Open-Source-Java-Lösung zur Ermöglichung von Single Sign-On (SSO) mit Identitäts- und Zugriffsverwaltung für moderne Apps und Dienste.

Da ich die Lösung selbst verwende, finde ich es interessant, in den Quellcode einzusteigen und mit dem statischen Analysator von PVS-Studio nach den dort versteckten Fehlern zu suchen.

He-he, klassische NullPointerException

Jemand klopfte an die Tür. Der Junior-Entwickler versuchte, eine Tür zu öffnen und stürzte ab. „NullPointerException!“ schloss der Senior Dev.

Fehler im Zusammenhang mit der Überprüfung auf null treten in fast jedem Projekt auf, das wir zuvor überprüft haben. Beginnen wir also mit diesem alten, aber goldenen Fehler.

Fragment N1

private void checkRevocationUsingOCSP(X509Certificate[] certs) 
  throws GeneralSecurityException {
    ....    
    if (rs == null) {
      if (_ocspFailOpen)
        logger.warnf(....);
      else
        throw new GeneralSecurityException(....);
    }

    if (rs.getRevocationStatus() == 
      OCSPProvider.RevocationStatus.UNKNOWN) { // <=
        if (_ocspFailOpen)
            logger.warnf(....);
        else
            throw new GeneralSecurityException(....);
    ....
}

Warnung:

V6008 Mögliche Null-Dereferenzierung von „rs“.

Dieser Codeausschnitt hat eine Null-Prüfung, aber wir müssen verstehen, was darin vor sich geht. Wenn die Variable _oscpFailOpen wahr ist, löst das Programm keine Ausnahme aus. Es speichert nur das Protokoll darüber und setzt die Ausführung fort – es erhält im folgenden if eine NullPointerException, da die Variable rs bereits in < verwendet wurde 🎜>wenn.

Es könnte so aussehen, als würde das Programm einfach eine weitere Ausnahme auslösen, wenn es nicht die

NullPointerException gäbe. Dies ist jedoch nicht der Fall, da die Variable _oscpFailOpen wahr ist und das Programm mit der Ausführung fortfahren sollte. Kein Schicksal, es stolperte über den Null-Zeiger und fiel in die Ausnahme.

Fragment N2

public void writeDateAttributeValue(XMLGregorianCalendar attributeValue) 
  throws ProcessingException {
    ....
    StaxUtil.writeAttribute(
      writer, 
      "xsi", 
      JBossSAMLURIConstants.XSI_NSURI.get(), 
      "type", 
      "xs:" + attributeValue.getXMLSchemaType().getLocalPart()   // <=
    ); 

    if (attributeValue == null) {
      StaxUtil.writeAttribute(
        writer, 
        "xsi", 
        JBossSAMLURIConstants.XSI_NSURI.get(), 
        "nil", 
        "true"
      );
    ....
}
Warnung*:*

V6060 Die „attributeValue“-Referenz wurde verwendet, bevor sie gegen null verifiziert wurde.

„Besser spät als nie“, dieser Satz ist für viele Fälle gut genug, aber leider nicht für die

Null-Prüfung. Im obigen Codeausschnitt wird das Objekt attributeValue verwendet, bevor es auf Existenz überprüft wird, was zur NullPointerException. führt

Hinweis. Wenn Sie sich weitere Beispiele für solche Fehler ansehen möchten, haben wir eine Liste für Sie zusammengestellt!

Argumente?

Ich weiß nicht, wie es passiert ist, aber Keycloak hat Fehler im Zusammenhang mit der Anzahl der Argumente in den Formatzeichenfolgenfunktionen. Es handelt sich jedoch nicht um eine illustrative Statistik, sondern nur um eine lustige Tatsache.

Fragment N3

protected void process() {
  ....
  if (f == null) {
    ....
  } else {
    ....
    if (isListType(f.getType()) && t instanceof ParameterizedType) {
      t = ((ParameterizedType) t).getActualTypeArguments()[0];
      if (!isBasicType(t) && t instanceof Class) {
        ....
        out.printf(", where value is:\n", ts);              // <=
        ....
      }
    } else if (isMapType(f.getType()) && t instanceof ParameterizedType) {
      ....
      out.printf(", where value is:\n", ts);                // <=
      ....
    }
  }
}
Warnung:

V6046 Falsches Format. Es wird eine andere Anzahl von Formatelementen erwartet. Nicht verwendete Argumente: 1.

Wenn im obigen Fragment die Funktion

printf aufgerufen wird, übergeben wir eine Formatzeichenfolge und einen Wert, der in die Zeichenfolge eingesetzt werden soll. Es gibt nur ein Problem: Es gibt einfach keinen Platz in der Zeichenfolge, um Argumente zu ersetzen.

Es ist ziemlich interessant, dass ein Entwickler nicht nur beide Codefragmente von

if nach else if kopiert und eingefügt hat, sondern dass ein Entwickler auch den Fehler in else kopiert und eingefügt hat wenn.

Im nächsten Snippet haben wir den umgekehrten Fall: Entwickler haben mit Argumenten gespart.

Fragment N4

public String toString() {
  return String.format(
    "AuthenticationSessionAuthNoteUpdateEvent 
      [ authSessionId=%s,
        tabId=%s,
        clientUUID=%s,
        authNotesFragment=%s ]", 
    authSessionId, 
    clientUUID, 
    authNotesFragment);      // <=
}
Warnung:

V6046 Falsches Format. Es wird eine andere Anzahl von Formatelementen erwartet. Fehlende Argumente: 4.

Obwohl Entwickler die Argumente

authSessionId, clientUUID und authNotesFragment an die Funktion übergeben haben, fehlt das vierte Argument tabld etwas.

In diesem Fall löst die Methode

String.format eine IllegalFormatException aus, was eine böse Überraschung sein kann.

Unreiner Code

Die folgenden PVS-Studio-Warnungen beziehen sich nicht auf Codezustandsfehler. Bei diesen Warnungen geht es eher um die Qualität des Codes. Ich habe nur darauf hingewiesen, dass es sich hierbei nicht um eindeutige Fehler handelt.

"What's the point of looking at them?" you may think. First, I believe that code should be clean and neat. It's not a matter of tastes: clean code is not only about the visual experience but also about code readability. Imho, it's important for any project, especially Open Source. Secondly, I'd like to show that the PVS-Studio static analyzer helps not only fix errors in code but also makes it beautiful and clean.

Not enough variables, My Lord!

For some reason, the following code fragment looks in my mind like an evil plan of someone who has a bad attitude to use variables: "Let's adopt variables and leave them waiting in horror for the garbage collector to gobble them up..."

Fragment N5

 private void onUserRemoved(RealmModel realm, String userId) {
    int num = em.createNamedQuery("deleteClientSessionsByUser")
      .setParameter("userId", userId).executeUpdate();             // <=
    num = em.createNamedQuery("deleteUserSessionsByUser")
      .setParameter("userId", userId).executeUpdate();
}

Warning:

V6021 The value is assigned to the 'num' variable but is not used.

From the point of program operation, nothing terrible happens in this code snippet. But it's still not clear why developers wrote that.

The num variable contains the number of set parameters that the executeUpdate method returns. So, I thought that the method might have had a check for changes. Even if I rewind in time, I'll only find that calls to the method aren't written to a variable but accept the current state a little later.

The result is a useless assignment to the variable—just like in the next fragment.

Fragment N6

private void verifyCodeVerifier(String codeVerifier, String codeChallenge, 
  String codeChallengeMethod) throws ClientPolicyException {
    ....
    String codeVerifierEncoded = codeVerifier;

    try {
      if (codeChallengeMethod != null &&
        codeChallengeMethod.equals(OAuth2Constants.PKCE_METHOD_S256)) {

        codeVerifierEncoded = generateS256CodeChallenge(codeVerifier);

        } else {
          codeVerifierEncoded = codeVerifier; // <=
        }
    } catch (Exception nae) {
      ....
    }
}

Warning:

V6026 This value is already assigned to the 'codeVerifierEncoded' variable.

If you look at the code, you can see that before this, the codeVerifierEncoded variable has already assigned the same value in the else branch. A developer just did redundant action: and useless, and overcomplicating.

The next code fragment just amuses me.

Fragment N7

private static Type[] extractTypeVariables(Map<String, Type> typeVarMap, 
  Type[] types){
    for (int j = 0; j < types.length; j++){
      if (types[j] instanceof TypeVariable){
        TypeVariable tv = (TypeVariable) types[j];
        types[j] = typeVarMap.get(tv.getName());
      } else {
        types[j] = types[j];     // <=
      }
    }
    return types;
}

Warning:

V6005 The variable 'types[j]' is assigned to itself.

It looks just like the previous snippet, but honestly, I'm totally lost on what this code is trying to do.

At first, I thought we were facing a nested loop here, and the author had just mixed up the variables i and j. But eventually I realized that there's only one loop here.

I also thought the assignment appeared when developers were refactoring the code, which might have been even more complicated before. In the end, I found that the function was originally created this way (commit).

So sweet copy-paste

Copy-paste errors are quite common. I'm sure you've seen them even in your own code.

Keycloak has some traces of the copy-paste use, too.

Fragment 8

public class IDFedLSInputResolver implements LSResourceResolver {
  ....

  static {
    ....
    schemaLocations.put("saml-schema-metadata-2.0.xsd", 
      "schema/saml/v2/saml-schema-metadata-2.0.xsd");
    schemaLocations.put("saml-schema-x500-2.0.xsd", 
      "schema/saml/v2/saml-schema-x500-2.0.xsd");
    schemaLocations.put("saml-schema-xacml-2.0.xsd", 
      "schema/saml/v2/saml-schema-xacml-2.0.xsd");

    schemaLocations.put("saml-schema-xacml-2.0.xsd", 
      "schema/saml/v2/saml-schema-xacml-2.0.xsd");          // <=

    schemaLocations.put("saml-schema-authn-context-2.0.xsd", 
      "schema/saml/v2/saml-schema-authn-context-2.0.xsd");
    ....
  }
  ....
}

Warning*:*

V6033 An item with the same key '"saml-schema-xacml-2.0.xsd"' has already been added.

Honestly, even though I knew there was a typo in the source code, I had a hard time finding it right away in the code.

If you notice, in the schemaLocations.put method calls, the passed arguments are quite similar. So, I assume that the dev who wrote this code simply copied a string as a template and then just changed values. The problem is that during copy-pasting, one line that repeats the previous one has crept into the project.

Such "typos" can either lead to serious consequences or have no effect at all. This copy-pasting example has been in the project since November 21, 2017 (commit), and I don't think it causes any serious problems.

We're including this error in the article to remind developers to be careful when copying and pasting code fragments and to keep an eye on any changes in code. Want to read more about it? Here's the article about the copy-paste typos.

Unreachable code

The headline gives us a little clue as to what kind of warning awaits us in the following snippet. I suggest you use your detective skills to spot the flaw yourself.

Fragment N9

public void executeOnEvent(ClientPolicyContext context) 
  throws ClientPolicyException {
    switch (context.getEvent()) {
      case REGISTER:
      case UPDATE:
        ....
      case RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST:
        ....
        executeOnAuthorizationRequest(ropcContext.getParams());
        return;
      default:
        return;
    }
}

It's not that easy to detect, isn't it? I'm not gloating over you, I just give you a chance to roughly access the situation. I show it because a small flaw makes it harder for the developer to find the error without examining the rest of the code. To find out what error is lurking in this code snippet, we need to look at what is cloaked in the executeOnAuthorizationRequest method:

private void executeOnAuthorizationRequest(MultivaluedMap<String, 
  String> params) throws ClientPolicyException {
    ....
    throw new ClientPolicyException(....);
}

Yes, this method throws an exception. That is, all the code written after calling this method will be unreachable—the PVS-Studio analyzer detected it.

public void executeOnEvent(ClientPolicyContext context) 
  throws ClientPolicyException {
    switch (context.getEvent()) {
      case REGISTER:
      case UPDATE:
        ....
      case RESOURCE_OWNER_PASSWORD_CREDENTIALS_REQUEST:
        ....
        executeOnAuthorizationRequest(ropcContext.getParams());
        return;       // <=
      default:
        return;
    }
}

Warning:

V6019 Unreachable code detected. It is possible that an error is present.

Even if this flaw is quite small, a similar case could lead to more serious consequences. I can only note here that a static analyzer will help you avoid such unpleasant things.

I dictate CONDITION

Now, let's look at conditional statements and cases when they execute their code.

Fragment N10

public boolean validatePassword(AuthenticationFlowContext context, 
  UserModel user, MultivaluedMap<String, String> inputData, 
  boolean clearUser) {

    ....

    if (password == null || password.isEmpty()) {
      return badPasswordHandler(context, user, clearUser,true);
    }

    ....

    if (password != null && !password.isEmpty() &&    // <=
      user.credentialManager()
        .isValid(UserCredentialModel.password(password))) { 
      ....
    }
}

Warning:

V6007 Expression 'password != null' is always true.

V6007 Expression '!password.isEmpty()' is always true.

Here are two warnings in one line! What does the analyzer warn us about? The first conditional statement checks that the password is non-null and non-empty. If the opposite occurs, the function is no longer executed. In the line the analyzer highlighted, both of these checks are repeated, so the conditions are always true.

On the one hand, it's better to check than not to check. On the other, such duplicates may lead to missing the part of the condition that may be equal to false—it can really affect the program operation.

Let's repeat the exercise.

Fragment N11

public KeycloakUriBuilder schemeSpecificPart(String ssp)
  throws IllegalArgumentException {
    if (ssp == null) 
      throw new IllegalArgumentException(....);
    ....
    if (ssp != null) // <=
      sb.append(ssp);
    ....
}

Warning:

V6007 Expression 'ssp != null' is always true.

In general, the case is the same. If the ssp variable is null, the program throws an exception. So, the condition below isn't only true all the time but is also redundant because the corresponding code block will always be executed.

The condition in the next fragment is also redundant.

Fragment N12

protected String changeSessionId(HttpScope session) {
  if (!deployment.turnOffChangeSessionIdOnLogin()) 
    return session.getID();     // <=
  else return session.getID();
}

Warning:

V6004 The 'then' statement is equivalent to the 'else' statement.

In this method, the same code is executed under different seasons, the moon phases, and, most importantly, under different conditions. So, again, the condition is redundant here.

Digging into the code, I found the code snippet that is like two drops of water similar to the one above:

protected String changeSessionId(HttpSession session) {
  if (!deployment.turnOffChangeSessionIdOnLogin()) 
    return ChangeSessionId.changeSessionId(exchange, false);
  else return session.getId();
}

As you can see, when the condition is executed, the method that changes the session ID is called.

So, we can make two guesses: either devs just copied the code and changed the condition result, or the first condition still should have updated the session, and this error goes way beyond the "sloppy" code.

But we mustn't live by redundant conditions alone*!*

Fragment N13

static String getParameter(String source, String messageIfNotFound) {
  Matcher matcher = PLACEHOLDER_PARAM_PATTERN.matcher(source);

  while (matcher.find()) {
    return matcher.group(1).replaceAll("'", ""); // <=
  }

  if (messageIfNotFound != null) {
    throw new RuntimeException(messageIfNotFound);
  }

  return null;
}

Warning:

V6037 An unconditional 'return' within a loop.

I have a feeling this while *was raised by *ifs. This code may have some hidden intentions, but the analyzer and I see the same thing here: a loop that always performs one iteration.

The code author might have wanted a different behavioral outcome. Even if they don't want, we'll find this code a bit harder to understand than if there is just a conditional operator.

String comparison

In the following snippet, a developer suggests everything is so easy. But it turns out it's not.

Fragment N14

public boolean equals(Object o) {
  if (this == o) return true;
  if (o == null || getClass() != o.getClass()) return false;

  Key key = (Key) o;

  if (action != key.action) return false;         // <=
  ....
}

Warning:

V6013 Strings 'action' and 'key.action' are compared by reference. Possibly an equality comparison was intended.

Comparing strings implies that we compare their contents. We actually compare object references. This also applies to arrays and collections, not only strings. I think it's clear that in certain cases, code operations can lead to unexpected consequences. Most importantly, it's pretty easy to fix such an error:

public boolean equals(Object o) {
  ....
  if (!action.equals(key.action)) return false;
  ....
}

The equals method returns a comparison exactly to the contents of two strings. Victory!

I'll draw your attention to the fact that the static analyzer has detected the error, which a developer would most likely have missed when reviewing the code. You can read about this and other reasons for using static analysis in this article.

Double-checked locking

Double-checked locking is a parallel design pattern used to reduce the overhead of acquiring a lock. We first check the lock condition without synchronization. If it's encountered, the thread tries to acquire the lock.

If we streamline it, this pattern helps get the lock only when it's actually needed.

I think you've already guessed that there are bugs in the implementation of this template as I've started talking about it. Actually, they are.

Fragment N15

public class WelcomeResource {
  private AtomicBoolean shouldBootstrap;

  ....

  private boolean shouldBootstrap() {
    if (shouldBootstrap == null) {
      synchronized (this) {
        if (shouldBootstrap == null) {
          shouldBootstrap = new AtomicBoolean(....);
        }
      }
    }
    return shouldBootstrap.get();
  }

Warning:

V6082 Unsafe double-checked locking. The field should be declared as volatile.

The analyzer warns that the shouldBootstrap field doesn't have the volatile modifier. What does it affect? In such code, it's likely that different threads use an object until they're fully initialized.

This fact doesn't seem to be that significant, does it? In the next example, the compiler may change the action order with non-volatile fields.

Fragment N16

public class DefaultFreeMarkerProviderFactory 
  implements FreeMarkerProviderFactory {

    private DefaultFreeMarkerProvider provider;   // <=

    ....

    public DefaultFreeMarkerProvider create(KeycloakSession session) {
      if (provider == null) {
        synchronized (this) {
          if (provider == null) {
            if (Config.scope("theme").getBoolean("cacheTemplates", true)) {
              cache = new ConcurrentHashMap<>();
            }
            kcSanitizeMethod = new KeycloakSanitizerMethod();
            provider = new DefaultFreeMarkerProvider(cache, kcSanitizeMethod);
          }
        }
      }
      return provider;
    }
}

Warning:

V6082 Unsafe double-checked locking. The field should be declared as volatile.

Warum beheben Entwickler diese Codefragmente nicht, wenn der Fehler so gefährlich ist? Der Fehler ist nicht nur gefährlich, sondern auch heimtückisch. Die meiste Zeit funktioniert alles so, wie es sollte. Es gibt viele verschiedene Gründe, warum schlechtes Verhalten auftreten kann, beispielsweise aufgrund der verwendeten JVM oder der Thread-Scheduler-Operationen. Daher kann es ziemlich schwierig sein, die Fehlerbedingungen zu reproduzieren.

Mehr über solche Fehler und deren Gründe können Sie im Artikel lesen.

Abschluss

Am Ende dieses Artikels möchte ich darauf hinweisen, dass ich den Analysator etwas nicht ordnungsgemäß verwendet habe. Ich wollte Sie nur unterhalten und Ihnen die Fehler im Projekt zeigen. Um Fehler zu beheben und ihnen vorzubeugen, ist es jedoch besser, den statischen Analysator regelmäßig beim Schreiben von Code zu verwenden. Mehr darüber können Sie hier lesen.

Der Analysator hat uns jedoch dabei geholfen, verschiedene Fehler zu erkennen, die sowohl mit dem Programmbetrieb als auch mit unzureichender Codesauberkeit zusammenhängen (ich halte das immer noch für wichtig, und Sie werden meine Meinung kaum ändern). Fehler sind nicht das Ende der Welt, wenn man sie rechtzeitig erkennt und behebt. Dabei hilft die statische Analyse. Probieren Sie PVS-Studio aus und prüfen Sie Ihr Projekt damit kostenlos.

Das obige ist der detaillierte Inhalt vonFallstricke bei der Autorisierung: Was verschleiert Keycloak?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:SortierungNächster Artikel:Sortierung