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 * @since 3.4 029 */ 030public class SSLSocketUtils { 031 private SSLSocketUtils() { 032 // Not instantiable 033 } 034 035 /** 036 * Enable the HTTPS endpoint identification algorithm on an SSLSocket. 037 * @param socket the SSL socket 038 * @return {@code true} on success (this is only supported on Java 1.7+) 039 */ 040 public static boolean enableEndpointNameVerification(final SSLSocket socket) { 041 try { 042 final Class<?> cls = Class.forName("javax.net.ssl.SSLParameters"); 043 final Method setEndpointIdentificationAlgorithm = cls 044 .getDeclaredMethod("setEndpointIdentificationAlgorithm", String.class); 045 final Method getSSLParameters = SSLSocket.class.getDeclaredMethod("getSSLParameters"); 046 final Method setSSLParameters = SSLSocket.class.getDeclaredMethod("setSSLParameters", cls); 047 if (setEndpointIdentificationAlgorithm != null && getSSLParameters != null && setSSLParameters != null) { 048 final Object sslParams = getSSLParameters.invoke(socket); 049 if (sslParams != null) { 050 setEndpointIdentificationAlgorithm.invoke(sslParams, "HTTPS"); 051 setSSLParameters.invoke(socket, sslParams); 052 return true; 053 } 054 } 055 } catch (final SecurityException e) { // Ignored 056 } catch (final ClassNotFoundException e) { // Ignored 057 } catch (final NoSuchMethodException e) { // Ignored 058 } catch (final IllegalArgumentException e) { // Ignored 059 } catch (final IllegalAccessException e) { // Ignored 060 } catch (final InvocationTargetException e) { // Ignored 061 } 062 return false; 063 } 064}