google-nomulus/java/google/registry/flows/TlsCredentials.java
jianglai 9e7c996081 Add fallback headers to GFE specific headers
Currently we exact the client certificate hash from header X-GFE-SSL-Certificate. This works because the proxy running on [] sends the request directly to the AFE via HttpOverRpc, bypassing the frontline GFE, which would strip away this header.

[]

After the proxy moves to GCP we can no longer use that header. Instead we should use X-SSL-Certificate, which does not get stripped by the GFE. In fact the open source build should never have contained X-GFE-SSL-Certificate because obviously external nomulus users have to go through the GFE to reach the registry app and that header would never have survived.

Without changing how the [] proxy works, this CL makes the registry first try to extract the hash from X-GFE-SSL-Certificate, and fallback to X-SSL-Certificate if necessary. This allows the current setup to continue to work, while the new proxy is being tested.

This should not open us up to attacks because even if an attacker uses a proxy that uses X-SSL-Certificate, it still needs to pass OAuth in order to talk to /_dr/epp.

Similarly, we use X-Requested-Servername-SNI as fallback to X-GFE-Requested-Servername-SNI. This can be eliminated altogether when the [] proxy is retired, because the only reason we check if the client request is SNI enabled (by checking the existence of that header) is because the GFE only requests client certificate when SNI is enabled. The GCP proxy does not have that limitation, and also will be only serving one certificate with all SAN listed in it.

Some formatting change is also introduced by the formatter. They seem to be better conforming to the style guide, so I left them there.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=165378083
2017-08-29 16:21:00 -04:00

221 lines
8.3 KiB
Java

// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.flows;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Strings.isNullOrEmpty;
import static google.registry.request.RequestParameters.extractOptionalHeader;
import static google.registry.request.RequestParameters.extractRequiredHeader;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.net.HostAndPort;
import com.google.common.net.InetAddresses;
import dagger.Module;
import dagger.Provides;
import google.registry.flows.EppException.AuthenticationErrorException;
import google.registry.model.registrar.Registrar;
import google.registry.request.Header;
import google.registry.util.CidrAddressBlock;
import google.registry.util.FormattingLogger;
import java.net.InetAddress;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
/**
* Container and validation for TLS certificate and ip-whitelisting.
*
* <p>Credentials are based on the following headers:
*
* <dl>
* <dt>X-SSL-Certificate
* <dd>This field should contain a base64 encoded digest of the client's TLS certificate. It is
* validated during an EPP login command against a known good value that is transmitted out of
* band.
* <dt>X-Forwarded-For
* <dd>This field should contain the host and port of the connecting client. It is validated
* during an EPP login command against an IP whitelist that is transmitted out of band.
* <dt>X-GFE-Requested-Servername-SNI
* <dd>This field should contain the servername that the client requested during the TLS
* handshake. It is unused, but expected to be present in the GFE-proxied configuration.
* </dl>
*/
public class TlsCredentials implements TransportCredentials {
private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();
private final String clientCertificateHash;
private final String sni;
private final InetAddress clientInetAddr;
@Inject
@VisibleForTesting
public TlsCredentials(
@Header("X-SSL-Certificate") String clientCertificateHash,
@Header("X-Forwarded-For") Optional<String> clientAddress,
@Header("X-Requested-Servername-SNI") String sni) {
this.clientCertificateHash = clientCertificateHash;
this.clientInetAddr = clientAddress.isPresent() ? parseInetAddress(clientAddress.get()) : null;
this.sni = sni;
}
static InetAddress parseInetAddress(String asciiAddr) {
try {
return InetAddresses.forString(HostAndPort.fromString(asciiAddr).getHost());
} catch (IllegalArgumentException e) {
return null;
}
}
/** Returns {@code true} if frontend passed us the requested server name. */
boolean hasSni() {
return !isNullOrEmpty(sni);
}
@Override
public void validate(Registrar registrar, String password) throws AuthenticationErrorException {
validateIp(registrar);
validateCertificate(registrar);
validatePassword(registrar, password);
}
/**
* Verifies {@link #clientInetAddr} is in CIDR whitelist associated with {@code registrar}.
*
* @throws BadRegistrarIpAddressException If IP address is not in the whitelist provided
*/
private void validateIp(Registrar registrar) throws AuthenticationErrorException {
ImmutableList<CidrAddressBlock> ipWhitelist = registrar.getIpAddressWhitelist();
if (ipWhitelist.isEmpty()) {
logger.infofmt(
"Skipping IP whitelist check because %s doesn't have an IP whitelist",
registrar.getClientId());
return;
}
for (CidrAddressBlock cidrAddressBlock : ipWhitelist) {
if (cidrAddressBlock.contains(clientInetAddr)) {
// IP address is in whitelist; return early.
return;
}
}
logger.infofmt(
"Authentication error: IP address %s is not whitelisted for registrar %s.",
clientInetAddr, registrar.getClientId());
throw new BadRegistrarIpAddressException();
}
/**
* Verifies client SSL certificate is permitted to issue commands as {@code registrar}.
*
* @throws NoSniException if frontend didn't send host or certificate hash headers
* @throws MissingRegistrarCertificateException if frontend didn't send certificate hash header
* @throws BadRegistrarCertificateException if registrar requires certificate and it didn't match
*/
private void validateCertificate(Registrar registrar) throws AuthenticationErrorException {
if (isNullOrEmpty(registrar.getClientCertificateHash())
&& isNullOrEmpty(registrar.getFailoverClientCertificateHash())) {
logger.infofmt(
"Skipping SSL certificate check because %s doesn't have any certificate hashes on file",
registrar.getClientId());
return;
}
if (isNullOrEmpty(clientCertificateHash)) {
// If there's no SNI header that's probably why we don't have a cert, so send a specific
// message. Otherwise, send a missing certificate message.
if (!hasSni()) {
throw new NoSniException();
}
logger.info("Request did not include X-SSL-Certificate");
throw new MissingRegistrarCertificateException();
}
if (!clientCertificateHash.equals(registrar.getClientCertificateHash())
&& !clientCertificateHash.equals(registrar.getFailoverClientCertificateHash())) {
logger.warningfmt(
"bad certificate hash (%s) for %s, wanted either %s or %s",
clientCertificateHash,
registrar.getClientId(),
registrar.getClientCertificateHash(),
registrar.getFailoverClientCertificateHash());
throw new BadRegistrarCertificateException();
}
}
private void validatePassword(Registrar registrar, String password)
throws BadRegistrarPasswordException {
if (!registrar.testPassword(password)) {
throw new BadRegistrarPasswordException();
}
}
@Override
public String toString() {
return toStringHelper(getClass())
.add("clientCertificateHash", clientCertificateHash)
.add("clientAddress", clientInetAddr)
.add("sni", sni)
.toString();
}
/** Registrar certificate does not match stored certificate. */
public static class BadRegistrarCertificateException extends AuthenticationErrorException {
public BadRegistrarCertificateException() {
super("Registrar certificate does not match stored certificate");
}
}
/** Registrar certificate not present. */
public static class MissingRegistrarCertificateException extends AuthenticationErrorException {
public MissingRegistrarCertificateException() {
super("Registrar certificate not present");
}
}
/** SNI header is required. */
public static class NoSniException extends AuthenticationErrorException {
public NoSniException() {
super("SNI header is required");
}
}
/** Registrar IP address is not in stored whitelist. */
public static class BadRegistrarIpAddressException extends AuthenticationErrorException {
public BadRegistrarIpAddressException() {
super("Registrar IP address is not in stored whitelist");
}
}
/** Dagger module for the EPP TLS endpoint. */
@Module
public static final class EppTlsModule {
@Provides
@Header("X-SSL-Certificate")
static String provideClientCertificateHash(HttpServletRequest req) {
return extractRequiredHeader(req, "X-SSL-Certificate");
}
@Provides
@Header("X-Forwarded-For")
static Optional<String> provideForwardedFor(HttpServletRequest req) {
return extractOptionalHeader(req, "X-Forwarded-For");
}
@Provides
@Header("X-Requested-Servername-SNI")
static String provideRequestedServername(HttpServletRequest req) {
return extractRequiredHeader(req, "X-Requested-Servername-SNI");
}
}
}