    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *   http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 *
    017 */
    018
    019package org.apache.commons.net.util;
    020
    021import java.lang.reflect.InvocationTargetException;
    022import java.lang.reflect.Method;
    023
    024import javax.net.ssl.SSLSocket;
    025
    026/**
    027 * General utilities for SSLSocket.
    028 *
    029 * @since 3.4
    030 */
    031public class SSLSocketUtils {
    032    private SSLSocketUtils() {
    033        // Not instantiable
    034    }
    035
    036    /**
    037     * Enable the HTTPS endpoint identification algorithm on an SSLSocket.
    038     *
    039     * @param socket the SSL socket
    040     * @return {@code true} on success (this is only supported on Java 1.7+)
    041     */
    042    public static boolean enableEndpointNameVerification(final SSLSocket socket) {
    043        try {
    044            final Class<?> cls = Class.forName("javax.net.ssl.SSLParameters");
    045            final Method setEndpointIdentificationAlgorithm = cls
    046                .getDeclaredMethod("setEndpointIdentificationAlgorithm", String.class);
    047            final Method getSSLParameters = SSLSocket.class.getDeclaredMethod("getSSLParameters");
    048            final Method setSSLParameters = SSLSocket.class.getDeclaredMethod("setSSLParameters", cls);
    049            if (setEndpointIdentificationAlgorithm != null && getSSLParameters != null && setSSLParameters != null) {
    050                final Object sslParams = getSSLParameters.invoke(socket);
    051                if (sslParams != null) {
    052                    setEndpointIdentificationAlgorithm.invoke(sslParams, "HTTPS");
    053                    setSSLParameters.invoke(socket, sslParams);
    054                    return true;
    055                }
    056            }
    057        } catch (final SecurityException | ClassNotFoundException | NoSuchMethodException | IllegalArgumentException |
    058            IllegalAccessException | InvocationTargetException e) { // Ignored
    059        }
    060        return false;
    061    }
    062}