Rileva la divulgazione di password e le violazioni delle credenziali

Questa pagina descrive come utilizzare la funzionalità di difesa delle password di reCAPTCHA per rilevare le divulgazioni di password e le credenziali compromesse per impedire le violazioni di account (ATO) e gli attacchi di credential stuffing. Con reCAPTCHA, puoi eseguire audit regolari delle credenziali utente (password) nell'ambito di qualsiasi test per assicurarti che non siano state divulgate o violate. Per eseguire queste valutazioni, Google utilizza la funzionalità Controllo password.

Prima di iniziare

  1. Prepara l'ambiente per reCAPTCHA.

  2. Configura reCAPTCHA.

  3. Make sure that billing is enabled for your Google Cloud project.

    Per utilizzare la funzionalità Password Defense, reCAPTCHA richiede che la fatturazione sia collegata e abilitata nel progetto. Puoi attivare la fatturazione utilizzando una carta di credito o un ID fatturazione progetto esistente. Google Cloud Se hai bisogno di assistenza per la fatturazione, contatta l'assistenza per la fatturazione Cloud.

Controllare la presenza di credenziali violate e divulgate

Puoi verificare se un insieme di credenziali è stato compromesso utilizzando funzioni crittografiche o il container Docker.

Il container Docker è un client open source che implementa il calcolo multi-parte sicuro necessario per preservare la privacy dell'utente finale e cercare in modo sicuro le violazioni delle password. Per maggiori informazioni, consulta il repository GitHub. Il container Docker astrae la complessità dell'implementazione degli algoritmi crittografici e semplifica il processo di installazione. Ti consente inoltre di ospitare l'app container nella tua infrastruttura.

Funzione crittografica

Per verificare se un insieme di credenziali è stato compromesso, utilizza Password Defense quando crei valutazioni per azioni come accessi, modifiche della password e reimpostazioni della password.

Per verificare la divulgazione di password e le violazioni delle credenziali, completa i seguenti passaggi:

  1. Genera parametri di richiesta.
  2. Crea una valutazione per rilevare la divulgazione delle password.
  3. Verifica le credenziali divulgate da un'analisi.
  4. Interpreta il verdetto e intervieni.

Genera parametri di richiesta

  1. Calcola i parametri di richiesta necessari utilizzando le funzioni crittografiche richieste dal protocollo di massima privacy. reCAPTCHA fornisce librerie Java e TypeScript per facilitare la generazione di questi campi:

  2. Per creare verifiche del controllo delle password, crea un oggetto PasswordCheckVerifier.

    PasswordCheckVerifier verifier = new PasswordCheckVerifier();
    
  3. Per avviare una verifica, chiama il numero PasswordCheckVerifier#createVerification. Questo metodo utilizza il nome utente e la password per calcolare i parametri per eseguire il controllo della password.

    PasswordCheckVerification verification = verifier.createVerification("username", "password").get();
    
  4. Crea una valutazione utilizzando i parametri di verifica.

    byte[] lookupHashPrefix = verification.getLookupHashPrefix();
    byte[] encryptedUserCredentialsHash = verification.getEncryptedUserCredentialsHash();
    

    Gli array di byte lookupHashPrefix e encryptedUserCredentialsHash contengono i parametri necessari per avviare un controllo della password Assessment.

Crea una valutazione per rilevare la divulgazione delle password

Utilizza il metodo projects.assessments.create.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • PROJECT_ID: il tuo ID progetto Google Cloud
  • LOOKUP_HASH_PREFIX: prefisso dell'hash SHA-256 del nome utente
  • ENCRYPTED_USER_CREDENTIALS_HASH: hash Scrypt delle credenziali utente criptate

Metodo HTTP e URL:

POST https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments

Corpo JSON della richiesta:

{
  "private_password_leak_verification": {
    "lookup_hash_prefix": "LOOKUP_HASH_PREFIX",
    "encrypted_user_credentials_hash": "ENCRYPTED_USER_CREDENTIALS_HASH"
  }
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments"

PowerShell

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://recaptchaenterprise.googleapis.com/v1/projects/PROJECT_ID/assessments" | Select-Object -Expand Content

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/698047609967/assessments/fb22000000000000",
  "score": 0,
  "reasons": [],
  "privatePasswordLeakVerification": {
    "lookupHashPrefix": "zoxZwA==",
    "encryptedUserCredentialsHash": "AyRihRcKaGLj/FA/r2uqQY/fzfTaDb/nEcIUMeD3Tygp",
    "reencryptedUserCredentialsHash": "Aw65yEbLM39ww1ridDEfx5VhkWo11tzn/R1B88Qqwr/+"
    "encryptedLeakMatchPrefixes": [
      "n/n5fvPD6rmQPFyb4xk=", "IVQqzXsbZenaibID6OI=", ..., "INeMMndrfnlf6osCVvs=",
      "MkIpxt2x4mtyBnRODu0=", "AqUyAUWzi+v7Kx03e6o="]
  }
}

Verifica le credenziali divulgate da un'analisi

Dalla risposta al test estrai i campi reEncryptedUserCredentials e encryptedLeakMatchPrefixes e passali all'oggetto di verifica per determinare se le credenziali sono state compromesse o meno.

PasswordCheckResult result = verifier.verify(verification,
result.getReEncryptedUserCredentials(),
result.getEncryptedLeakMatchPrefixes()
).get();

System.out.println("Credentials leaked: " + result.areCredentialsLeaked());

Esempio di codice

Node.js (TypeScript)

Per scoprire come implementare il rilevamento delle fughe di password utilizzando Node.js (TypeScript), consulta l'esempio di codice TypeScript su GitHub.

Java

Per eseguire l'autenticazione in reCAPTCHA, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, vedi Configura l'autenticazione per un ambiente di sviluppo locale.


import com.google.cloud.recaptcha.passwordcheck.PasswordCheckResult;
import com.google.cloud.recaptcha.passwordcheck.PasswordCheckVerification;
import com.google.cloud.recaptcha.passwordcheck.PasswordCheckVerifier;
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
import com.google.protobuf.ByteString;
import com.google.recaptchaenterprise.v1.Assessment;
import com.google.recaptchaenterprise.v1.CreateAssessmentRequest;
import com.google.recaptchaenterprise.v1.PrivatePasswordLeakVerification;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.bouncycastle.util.encoders.Base64;

public class CreatePasswordLeakAssessment {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    // Google Cloud Project ID.
    String projectID = "project-id";

    // Username and password to be checked for credential breach.
    String username = "username";
    String password = "password";

    checkPasswordLeak(projectID, username, password);
  }

  /*
   * Detect password leaks and breached credentials to prevent account takeovers
   * (ATOs) and credential stuffing attacks.
   * For more information, see:
   * https://cloud.google.com/recaptcha-enterprise/docs/check-passwords and
   * https://security.googleblog.com/2019/02/protect-your-accounts-from-data.html

   * Steps:
   * 1. Use the 'create' method to hash and Encrypt the hashed username and
   * password.
   * 2. Send the hash prefix (26-bit) and the encrypted credentials to create
   * the assessment.(Hash prefix is used to partition the database.)
   * 3. Password leak assessment returns a list of encrypted credential hashes to
   * be compared with the decryption of the returned re-encrypted credentials.
   * Create Assessment also sends back re-encrypted credentials.
   * 4. The re-encrypted credential is then locally verified to see if there is
   * a match in the database.
   *
   * To perform hashing, encryption and verification (steps 1, 2 and 4),
   * reCAPTCHA Enterprise provides a helper library in Java.
   * See, https://github.com/GoogleCloudPlatform/java-recaptcha-password-check-helpers

   * If you want to extend this behavior to your own implementation/ languages,
   * make sure to perform the following steps:
   * 1. Hash the credentials (First 26 bits of the result is the
   * 'lookupHashPrefix')
   * 2. Encrypt the hash (result = 'encryptedUserCredentialsHash')
   * 3. Get back the PasswordLeak information from
   * reCAPTCHA Enterprise Create Assessment.
   * 4. Decrypt the obtained 'credentials.getReencryptedUserCredentialsHash()'
   * with the same key you used for encryption.
   * 5. Check if the decrypted credentials are present in
   * 'credentials.getEncryptedLeakMatchPrefixesList()'.
   * 6. If there is a match, that indicates a credential breach.
   */
  public static void checkPasswordLeak(
      String projectID, String username, String password)
      throws ExecutionException, InterruptedException, IOException {

    // Instantiate the java-password-leak-helper library to perform the cryptographic functions.
    PasswordCheckVerifier passwordLeak = new PasswordCheckVerifier();

    // Create the request to obtain the hash prefix and encrypted credentials.
    PasswordCheckVerification verification =
        passwordLeak.createVerification(username, password).get();

    byte[] lookupHashPrefix = Base64.encode(verification.getLookupHashPrefix());
    byte[] encryptedUserCredentialsHash = Base64.encode(
        verification.getEncryptedUserCredentialsHash());

    // Pass the credentials to the createPasswordLeakAssessment() to get back
    // the matching database entry for the hash prefix.
    PrivatePasswordLeakVerification credentials =
        createPasswordLeakAssessment(
            projectID,
            lookupHashPrefix,
            encryptedUserCredentialsHash);

    // Convert to appropriate input format.
    List<byte[]> leakMatchPrefixes =
        credentials.getEncryptedLeakMatchPrefixesList().stream()
            .map(x -> Base64.decode(x.toByteArray()))
            .collect(Collectors.toList());

    // Verify if the encrypted credentials are present in the obtained match list.
    PasswordCheckResult result =
        passwordLeak
            .verify(
                verification,
                Base64.decode(credentials.getReencryptedUserCredentialsHash().toByteArray()),
                leakMatchPrefixes)
            .get();

    // Check if the credential is leaked.
    boolean isLeaked = result.areCredentialsLeaked();
    System.out.printf("Is Credential leaked: %s", isLeaked);
  }

  // Create a reCAPTCHA Enterprise assessment.
  // Returns:  PrivatePasswordLeakVerification which contains
  // reencryptedUserCredentialsHash and credential breach database
  // whose prefix matches the lookupHashPrefix.
  private static PrivatePasswordLeakVerification createPasswordLeakAssessment(
      String projectID,
      byte[] lookupHashPrefix,
      byte[] encryptedUserCredentialsHash)
      throws IOException {
    try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {

      // Set the hashprefix and credentials hash.
      // Setting this will trigger the Password leak protection.
      PrivatePasswordLeakVerification passwordLeakVerification =
          PrivatePasswordLeakVerification.newBuilder()
              .setLookupHashPrefix(ByteString.copyFrom(lookupHashPrefix))
              .setEncryptedUserCredentialsHash(ByteString.copyFrom(encryptedUserCredentialsHash))
              .build();

      // Build the assessment request.
      CreateAssessmentRequest createAssessmentRequest =
          CreateAssessmentRequest.newBuilder()
              .setParent(String.format("projects/%s", projectID))
              .setAssessment(
                  Assessment.newBuilder()
                      // Set request for Password leak verification.
                      .setPrivatePasswordLeakVerification(passwordLeakVerification)
                      .build())
              .build();

      // Send the create assessment request.
      Assessment response = client.createAssessment(createAssessmentRequest);

      // Get the reCAPTCHA Enterprise score.
      float recaptchaScore = response.getRiskAnalysis().getScore();
      System.out.println("The reCAPTCHA score is: " + recaptchaScore);

      // Get the assessment name (id). Use this to annotate the assessment.
      String assessmentName = response.getName();
      System.out.println(
          "Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1));

      return response.getPrivatePasswordLeakVerification();
    }
  }
}

Container Docker

Per verificare se le credenziali sono state compromesse, invia in modo sicuro la coppia di credenziali nome utente e password al container utilizzando una connessione localhost o configurando HTTPS sul container. Il container cripta quindi queste credenziali prima di effettuare una richiesta API a reCAPTCHA e verifica il risultato ri-criptato localmente.

Per inviare richieste al container Docker, completa i seguenti passaggi:

  1. Configura Docker.
  2. Prepara un ambiente per il container Docker.
  3. Crea ed esegui il container.
  4. Invia richieste HTTP al container.
  5. Interpreta il verdetto e intervieni.

Preparati a eseguire il container Docker

  1. Scegli una strategia di autenticazione.

    Il container supporta l'impostazione delle credenziali predefinite dell'applicazione o può accettare una chiave API per l'autenticazione.

  2. Configura il contenitore PLD in modo che venga eseguito con HTTPS o in modalità demo solo localhost.

    Poiché il container accetta credenziali sensibili dell'utente finale (nomi utente e password), deve essere eseguito con HTTPS o in modalità demo solo localhost. Per indicazioni sulla configurazione HTTPS, consulta README su GitHub.

I seguenti passaggi utilizzano l'autenticazione con chiave API ed eseguono il client in modalità demo solo localhost.

Crea ed esegui il container Docker

  1. Clona il repository:

    git clone github.com/GoogleCloudPlatform/reCAPTCHA-PLD
    
  2. Crea il container:

    docker build . -t pld-local
    
  3. Avvia il container:

    docker run --network host \
    -e RECAPTCHA_PROJECT_ID=PROJECT_ID \
    -e GOOGLE_CLOUD_API_KEY=API_KEY \
    pld-local
    

Il container viene avviato e inizia a gestire le richieste sulla porta 8080 di localhost.

Inviare richieste localhost

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • LEAKED_USERNAME: il nome utente della coppia di credenziali compromesse.
  • LEAKED_PASSWORD: la password della coppia di credenziali compromesse.

Metodo HTTP e URL:

POST http://localhost:8080/createAssessment/

Corpo JSON della richiesta:

{
    "username":"LEAKED_USERNAME",
    "password":"LEAKED_PASSWORD"
}

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

curl -X POST \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"http://localhost:8080/createAssessment/"

PowerShell

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$headers = @{  }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "http://localhost:8080/createAssessment/" | Select-Object -Expand Content

Dovresti ricevere una risposta JSON simile alla seguente:


  { "leakedStatus":"LEAKED" }


 OR


  { "leakedStatus":"NO_STATUS" }

Interpreta il verdetto e intervieni

La risposta alla valutazione mostra se le credenziali sono state compromesse e ti fornisce informazioni che puoi utilizzare per intraprendere le azioni appropriate per proteggere i tuoi utenti.

La seguente tabella elenca le azioni consigliate che puoi intraprendere quando viene rilevata una password compromessa:

Password divulgata rilevata Azioni per proteggere l'utente
Durante l'accesso
  • Rifiuta e richiedi al cliente di scegliere una password diversa e attiva una verifica MFA, se possibile.
  • Ricorda all'utente di utilizzare password univoche per tutti gli account.
  • Richiedi password efficaci sul tuo sito.
  • Chiedi all'utente di attivare l'autenticazione a più fattori (MFA) se non la utilizza.
Durante la creazione dell'account o il ripristino della password
  • Richiedi all'utente di cambiare la password.
  • Attiva un flusso di autenticazione a più fattori (MFA).

Se non utilizzi già un provider MFA sul tuo sito, puoi utilizzare la funzionalità MFA di reCAPTCHA.

Passaggi successivi