|
| 1 | +/* |
| 2 | + * Copyright 2022 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package passwordleak; |
| 18 | + |
| 19 | +// [START recaptcha_enterprise_password_leak_verification] |
| 20 | + |
| 21 | +import com.google.cloud.recaptcha.passwordcheck.PasswordCheckResult; |
| 22 | +import com.google.cloud.recaptcha.passwordcheck.PasswordCheckVerification; |
| 23 | +import com.google.cloud.recaptcha.passwordcheck.PasswordCheckVerifier; |
| 24 | +import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient; |
| 25 | +import com.google.protobuf.ByteString; |
| 26 | +import com.google.recaptchaenterprise.v1.Assessment; |
| 27 | +import com.google.recaptchaenterprise.v1.CreateAssessmentRequest; |
| 28 | +import com.google.recaptchaenterprise.v1.Event; |
| 29 | +import com.google.recaptchaenterprise.v1.PrivatePasswordLeakVerification; |
| 30 | +import com.google.recaptchaenterprise.v1.TokenProperties; |
| 31 | +import java.io.IOException; |
| 32 | +import java.util.List; |
| 33 | +import java.util.concurrent.ExecutionException; |
| 34 | +import java.util.stream.Collectors; |
| 35 | + |
| 36 | +public class CreatePasswordLeakAssessment { |
| 37 | + |
| 38 | + public static void main(String[] args) |
| 39 | + throws IOException, ExecutionException, InterruptedException { |
| 40 | + // TODO(developer): Replace these variables before running the sample. |
| 41 | + // GCloud Project ID. |
| 42 | + String projectID = "project-id"; |
| 43 | + |
| 44 | + // Site key obtained by registering a domain/app to use recaptcha Enterprise. |
| 45 | + String recaptchaSiteKey = "recaptcha-site-key"; |
| 46 | + |
| 47 | + // The token obtained from the client on passing the recaptchaSiteKey. |
| 48 | + // To get the token, integrate the recaptchaSiteKey with frontend. See, |
| 49 | + // https://cloud.google.com/recaptcha-enterprise/docs/instrument-web-pages#frontend_integration_score |
| 50 | + String token = "recaptcha-token"; |
| 51 | + |
| 52 | + // Action name corresponding to the token. |
| 53 | + String recaptchaAction = "recaptcha-action"; |
| 54 | + |
| 55 | + checkPasswordLeak(projectID, recaptchaSiteKey, token, recaptchaAction); |
| 56 | + } |
| 57 | + |
| 58 | + /* |
| 59 | + * Detect password leaks and breached credentials to prevent account takeovers (ATOs) |
| 60 | + * and credential stuffing attacks. |
| 61 | + * For more information, see: https://cloud.google.com/recaptcha-enterprise/docs/getting-started |
| 62 | + * and https://security.googleblog.com/2019/02/protect-your-accounts-from-data.html |
| 63 | +
|
| 64 | + * Steps: |
| 65 | + * 1. Use the 'createVerification' method to hash and Encrypt the hashed username and password. |
| 66 | + * 2. Send the hash prefix (2-byte) and the encrypted credentials to create the assessment. |
| 67 | + * (Hash prefix is used to partition the database.) |
| 68 | + * 3. Password leak assessment returns a database whose prefix matches the sent hash prefix. |
| 69 | + * Create Assessment also sends back re-encrypted credentials. |
| 70 | + * 4. The re-encrypted credential is then locally verified to see if there is a |
| 71 | + * match in the database. |
| 72 | + * |
| 73 | + * To perform hashing, encryption and verification (steps 1, 2 and 4), |
| 74 | + * reCAPTCHA Enterprise provides a helper library in Java. |
| 75 | + * See, https://github.com/GoogleCloudPlatform/java-recaptcha-password-check-helpers |
| 76 | +
|
| 77 | + * If you want to extend this behavior to your own implementation/ languages, |
| 78 | + * make sure to perform the following steps: |
| 79 | + * 1. Hash the credentials (First 2 bytes of the result is the 'lookupHashPrefix') |
| 80 | + * 2. Encrypt the hash (result = 'encryptedUserCredentialsHash') |
| 81 | + * 3. Get back the PasswordLeak information from reCAPTCHA Enterprise Create Assessment. |
| 82 | + * 4. Decrypt the obtained 'credentials.getReencryptedUserCredentialsHash()' |
| 83 | + * with the same key you used for encryption. |
| 84 | + * 5. Check if the decrypted credentials are present in 'credentials.getEncryptedLeakMatchPrefixesList()'. |
| 85 | + * 6. If there is a match, that indicates a credential breach. |
| 86 | + */ |
| 87 | + public static void checkPasswordLeak( |
| 88 | + String projectID, String recaptchaSiteKey, String token, String recaptchaAction) |
| 89 | + throws ExecutionException, InterruptedException, IOException { |
| 90 | + // Set the username and password to be checked. |
| 91 | + String username = "username"; |
| 92 | + String password = "password123"; |
| 93 | + |
| 94 | + // Instantiate the java-password-leak-helper library to perform the cryptographic functions. |
| 95 | + PasswordCheckVerifier passwordLeak = new PasswordCheckVerifier(); |
| 96 | + |
| 97 | + // Create the request to obtain the hash prefix and encrypted credentials. |
| 98 | + PasswordCheckVerification verification = |
| 99 | + passwordLeak.createVerification(username, password).get(); |
| 100 | + |
| 101 | + byte[] lookupHashPrefix = verification.getLookupHashPrefix(); |
| 102 | + byte[] encryptedUserCredentialsHash = verification.getEncryptedLookupHash(); |
| 103 | + |
| 104 | + // Pass the credentials to the createPasswordLeakAssessment() to get back |
| 105 | + // the matching database entry for the hash prefix. |
| 106 | + PrivatePasswordLeakVerification credentials = |
| 107 | + createPasswordLeakAssessment( |
| 108 | + projectID, |
| 109 | + recaptchaSiteKey, |
| 110 | + token, |
| 111 | + recaptchaAction, |
| 112 | + lookupHashPrefix, |
| 113 | + encryptedUserCredentialsHash); |
| 114 | + |
| 115 | + // Convert to appropriate input format. |
| 116 | + List<byte[]> leakMatchPrefixes = |
| 117 | + credentials.getEncryptedLeakMatchPrefixesList().stream() |
| 118 | + .map(ByteString::toByteArray) |
| 119 | + .collect(Collectors.toList()); |
| 120 | + |
| 121 | + // Verify if the encrypted credentials are present in the obtained match list. |
| 122 | + PasswordCheckResult result = |
| 123 | + passwordLeak |
| 124 | + .verify( |
| 125 | + verification, |
| 126 | + credentials.getReencryptedUserCredentialsHash().toByteArray(), |
| 127 | + leakMatchPrefixes) |
| 128 | + .get(); |
| 129 | + |
| 130 | + // Check if the credential is leaked. |
| 131 | + boolean isLeaked = result.areCredentialsLeaked(); |
| 132 | + System.out.printf("Is Credential leaked: %s", isLeaked); |
| 133 | + } |
| 134 | + |
| 135 | + // Create a reCAPTCHA Enterprise assessment. |
| 136 | + // Returns: PrivatePasswordLeakVerification which contains |
| 137 | + // reencryptedUserCredentialsHash and credential breach database |
| 138 | + // whose prefix matches the lookupHashPrefix. |
| 139 | + private static PrivatePasswordLeakVerification createPasswordLeakAssessment( |
| 140 | + String projectID, |
| 141 | + String recaptchaSiteKey, |
| 142 | + String token, |
| 143 | + String recaptchaAction, |
| 144 | + byte[] lookupHashPrefix, |
| 145 | + byte[] encryptedUserCredentialsHash) |
| 146 | + throws IOException { |
| 147 | + try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) { |
| 148 | + |
| 149 | + // Set the properties of the event to be tracked. |
| 150 | + Event event = Event.newBuilder().setSiteKey(recaptchaSiteKey).setToken(token).build(); |
| 151 | + |
| 152 | + // Set the hashprefix and credentials hash. |
| 153 | + // Setting this will trigger the Password leak protection. |
| 154 | + PrivatePasswordLeakVerification passwordLeakVerification = |
| 155 | + PrivatePasswordLeakVerification.newBuilder() |
| 156 | + .setLookupHashPrefix(ByteString.copyFrom(lookupHashPrefix)) |
| 157 | + .setEncryptedUserCredentialsHash(ByteString.copyFrom(encryptedUserCredentialsHash)) |
| 158 | + .build(); |
| 159 | + |
| 160 | + // Build the assessment request. |
| 161 | + CreateAssessmentRequest createAssessmentRequest = |
| 162 | + CreateAssessmentRequest.newBuilder() |
| 163 | + .setParent(String.format("projects/%s", projectID)) |
| 164 | + .setAssessment( |
| 165 | + Assessment.newBuilder() |
| 166 | + .setEvent(event) |
| 167 | + // Set request for Password leak verification. |
| 168 | + .setPrivatePasswordLeakVerification(passwordLeakVerification) |
| 169 | + .build()) |
| 170 | + .build(); |
| 171 | + |
| 172 | + // Send the create assessment request. |
| 173 | + Assessment response = client.createAssessment(createAssessmentRequest); |
| 174 | + |
| 175 | + // Check validity and integrity of the response. |
| 176 | + if (!checkTokenIntegrity(response.getTokenProperties(), recaptchaAction)) { |
| 177 | + return passwordLeakVerification; |
| 178 | + } |
| 179 | + |
| 180 | + // Get the reCAPTCHA Enterprise score. |
| 181 | + float recaptchaScore = response.getRiskAnalysis().getScore(); |
| 182 | + System.out.println("The reCAPTCHA score is: " + recaptchaScore); |
| 183 | + |
| 184 | + // Get the assessment name (id). Use this to annotate the assessment. |
| 185 | + String assessmentName = response.getName(); |
| 186 | + System.out.println( |
| 187 | + "Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1)); |
| 188 | + |
| 189 | + return response.getPrivatePasswordLeakVerification(); |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + // Check for token validity and action integrity. |
| 194 | + private static boolean checkTokenIntegrity( |
| 195 | + TokenProperties tokenProperties, String recaptchaAction) { |
| 196 | + // Check if the token is valid. |
| 197 | + if (!tokenProperties.getValid()) { |
| 198 | + System.out.println( |
| 199 | + "The Password check call failed because the token was: " |
| 200 | + + tokenProperties.getInvalidReason().name()); |
| 201 | + return false; |
| 202 | + } |
| 203 | + |
| 204 | + // Check if the expected action was executed. |
| 205 | + if (!tokenProperties.getAction().equals(recaptchaAction)) { |
| 206 | + System.out.printf( |
| 207 | + "The action attribute in the reCAPTCHA tag '%s' does not match " |
| 208 | + + "the action '%s' you are expecting to score", |
| 209 | + tokenProperties.getAction(), recaptchaAction); |
| 210 | + return false; |
| 211 | + } |
| 212 | + return true; |
| 213 | + } |
| 214 | +} |
| 215 | +// [END recaptcha_enterprise_password_leak_verification] |
0 commit comments