directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From plusplusjia...@apache.org
Subject [2/3] directory-kerby git commit: DIRKRB-672 Embed a web server in KDC to upgrade Kerby KDC.
Date Fri, 22 Dec 2017 01:06:52 GMT
http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-common/src/main/java/org/apache/kerby/has/common/ssl/SSLHostnameVerifier.java
----------------------------------------------------------------------
diff --git a/has-project/has-common/src/main/java/org/apache/kerby/has/common/ssl/SSLHostnameVerifier.java b/has-project/has-common/src/main/java/org/apache/kerby/has/common/ssl/SSLHostnameVerifier.java
new file mode 100644
index 0000000..b474d7b
--- /dev/null
+++ b/has-project/has-common/src/main/java/org/apache/kerby/has/common/ssl/SSLHostnameVerifier.java
@@ -0,0 +1,615 @@
+/*
+ * $HeadURL$
+ * $Revision$
+ * $Date$
+ *
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.kerby.has.common.ssl;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.kerby.has.common.util.StringUtils;
+
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSocket;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.TreeSet;
+
+/**
+ * Borrow the class from Apache Hadoop
+ */
+
+/**
+ ************************************************************************
+ * Copied from the not-yet-commons-ssl project at
+ * http://juliusdavies.ca/commons-ssl/
+ * This project is not yet in Apache, but it is Apache 2.0 licensed.
+ ************************************************************************
+ * Interface for checking if a hostname matches the names stored inside the
+ * server's X.509 certificate.  Correctly implements
+ * javax.net.ssl.HostnameVerifier, but that interface is not recommended.
+ * Instead we added several check() methods that take SSLSocket,
+ * or X509Certificate, or ultimately (they all end up calling this one),
+ * String.  (It's easier to supply JUnit with Strings instead of mock
+ * SSLSession objects!)
+ * </p><p>Our check() methods throw exceptions if the name is
+ * invalid, whereas javax.net.ssl.HostnameVerifier just returns true/false.
+ * <p/>
+ * We provide the HostnameVerifier.DEFAULT, HostnameVerifier.STRICT, and
+ * HostnameVerifier.ALLOW_ALL implementations.  We also provide the more
+ * specialized HostnameVerifier.DEFAULT_AND_LOCALHOST, as well as
+ * HostnameVerifier.STRICT_IE6.  But feel free to define your own
+ * implementations!
+ * <p/>
+ * Inspired by Sebastian Hauer's original StrictSSLProtocolSocketFactory in the
+ * HttpClient "contrib" repository.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Evolving
+@SuppressWarnings("PMD")
+public interface SSLHostnameVerifier extends javax.net.ssl.HostnameVerifier {
+
+    @Override
+    boolean verify(String host, SSLSession session);
+
+    void check(String host, SSLSocket ssl) throws IOException;
+
+    void check(String host, X509Certificate cert) throws SSLException;
+
+    void check(String host, String[] cns, String[] subjectAlts)
+        throws SSLException;
+
+    void check(String[] hosts, SSLSocket ssl) throws IOException;
+
+    void check(String[] hosts, X509Certificate cert) throws SSLException;
+
+
+    /**
+     * Checks to see if the supplied hostname matches any of the supplied CNs
+     * or "DNS" Subject-Alts.  Most implementations only look at the first CN,
+     * and ignore any additional CNs.  Most implementations do look at all of
+     * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
+     * according to RFC 2818.
+     *
+     * @param cns         CN fields, in order, as extracted from the X.509
+     *                    certificate.
+     * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
+     *                    from the X.509 certificate.
+     * @param hosts       The array of hostnames to verify.
+     * @throws SSLException If verification failed.
+     */
+    void check(String[] hosts, String[] cns, String[] subjectAlts)
+        throws SSLException;
+
+
+    /**
+     * The DEFAULT HostnameVerifier works the same way as Curl and Firefox.
+     * <p/>
+     * The hostname must match either the first CN, or any of the subject-alts.
+     * A wildcard can occur in the CN, and in any of the subject-alts.
+     * <p/>
+     * The only difference between DEFAULT and STRICT is that a wildcard (such
+     * as "*.foo.com") with DEFAULT matches all subdomains, including
+     * "a.b.foo.com".
+     */
+    SSLHostnameVerifier DEFAULT =
+        new AbstractVerifier() {
+            @Override
+            public final void check(final String[] hosts, final String[] cns,
+                                    final String[] subjectAlts)
+                throws SSLException {
+                check(hosts, cns, subjectAlts, false, false);
+            }
+
+            @Override
+            public final String toString() {
+                return "DEFAULT";
+            }
+        };
+
+
+    /**
+     * The DEFAULT_AND_LOCALHOST HostnameVerifier works like the DEFAULT
+     * one with one additional relaxation:  a host of "localhost",
+     * "localhost.localdomain", "127.0.0.1", "::1" will always pass, no matter
+     * what is in the server's certificate.
+     */
+    SSLHostnameVerifier DEFAULT_AND_LOCALHOST =
+        new AbstractVerifier() {
+            @Override
+            public final void check(final String[] hosts, final String[] cns,
+                                    final String[] subjectAlts)
+                throws SSLException {
+                if (isLocalhost(hosts[0])) {
+                    return;
+                }
+                check(hosts, cns, subjectAlts, false, false);
+            }
+
+            @Override
+            public final String toString() {
+                return "DEFAULT_AND_LOCALHOST";
+            }
+        };
+
+    /**
+     * The STRICT HostnameVerifier works the same way as java.net.URL in Sun
+     * Java 1.4, Sun Java 5, Sun Java 6.  It's also pretty close to IE6.
+     * This implementation appears to be compliant with RFC 2818 for dealing
+     * with wildcards.
+     * <p/>
+     * The hostname must match either the first CN, or any of the subject-alts.
+     * A wildcard can occur in the CN, and in any of the subject-alts.  The
+     * one divergence from IE6 is how we only check the first CN.  IE6 allows
+     * a match against any of the CNs present.  We decided to follow in
+     * Sun Java 1.4's footsteps and only check the first CN.
+     * <p/>
+     * A wildcard such as "*.foo.com" matches only subdomains in the same
+     * level, for example "a.foo.com".  It does not match deeper subdomains
+     * such as "a.b.foo.com".
+     */
+    SSLHostnameVerifier STRICT =
+        new AbstractVerifier() {
+            @Override
+            public final void check(final String[] host, final String[] cns,
+                                    final String[] subjectAlts)
+                throws SSLException {
+                check(host, cns, subjectAlts, false, true);
+            }
+
+            @Override
+            public final String toString() {
+                return "STRICT";
+            }
+        };
+
+    /**
+     * The STRICT_IE6 HostnameVerifier works just like the STRICT one with one
+     * minor variation:  the hostname can match against any of the CN's in the
+     * server's certificate, not just the first one.  This behaviour is
+     * identical to IE6's behaviour.
+     */
+    SSLHostnameVerifier STRICT_IE6 =
+        new AbstractVerifier() {
+            @Override
+            public final void check(final String[] host, final String[] cns,
+                                    final String[] subjectAlts)
+                throws SSLException {
+                check(host, cns, subjectAlts, true, true);
+            }
+
+            @Override
+            public final String toString() {
+                return "STRICT_IE6";
+            }
+        };
+
+    /**
+     * The ALLOW_ALL HostnameVerifier essentially turns hostname verification
+     * off.  This implementation is a no-op, and never throws the SSLException.
+     */
+    SSLHostnameVerifier ALLOW_ALL =
+        new AbstractVerifier() {
+            @Override
+            public final void check(final String[] host, final String[] cns,
+                                    final String[] subjectAlts) {
+                // Allow everything - so never blowup.
+            }
+
+            @Override
+            public final String toString() {
+                return "ALLOW_ALL";
+            }
+        };
+
+    abstract class AbstractVerifier implements SSLHostnameVerifier {
+
+        /**
+         * This contains a list of 2nd-level domains that aren't allowed to
+         * have wildcards when combined with country-codes.
+         * For example: [*.co.uk].
+         * <p/>
+         * The [*.co.uk] problem is an interesting one.  Should we just hope
+         * that CA's would never foolishly allow such a certificate to happen?
+         * Looks like we're the only implementation guarding against this.
+         * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
+         */
+        private static final String[] BAD_COUNTRY_2LDS =
+            {"ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
+                "lg", "ne", "net", "or", "org"};
+
+        private static final String[] LOCALHOSTS = {"::1", "127.0.0.1",
+            "localhost",
+            "localhost.localdomain"};
+
+
+        static {
+            // Just in case developer forgot to manually sort the array.  :-)
+            Arrays.sort(BAD_COUNTRY_2LDS);
+            Arrays.sort(LOCALHOSTS);
+        }
+
+        protected AbstractVerifier() {
+        }
+
+        /**
+         * The javax.net.ssl.HostnameVerifier contract.
+         *
+         * @param host    'hostname' we used to create our socket
+         * @param session SSLSession with the remote server
+         * @return true if the host matched the one in the certificate.
+         */
+        @Override
+        public boolean verify(String host, SSLSession session) {
+            try {
+                Certificate[] certs = session.getPeerCertificates();
+                X509Certificate x509 = (X509Certificate) certs[0];
+                check(new String[]{host}, x509);
+                return true;
+            } catch (SSLException e) {
+                return false;
+            }
+        }
+
+        @Override
+        public void check(String host, SSLSocket ssl) throws IOException {
+            check(new String[]{host}, ssl);
+        }
+
+        @Override
+        public void check(String host, X509Certificate cert)
+            throws SSLException {
+            check(new String[]{host}, cert);
+        }
+
+        @Override
+        public void check(String host, String[] cns, String[] subjectAlts)
+            throws SSLException {
+            check(new String[]{host}, cns, subjectAlts);
+        }
+
+        @Override
+        public void check(String[] host, SSLSocket ssl)
+            throws IOException {
+            if (host == null) {
+                throw new NullPointerException("host to verify is null");
+            }
+
+            SSLSession session = ssl.getSession();
+            if (session == null) {
+                // In our experience this only happens under IBM 1.4.x when
+                // spurious (unrelated) certificates show up in the server'
+                // chain.  Hopefully this will unearth the real problem:
+                InputStream in = ssl.getInputStream();
+                in.available();
+                /*
+                  If you're looking at the 2 lines of code above because
+                  you're running into a problem, you probably have two
+                  options:
+
+                    #1.  Clean up the certificate chain that your server
+                         is presenting (e.g. edit "/etc/apache2/server.crt"
+                         or wherever it is your server's certificate chain
+                         is defined).
+
+                                               OR
+
+                    #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
+                          to a non-IBM JVM.
+                */
+
+                // If ssl.getInputStream().available() didn't cause an
+                // exception, maybe at least now the session is available?
+                session = ssl.getSession();
+                if (session == null) {
+                    // If it's still null, probably a startHandshake() will
+                    // unearth the real problem.
+                    ssl.startHandshake();
+
+                    // Okay, if we still haven't managed to cause an exception,
+                    // might as well go for the NPE.  Or maybe we're okay now?
+                    session = ssl.getSession();
+                }
+            }
+            Certificate[] certs;
+            try {
+                certs = session.getPeerCertificates();
+            } catch (SSLPeerUnverifiedException spue) {
+                InputStream in = ssl.getInputStream();
+                in.available();
+                // Didn't trigger anything interesting?  Okay, just throw
+                // original.
+                throw spue;
+            }
+            X509Certificate x509 = (X509Certificate) certs[0];
+            check(host, x509);
+        }
+
+        @Override
+        public void check(String[] host, X509Certificate cert)
+            throws SSLException {
+            String[] cns = Certificates.getCNs(cert);
+            String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
+            check(host, cns, subjectAlts);
+        }
+
+        public void check(final String[] hosts, final String[] cns,
+                          final String[] subjectAlts, final boolean ie6,
+                          final boolean strictWithSubDomains)
+            throws SSLException {
+            // Build up lists of allowed hosts For logging/debugging purposes.
+            StringBuffer buf = new StringBuffer(32);
+            buf.append('<');
+            for (int i = 0; i < hosts.length; i++) {
+                String h = hosts[i];
+                h = h != null ? StringUtils.toLowerCase(h.trim()) : "";
+                hosts[i] = h;
+                if (i > 0) {
+                    buf.append('/');
+                }
+                buf.append(h);
+            }
+            buf.append('>');
+            String hostnames = buf.toString();
+            // Build the list of names we're going to check.  Our DEFAULT and
+            // STRICT implementations of the HostnameVerifier only use the
+            // first CN provided.  All other CNs are ignored.
+            // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
+            final Set<String> names = new TreeSet<String>();
+            if (cns != null && cns.length > 0 && cns[0] != null) {
+                names.add(cns[0]);
+                if (ie6) {
+                    for (int i = 1; i < cns.length; i++) {
+                        names.add(cns[i]);
+                    }
+                }
+            }
+            if (subjectAlts != null) {
+                for (int i = 0; i < subjectAlts.length; i++) {
+                    if (subjectAlts[i] != null) {
+                        names.add(subjectAlts[i]);
+                    }
+                }
+            }
+            if (names.isEmpty()) {
+                String msg = "Certificate for " + hosts[0] + " doesn't contain CN or DNS subjectAlt";
+                throw new SSLException(msg);
+            }
+
+            // StringBuffer for building the error message.
+            buf = new StringBuffer();
+
+            boolean match = false;
+            out:
+            for (Iterator<String> it = names.iterator(); it.hasNext();) {
+                // Don't trim the CN, though!
+                final String cn = StringUtils.toLowerCase(it.next());
+                // Store CN in StringBuffer in case we need to report an error.
+                buf.append(" <");
+                buf.append(cn);
+                buf.append('>');
+                if (it.hasNext()) {
+                    buf.append(" OR");
+                }
+
+                // The CN better have at least two dots if it wants wildcard
+                // action.  It also can't be [*.co.uk] or [*.co.jp] or
+                // [*.org.uk], etc...
+                boolean doWildcard = cn.startsWith("*.")
+                    && cn.lastIndexOf('.') >= 0
+                    && !isIP4Address(cn)
+                    && acceptableCountryWildcard(cn);
+
+                for (int i = 0; i < hosts.length; i++) {
+                    final String hostName =
+                        StringUtils.toLowerCase(hosts[i].trim());
+                    if (doWildcard) {
+                        match = hostName.endsWith(cn.substring(1));
+                        if (match && strictWithSubDomains) {
+                            // If we're in strict mode, then [*.foo.com] is not
+                            // allowed to match [a.b.foo.com]
+                            match = countDots(hostName) == countDots(cn);
+                        }
+                    } else {
+                        match = hostName.equals(cn);
+                    }
+                    if (match) {
+                        break out;
+                    }
+                }
+            }
+            if (!match) {
+                throw new SSLException("hostname in certificate didn't match: " + hostnames + " !=" + buf);
+            }
+        }
+
+        public static boolean isIP4Address(final String cn) {
+            boolean isIP4 = true;
+            String tld = cn;
+            int x = cn.lastIndexOf('.');
+            // We only bother analyzing the characters after the final dot
+            // in the name.
+            if (x >= 0 && x + 1 < cn.length()) {
+                tld = cn.substring(x + 1);
+            }
+            for (int i = 0; i < tld.length(); i++) {
+                if (!Character.isDigit(tld.charAt(0))) {
+                    isIP4 = false;
+                    break;
+                }
+            }
+            return isIP4;
+        }
+
+        public static boolean acceptableCountryWildcard(final String cn) {
+            int cnLen = cn.length();
+            if (cnLen >= 7 && cnLen <= 9) {
+                // Look for the '.' in the 3rd-last position:
+                if (cn.charAt(cnLen - 3) == '.') {
+                    // Trim off the [*.] and the [.XX].
+                    String s = cn.substring(2, cnLen - 3);
+                    // And test against the sorted array of bad 2lds:
+                    int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
+                    return x < 0;
+                }
+            }
+            return true;
+        }
+
+        public static boolean isLocalhost(String host) {
+            host = host != null ? StringUtils.toLowerCase(host.trim()) : "";
+            if (host.startsWith("::1")) {
+                int x = host.lastIndexOf('%');
+                if (x >= 0) {
+                    host = host.substring(0, x);
+                }
+            }
+            int x = Arrays.binarySearch(LOCALHOSTS, host);
+            return x >= 0;
+        }
+
+        /**
+         * Counts the number of dots "." in a string.
+         *
+         * @param s string to count dots from
+         * @return number of dots
+         */
+        public static int countDots(final String s) {
+            int count = 0;
+            for (int i = 0; i < s.length(); i++) {
+                if (s.charAt(i) == '.') {
+                    count++;
+                }
+            }
+            return count;
+        }
+    }
+
+    class Certificates {
+      public static String[] getCNs(X509Certificate cert) {
+        final List<String> cnList = new LinkedList<String>();
+        /*
+          Sebastian Hauer's original StrictSSLProtocolSocketFactory used
+          getName() and had the following comment:
+
+             Parses a X.500 distinguished name for the value of the
+             "Common Name" field.  This is done a bit sloppy right
+             now and should probably be done a bit more according to
+             <code>RFC 2253</code>.
+
+           I've noticed that toString() seems to do a better job than
+           getName() on these X500Principal objects, so I'm hoping that
+           addresses Sebastian's concern.
+
+           For example, getName() gives me this:
+           1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
+
+           whereas toString() gives me this:
+           EMAILADDRESS=juliusdavies@cucbc.com
+
+           Looks like toString() even works with non-ascii domain names!
+           I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
+          */
+        String subjectPrincipal = cert.getSubjectX500Principal().toString();
+        StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
+        while (st.hasMoreTokens()) {
+            String tok = st.nextToken();
+            int x = tok.indexOf("CN=");
+            if (x >= 0) {
+                cnList.add(tok.substring(x + 3));
+            }
+        }
+        if (!cnList.isEmpty()) {
+            String[] cns = new String[cnList.size()];
+            cnList.toArray(cns);
+            return cns;
+        } else {
+            return null;
+        }
+      }
+
+
+      /**
+       * Extracts the array of SubjectAlt DNS names from an X509Certificate.
+       * Returns null if there aren't any.
+       * <p/>
+       * Note:  Java doesn't appear able to extract international characters
+       * from the SubjectAlts.  It can only extract international characters
+       * from the CN field.
+       * <p/>
+       * (Or maybe the version of OpenSSL I'm using to test isn't storing the
+       * international characters correctly in the SubjectAlts?).
+       *
+       * @param cert X509Certificate
+       * @return Array of SubjectALT DNS names stored in the certificate.
+       */
+      public static String[] getDNSSubjectAlts(X509Certificate cert) {
+          final List<String> subjectAltList = new LinkedList<String>();
+          Collection<List<?>> c = null;
+          try {
+              c = cert.getSubjectAlternativeNames();
+          } catch (CertificateParsingException cpe) {
+              // Should probably log.debug() this?
+              cpe.printStackTrace();
+          }
+          if (c != null) {
+              Iterator<List<?>> it = c.iterator();
+              while (it.hasNext()) {
+                  List<?> list = it.next();
+                  int type = ((Integer) list.get(0)).intValue();
+                  // If type is 2, then we've got a dNSName
+                  if (type == 2) {
+                      String s = (String) list.get(1);
+                      subjectAltList.add(s);
+                  }
+              }
+          }
+          if (!subjectAltList.isEmpty()) {
+              String[] subjectAlts = new String[subjectAltList.size()];
+              subjectAltList.toArray(subjectAlts);
+              return subjectAlts;
+          } else {
+              return null;
+          }
+      }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/ConnectionConfigurator.java
----------------------------------------------------------------------
diff --git a/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/ConnectionConfigurator.java b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/ConnectionConfigurator.java
new file mode 100644
index 0000000..c913e59
--- /dev/null
+++ b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/ConnectionConfigurator.java
@@ -0,0 +1,39 @@
+/**
+ * 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. See accompanying LICENSE file.
+ */
+package org.apache.kerby.has.common.util;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+
+/**
+ * Borrow the class from Apache Hadoop
+ */
+
+/**
+ * Interface to configure  {@link HttpURLConnection} created by
+ * {@link org.apache.kerby.has.common.spnego.AuthenticatedURL} instances.
+ */
+public interface ConnectionConfigurator {
+
+  /**
+   * Configures the given {@link HttpURLConnection} instance.
+   *
+   * @param conn the {@link HttpURLConnection} instance to configure.
+   * @return the configured {@link HttpURLConnection} instance.
+   * 
+   * @throws IOException if an IO error occurred.
+   */
+  HttpURLConnection configure(HttpURLConnection conn) throws IOException;
+
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/HasUtil.java
----------------------------------------------------------------------
diff --git a/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/HasUtil.java b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/HasUtil.java
new file mode 100644
index 0000000..3ccd749
--- /dev/null
+++ b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/HasUtil.java
@@ -0,0 +1,81 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.kerby.has.common.util;
+
+import org.apache.kerby.has.common.HasConfig;
+import org.apache.kerby.has.common.HasException;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.PrintStream;
+
+public class HasUtil {
+
+    /**
+     * Get has configuration
+     * @param hasConfFile configuration directory
+     * @return has configuration
+     */
+    public static HasConfig getHasConfig(File hasConfFile) throws HasException {
+
+        if (hasConfFile.exists()) {
+            HasConfig hasConfig = new HasConfig();
+            try {
+                hasConfig.addIniConfig(hasConfFile);
+            } catch (IOException e) {
+                throw new HasException("Can not load the has configuration file "
+                    + hasConfFile.getAbsolutePath());
+            }
+            return hasConfig;
+        }
+
+        return null;
+    }
+
+    public static void setEnableConf(File hasConfFile, String value)
+            throws HasException, IOException {
+        String oldValue = getHasConfig(hasConfFile).getEnableConf();
+        if (oldValue == null) {
+            throw new HasException("Please set enable_conf in has-server.conf.");
+        }
+        if (oldValue.equals(value)) {
+            return;
+        }
+        try {
+            BufferedReader bf = new BufferedReader(new FileReader(hasConfFile));
+            StringBuilder sb = new StringBuilder();
+            String tempString;
+            while ((tempString = bf.readLine()) != null) {
+                if (tempString.trim().startsWith("enable_conf")) {
+                    tempString = tempString.replace(oldValue, value);
+                }
+                sb.append(tempString + "\n");
+            }
+            PrintStream ps = new PrintStream(new FileOutputStream(hasConfFile));
+            ps.print(sb.toString());
+            bf.close();
+        } catch (FileNotFoundException e) {
+            throw new HasException("Can not load the has configuration file "
+                    + hasConfFile.getAbsolutePath());
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/PlatformName.java
----------------------------------------------------------------------
diff --git a/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/PlatformName.java b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/PlatformName.java
new file mode 100644
index 0000000..8a2c961
--- /dev/null
+++ b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/PlatformName.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.kerby.has.common.util;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+
+/**
+ * Borrow the class from Apache Hadoop
+ */
+
+/**
+ * A helper class for getting build-info of the java-vm.
+ *
+ */
+@InterfaceAudience.LimitedPrivate({"HBase"})
+@InterfaceStability.Unstable
+public class PlatformName {
+  /**
+   * The complete platform 'name' to identify the platform as
+   * per the java-vm.
+   */
+  public static final String PLATFORM_NAME =
+      (System.getProperty("os.name").startsWith("Windows")
+      ? System.getenv("os") : System.getProperty("os.name"))
+      + "-" + System.getProperty("os.arch")
+      + "-" + System.getProperty("sun.arch.data.model");
+
+  /**
+   * The java vendor name used in this platform.
+   */
+  public static final String JAVA_VENDOR_NAME = System.getProperty("java.vendor");
+
+  /**
+   * A public static variable to indicate the current java vendor is
+   * IBM java or not.
+   */
+  public static final boolean IBM_JAVA = JAVA_VENDOR_NAME.contains("IBM");
+
+  public static void main(String[] args) {
+    System.out.println(PLATFORM_NAME);
+  }
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/StringUtils.java
----------------------------------------------------------------------
diff --git a/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/StringUtils.java b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/StringUtils.java
new file mode 100644
index 0000000..b9c323d
--- /dev/null
+++ b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/StringUtils.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.kerby.has.common.util;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+
+import java.util.Locale;
+
+/**
+ * General string utils
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Unstable
+public class StringUtils {
+
+  /**
+   * Converts all of the characters in this String to lower case with
+   * Locale.ENGLISH.
+   *
+   * @param str  string to be converted
+   * @return     the str, converted to lowercase.
+   */
+  public static String toLowerCase(String str) {
+    return str.toLowerCase(Locale.ENGLISH);
+  }
+
+  /**
+   * Converts all of the characters in this String to upper case with
+   * Locale.ENGLISH.
+   *
+   * @param str  string to be converted
+   * @return     the str, converted to uppercase.
+   */
+  public static String toUpperCase(String str) {
+    return str.toUpperCase(Locale.ENGLISH);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/URLConnectionFactory.java
----------------------------------------------------------------------
diff --git a/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/URLConnectionFactory.java b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/URLConnectionFactory.java
new file mode 100644
index 0000000..06a8822
--- /dev/null
+++ b/has-project/has-common/src/main/java/org/apache/kerby/has/common/util/URLConnectionFactory.java
@@ -0,0 +1,197 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.kerby.has.common.util;
+
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.kerby.has.common.HasConfig;
+import org.apache.kerby.has.common.HasException;
+import org.apache.kerby.has.common.spnego.AuthenticatedURL;
+import org.apache.kerby.has.common.spnego.AuthenticationException;
+import org.apache.kerby.has.common.spnego.KerberosHasAuthenticator;
+import org.apache.kerby.has.common.ssl.SSLFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLSocketFactory;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.security.GeneralSecurityException;
+
+/**
+ * Borrow the class from Apache Hadoop
+ */
+
+/**
+ * Utilities for handling URLs
+ */
+@InterfaceStability.Unstable
+public class URLConnectionFactory {
+  private static final Logger LOG = LoggerFactory
+      .getLogger(URLConnectionFactory.class);
+
+  /**
+   * Timeout for socket connects and reads
+   */
+   // 1 minute
+  public static final int DEFAULT_SOCKET_TIMEOUT = 60 * 1000;
+  private final ConnectionConfigurator connConfigurator;
+
+  private static final ConnectionConfigurator DEFAULT_TIMEOUT_CONN_CONFIGURATOR
+      = new ConnectionConfigurator() {
+        @Override
+        public HttpURLConnection configure(HttpURLConnection conn)
+            throws IOException {
+          URLConnectionFactory.setTimeouts(conn,
+                                           DEFAULT_SOCKET_TIMEOUT,
+                                           DEFAULT_SOCKET_TIMEOUT);
+          return conn;
+        }
+      };
+
+  /**
+   * The URLConnectionFactory that sets the default timeout and it only trusts
+   * Java's SSL certificates.
+   */
+  public static final URLConnectionFactory DEFAULT_SYSTEM_CONNECTION_FACTORY =
+      new URLConnectionFactory(DEFAULT_TIMEOUT_CONN_CONFIGURATOR);
+
+  /**
+   * Construct a new URLConnectionFactory based on the configuration. It will
+   * try to load SSL certificates when it is specified.
+   */
+  public static URLConnectionFactory newDefaultURLConnectionFactory(HasConfig conf) {
+    ConnectionConfigurator conn = null;
+    try {
+      conn = newSslConnConfigurator(DEFAULT_SOCKET_TIMEOUT, conf);
+    } catch (Exception e) {
+      LOG.debug(
+          "Cannot load customized ssl related configuration. Fallback to system-generic settings.",
+          e);
+      conn = DEFAULT_TIMEOUT_CONN_CONFIGURATOR;
+    }
+    return new URLConnectionFactory(conn);
+  }
+
+  URLConnectionFactory(ConnectionConfigurator connConfigurator) {
+    this.connConfigurator = connConfigurator;
+  }
+
+  /**
+   * Create a new ConnectionConfigurator for SSL connections
+   */
+  private static ConnectionConfigurator newSslConnConfigurator(
+      final int defaultTimeout, HasConfig conf)
+      throws IOException, GeneralSecurityException, HasException {
+    final SSLFactory factory;
+    final SSLSocketFactory sf;
+    final HostnameVerifier hv;
+    final int connectTimeout;
+    final int readTimeout;
+
+    factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
+    factory.init();
+    sf = factory.createSSLSocketFactory();
+    hv = factory.getHostnameVerifier();
+
+    connectTimeout = defaultTimeout;
+
+    readTimeout = defaultTimeout;
+
+    return new ConnectionConfigurator() {
+      @Override
+      public HttpURLConnection configure(HttpURLConnection conn)
+          throws IOException {
+        if (conn instanceof HttpsURLConnection) {
+          HttpsURLConnection c = (HttpsURLConnection) conn;
+          c.setSSLSocketFactory(sf);
+          c.setHostnameVerifier(hv);
+        }
+        URLConnectionFactory.setTimeouts(conn, connectTimeout, readTimeout);
+        return conn;
+      }
+    };
+  }
+
+  /**
+   * Opens a url with read and connect timeouts
+   *
+   * @param url
+   *          to open
+   * @return URLConnection
+   * @throws IOException
+   */
+  public URLConnection openConnection(URL url) throws IOException {
+    try {
+      return openConnection(url, false, null);
+    } catch (AuthenticationException e) {
+      // Unreachable
+      LOG.error("Open connection {} failed", url, e);
+      return null;
+    }
+  }
+
+  /**
+   * Opens a url with read and connect timeouts
+   *
+   * @param url
+   *          URL to open
+   * @param isSpnego
+   *          whether the url should be authenticated via SPNEGO
+   * @return URLConnection
+   * @throws IOException
+   * @throws AuthenticationException
+   */
+  public URLConnection openConnection(URL url, boolean isSpnego, HasConfig hasConfig)
+      throws IOException, AuthenticationException {
+    if (isSpnego && hasConfig != null) {
+      LOG.debug("open AuthenticatedURL connection {}", url);
+//      UserGroupInformation.getCurrentUser().checkTGTAndReloginFromKeytab();
+      final AuthenticatedURL.Token authToken = new AuthenticatedURL.Token();
+      return new AuthenticatedURL(new KerberosHasAuthenticator(hasConfig.getAdminKeytab(),
+          hasConfig.getAdminKeytabPrincipal()),
+          connConfigurator).openConnection(url, authToken);
+    } else {
+      LOG.debug("open URL connection");
+      URLConnection connection = url.openConnection();
+      if (connection instanceof HttpURLConnection) {
+        connConfigurator.configure((HttpURLConnection) connection);
+      }
+      return connection;
+    }
+  }
+
+  /**
+   * Sets timeout parameters on the given URLConnection.
+   *
+   * @param connection
+   *          URLConnection to set
+   * @param connectTimeout
+   *          the connection and read timeout of the connection.
+   */
+  private static void setTimeouts(URLConnection connection,
+                                  int connectTimeout,
+                                  int readTimeout) {
+    connection.setConnectTimeout(connectTimeout);
+    connection.setReadTimeout(readTimeout);
+  }
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-server/pom.xml
----------------------------------------------------------------------
diff --git a/has-project/has-server/pom.xml b/has-project/has-server/pom.xml
new file mode 100644
index 0000000..9338981
--- /dev/null
+++ b/has-project/has-server/pom.xml
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <parent>
+    <artifactId>has-project</artifactId>
+    <groupId>org.apache.kerby</groupId>
+    <version>1.1.1-SNAPSHOT</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+
+  <artifactId>has-server</artifactId>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>kerby-config</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>kerb-identity</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>kerb-core</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>kerb-server-api-all</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>kerby-kdc</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>json-backend</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>token-provider</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-common</artifactId>
+      <version>${hadoop.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.kerby</groupId>
+      <artifactId>has-common</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.bouncycastle</groupId>
+      <artifactId>bcprov-jdk15on</artifactId>
+      <version>${bouncycastle.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+</project>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-server/src/main/java/org/apache/kerby/has/server/HasServer.java
----------------------------------------------------------------------
diff --git a/has-project/has-server/src/main/java/org/apache/kerby/has/server/HasServer.java b/has-project/has-server/src/main/java/org/apache/kerby/has/server/HasServer.java
new file mode 100644
index 0000000..ed65103
--- /dev/null
+++ b/has-project/has-server/src/main/java/org/apache/kerby/has/server/HasServer.java
@@ -0,0 +1,323 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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 org.apache.kerby.has.server;
+
+import org.apache.hadoop.http.HttpConfig;
+import org.apache.kerby.has.common.HasConfig;
+import org.apache.kerby.has.common.HasException;
+import org.apache.kerby.has.common.util.HasUtil;
+import org.apache.kerby.has.server.web.WebConfigKey;
+import org.apache.kerby.has.server.web.WebServer;
+import org.apache.kerby.kerberos.kdc.impl.NettyKdcServerImpl;
+import org.apache.kerby.kerberos.kerb.KrbException;
+import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadmin;
+import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadminImpl;
+import org.apache.kerby.kerberos.kerb.client.ClientUtil;
+import org.apache.kerby.kerberos.kerb.client.KrbConfig;
+import org.apache.kerby.kerberos.kerb.client.KrbSetting;
+import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend;
+import org.apache.kerby.kerberos.kerb.server.KdcServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+/**
+ * The HAS KDC server implementation.
+ */
+public class HasServer {
+    public static final Logger LOG = LoggerFactory.getLogger(HasServer.class);
+
+    private static HasServer server = null;
+
+    private KrbSetting krbSetting;
+    private KdcServer kdcServer;
+    private WebServer webServer;
+    private File confDir;
+    private File workDir;
+    private String kdcHost;
+    private HasConfig hasConfig;
+
+    public HasServer(File confDir) throws KrbException {
+        this.confDir = confDir;
+    }
+
+    private void setConfDir(File confDir) {
+        this.confDir = confDir;
+    }
+
+    public File getConfDir() {
+        return confDir;
+    }
+
+    public File getWorkDir() {
+        return workDir;
+    }
+
+    public void setWorkDir(File workDir) {
+        this.workDir = workDir;
+    }
+
+    public void setKdcHost(String host) {
+        this.kdcHost = host;
+    }
+
+    public String getKdcHost() {
+        return kdcHost;
+    }
+
+    public KrbSetting getKrbSetting() {
+        return krbSetting;
+    }
+
+    public KdcServer getKdcServer() {
+        return kdcServer;
+    }
+
+    public WebServer getWebServer() {
+        return webServer;
+    }
+
+    public void setWebServer(WebServer webServer) {
+        this.webServer = webServer;
+    }
+
+    public void startKdcServer() throws HasException {
+        try {
+            kdcServer = new KdcServer(confDir);
+        } catch (KrbException e) {
+            throw new HasException("Failed to create KdcServer. " + e);
+        }
+        kdcServer.setWorkDir(workDir);
+        kdcServer.setInnerKdcImpl(new NettyKdcServerImpl(kdcServer.getKdcSetting()));
+        try {
+            kdcServer.init();
+        } catch (KrbException e) {
+            LOG.error("Errors occurred when init has kdc server:  " + e.getMessage());
+            throw new HasException("Errors occurred when init has kdc server:  " + e.getMessage());
+        }
+
+        KrbConfig krbConfig = null;
+        try {
+            krbConfig = ClientUtil.getConfig(confDir);
+        } catch (KrbException e) {
+            new HasException("Errors occurred when getting the config from conf dir. "
+                + e.getMessage());
+        }
+        if (krbConfig == null) {
+            krbConfig = new KrbConfig();
+        }
+        this.krbSetting = new KrbSetting(krbConfig);
+        try {
+            kdcServer.start();
+        } catch (KrbException e) {
+            throw new HasException("Failed to start kdc server. " + e);
+        }
+        try {
+            HasUtil.setEnableConf(new File(confDir, "has-server.conf"), "false");
+        } catch (Exception e) {
+            throw new HasException("Failed to enable conf. " + e);
+        }
+        setHttpFilter();
+    }
+
+    private void setHttpFilter() throws HasException {
+        File httpKeytabFile = new File(workDir, "http.keytab");
+        LocalKadmin kadmin = new LocalKadminImpl(kdcServer.getKdcSetting(),
+            kdcServer.getIdentityService());
+        createHttpPrincipal(kadmin);
+        try {
+            kadmin.exportKeytab(httpKeytabFile, getHttpPrincipal());
+        } catch (KrbException e) {
+            throw new HasException("Failed to export keytab: " + e.getMessage());
+        }
+        webServer.getConf().setString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE,
+            hasConfig.getFilterAuthType());
+        webServer.getConf().setString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY,
+            getHttpPrincipal());
+        webServer.getConf().setString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY,
+            httpKeytabFile.getPath());
+        webServer.defineFilter();
+    }
+
+    public void createHttpPrincipal(LocalKadmin kadmin) throws HasException {
+        String httpPrincipal = getHttpPrincipal();
+        IdentityBackend backend = kdcServer.getIdentityService();
+        try {
+            if (backend.getIdentity(httpPrincipal) == null) {
+                kadmin.addPrincipal(httpPrincipal);
+            } else {
+                LOG.info("The http principal already exists in backend.");
+            }
+        } catch (KrbException e) {
+            throw new HasException("Failed to add principal, " + e.getMessage());
+        }
+    }
+
+    public String getHttpPrincipal() throws HasException {
+        String realm = kdcServer.getKdcSetting().getKdcRealm();
+        String nameString;
+        try {
+            InetAddress addr = InetAddress.getLocalHost();
+            String fqName = addr.getCanonicalHostName();
+            nameString = "HTTP/" + fqName + "@" + realm;
+        } catch (UnknownHostException e) {
+            throw new HasException(e);
+        }
+        LOG.info("The http principal name is: " + nameString);
+        return nameString;
+    }
+
+    public void stopKdcServer() {
+        try {
+            kdcServer.stop();
+        } catch (KrbException e) {
+            LOG.error("Fail to stop has kdc server");
+        }
+    }
+
+    public void startWebServer() throws HasException {
+        if (webServer == null) {
+            HasConfig conf = new HasConfig();
+
+            // Parse has-server.conf to get http_host and http_port
+            File confFile = new File(confDir, "has-server.conf");
+            hasConfig = HasUtil.getHasConfig(confFile);
+            if (hasConfig != null) {
+                try {
+                    String httpHost;
+                    String httpPort;
+                    String httpsHost;
+                    String httpsPort;
+                    if (hasConfig.getHttpHost() != null) {
+                        httpHost = hasConfig.getHttpHost();
+                    } else {
+                        LOG.info("Cannot get the http_host from has-server.conf, using the default http host.");
+                        httpHost = WebConfigKey.HAS_HTTP_HOST_DEFAULT;
+                    }
+                    if (hasConfig.getHttpPort() != null) {
+                        httpPort = hasConfig.getHttpPort();
+                    } else {
+                        LOG.info("Cannot get the http_port from has-server.conf, using the default http port.");
+                        httpPort = String.valueOf(WebConfigKey.HAS_HTTP_PORT_DEFAULT);
+                    }
+                    if (hasConfig.getHttpsHost() != null) {
+                        httpsHost = hasConfig.getHttpsHost();
+                    } else {
+                        LOG.info("Cannot get the https_host from has-server.conf, using the default https host.");
+                        httpsHost = WebConfigKey.HAS_HTTPS_HOST_DEFAULT;
+                    }
+                    if (hasConfig.getHttpsPort() != null) {
+                        httpsPort = hasConfig.getHttpsPort();
+                    } else {
+                        LOG.info("Cannot get the https_port from has-server.conf , using the default https port.");
+                        httpsPort = String.valueOf(WebConfigKey.HAS_HTTPS_PORT_DEFAULT);
+                    }
+                    String hasHttpAddress = httpHost + ":" + httpPort;
+                    String hasHttpsAddress = httpsHost + ":" + httpsPort;
+                    LOG.info("The web server http address: " + hasHttpAddress);
+                    LOG.info("The web server https address: " + hasHttpsAddress);
+
+                    conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, hasHttpAddress);
+                    conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, hasHttpsAddress);
+                    conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY,
+                        HttpConfig.Policy.HTTP_AND_HTTPS.name());
+                    conf.setString(WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY,
+                        hasConfig.getSslServerConf());
+                    webServer = new WebServer(conf);
+                } catch (NumberFormatException e) {
+                    throw new IllegalArgumentException("https_port should be a number. "
+                        + e.getMessage());
+                }
+            } else {
+                throw new HasException("has-server.conf not found in " + confDir + ". ");
+            }
+        } else {
+            hasConfig = webServer.getConf();
+        }
+        webServer.start();
+        webServer.defineConfFilter();
+        try {
+            HasUtil.setEnableConf(new File(confDir, "has-server.conf"), "true");
+        } catch (IOException e) {
+            throw new HasException("Errors occurred when enable conf. " + e.getMessage());
+        }
+        webServer.setWebServerAttribute(this);
+    }
+
+    public void stopWebServer() {
+        if (webServer != null) {
+            try {
+                webServer.stop();
+            } catch (Exception e) {
+                LOG.error("Failed to stop http server. " + e.getMessage());
+            }
+        }
+    }
+
+    public static void main(String[] args) {
+        if (args[0].equals("-start")) {
+            String confDirPath = args[1];
+            String workDirPath = args[2];
+            File confDir = new File(confDirPath);
+            File workDir = new File(workDirPath);
+            if (!confDir.exists() || !workDir.exists()) {
+                LOG.error("Invalid or not exist conf-dir or work-dir");
+                System.exit(3);
+            }
+            try {
+                server = new HasServer(confDir);
+            } catch (KrbException e) {
+                LOG.error("Errors occurred when create kdc server:  " + e.getMessage());
+                System.exit(4);
+            }
+            server.setConfDir(confDir);
+            server.setWorkDir(workDir);
+            //Only start the webserver, the kdcserver could be started after setting the realm
+            try {
+                server.startWebServer();
+            } catch (HasException e) {
+                LOG.error("Errors occurred when start has http server:  " + e.getMessage());
+                System.exit(6);
+            }
+
+            if (server.getWebServer().getHttpAddress() != null) {
+                LOG.info("HAS http server started.");
+                LOG.info("host: " + server.getWebServer().getHttpAddress().getHostName());
+                LOG.info("port: " + server.getWebServer().getHttpAddress().getPort());
+            }
+            if (server.getWebServer().getHttpsAddress() != null) {
+                LOG.info("HAS https server started.");
+                LOG.info("host: " + server.getWebServer().getHttpsAddress().getHostName());
+                LOG.info("port: " + server.getWebServer().getHttpsAddress().getPort());
+            }
+        } else if (args[0].equals("-stop")) {
+            if (server != null) {
+                server.stopWebServer();
+                server.stopKdcServer();
+            }
+        } else {
+            System.exit(2);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/ConfFilter.java
----------------------------------------------------------------------
diff --git a/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/ConfFilter.java b/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/ConfFilter.java
new file mode 100644
index 0000000..04c3537
--- /dev/null
+++ b/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/ConfFilter.java
@@ -0,0 +1,55 @@
+package org.apache.kerby.has.server.web;
+
+
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+import org.apache.hadoop.classification.InterfaceStability.Unstable;
+import org.apache.kerby.has.common.HasConfig;
+import org.apache.kerby.has.common.HasException;
+import org.apache.kerby.has.common.util.HasUtil;
+import org.apache.kerby.has.server.HasServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.File;
+import java.io.IOException;
+
+@Private
+@Unstable
+public class ConfFilter implements Filter {
+    public static final Logger LOG = LoggerFactory.getLogger(ConfFilter.class);
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+
+    }
+
+    @Override
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
+                         FilterChain filterChain) throws IOException, ServletException {
+
+        final HasServer hasServer = WebServer.getHasServerFromContext(
+                servletRequest.getServletContext());
+        HasConfig hasConfig;
+        try {
+            hasConfig = HasUtil.getHasConfig(
+                    new File(hasServer.getConfDir(), "has-server.conf"));
+            String isEnableConf = hasConfig.getEnableConf();
+            if (!isEnableConf.equals("true")) {
+                throw new RuntimeException("The kdc has started.");
+            }
+            filterChain.doFilter(servletRequest, servletResponse);
+        } catch (HasException e) {
+            LOG.error(e.getMessage());
+        }
+    }
+
+    @Override
+    public void destroy() {
+
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebConfigKey.java
----------------------------------------------------------------------
diff --git a/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebConfigKey.java b/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebConfigKey.java
new file mode 100644
index 0000000..ff31229
--- /dev/null
+++ b/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebConfigKey.java
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.kerby.has.server.web;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.http.HttpConfig;
+import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
+
+/** 
+ * This class contains constants for configuration keys and default values
+ * used in hdfs.
+ */
+@InterfaceAudience.Private
+public class WebConfigKey {
+
+  public static final int HAS_HTTP_PORT_DEFAULT = 9870;
+  public static final String HAS_HTTP_HOST_DEFAULT = "0.0.0.0";
+  public static final String HAS_HTTP_ADDRESS_KEY = "has.http-address";
+  public static final String HAS_HTTP_ADDRESS_DEFAULT = HAS_HTTP_HOST_DEFAULT + ":" + HAS_HTTP_PORT_DEFAULT;
+
+  public static final String HAS_HTTPS_BIND_HOST_KEY = "has.https-bind-host";
+  public static final int HAS_HTTPS_PORT_DEFAULT = 9871;
+  public static final String HAS_HTTPS_HOST_DEFAULT = "0.0.0.0";
+  public static final String HAS_HTTPS_ADDRESS_KEY = "has.https-address";
+  public static final String HAS_HTTPS_ADDRESS_DEFAULT = HAS_HTTPS_HOST_DEFAULT + ":" + HAS_HTTPS_PORT_DEFAULT;
+  public static final String HAS_HTTP_POLICY_KEY = "has.http.policy";
+  public static final String HAS_HTTP_POLICY_DEFAULT = HttpConfig.Policy.HTTPS_ONLY.name();
+
+  public static final String HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY = "has.https.server.keystore.resource";
+  public static final String HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT = "ssl-server.xml";
+  public static final String HAS_SERVER_HTTPS_KEYPASSWORD_KEY = "ssl.server.keystore.keypassword";
+  public static final String HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY = "ssl.server.keystore.password";
+  public static final String HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY = "ssl.server.keystore.location";
+  public static final String HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY = "ssl.server.truststore.location";
+  public static final String HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY = "ssl.server.truststore.password";
+  public static final String HAS_CLIENT_HTTPS_NEED_AUTH_KEY = "has.client.https.need-auth";
+  public static final boolean HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT = false;
+
+  public static final String HAS_AUTHENTICATION_FILTER_KEY = "has.web.authentication.filter";
+  public static final String HAS_AUTHENTICATION_FILTER_DEFAULT = AuthenticationFilter.class.getName();
+
+  public static final String HAS_AUTHENTICATION_FILTER_AUTH_TYPE = "has.authentication.filter.auth.type";
+  public static final String HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY = "has.authentication.kerberos.principal";
+  public static final String HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY = "has.authentication.kerberos.keytab";
+  public static final String HAS_AUTHENTICATION_KERBEROS_NAME_RULES = "has.authentication.kerberos.name.rules";
+}

http://git-wip-us.apache.org/repos/asf/directory-kerby/blob/59a31012/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java
----------------------------------------------------------------------
diff --git a/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java b/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java
new file mode 100644
index 0000000..15e817c
--- /dev/null
+++ b/has-project/has-server/src/main/java/org/apache/kerby/has/server/web/WebServer.java
@@ -0,0 +1,335 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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 org.apache.kerby.has.server.web;
+
+import org.apache.hadoop.HadoopIllegalArgumentException;
+import org.apache.hadoop.http.HttpConfig;
+import org.apache.hadoop.http.HttpServer2;
+import org.apache.hadoop.net.NetUtils;
+import org.apache.hadoop.security.SecurityUtil;
+import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
+import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler;
+import org.apache.kerby.has.common.HasConfig;
+import org.apache.kerby.has.common.HasException;
+import org.apache.kerby.has.server.HasServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.ServletContext;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+
+public class WebServer {
+    public static final Logger LOG = LoggerFactory.getLogger(WebServer.class);
+
+    private HttpServer2 httpServer;
+    private final HasConfig conf;
+
+    private InetSocketAddress httpAddress;
+    private InetSocketAddress httpsAddress;
+
+    protected static final String HAS_SERVER_ATTRIBUTE_KEY = "hasserver";
+
+    public WebServer(HasConfig conf) {
+        this.conf = conf;
+    }
+
+    public HasConfig getConf() {
+        return conf;
+    }
+
+    public void defineFilter() {
+        String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE);
+        if (authType.equals("kerberos")) {
+            // add authentication filter for webhdfs
+            final String className = conf.getString(
+                WebConfigKey.HAS_AUTHENTICATION_FILTER_KEY,
+                WebConfigKey.HAS_AUTHENTICATION_FILTER_DEFAULT);
+
+            final String name = className;
+
+            Map<String, String> params = getAuthFilterParams(conf);
+
+            String adminPathSpec = "/has/v1/admin/*";
+            HttpServer2.defineFilter(httpServer.getWebAppContext(), name, className,
+                params, new String[]{adminPathSpec});
+            HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className
+                + ")");
+        }
+    }
+
+    public void defineConfFilter() {
+        String confFilterName = ConfFilter.class.getName();
+        String confPath = "/has/v1/conf/*";
+        HttpServer2.defineFilter(httpServer.getWebAppContext(), confFilterName, confFilterName,
+                getAuthFilterParams(conf), new String[]{confPath});
+        HttpServer2.LOG.info("Added filter '" + confFilterName + "' (class=" + confFilterName
+                + ")");
+    }
+
+    private Map<String, String> getAuthFilterParams(HasConfig conf) {
+        Map<String, String> params = new HashMap<String, String>();
+
+        String authType = conf.getString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE);
+        if (authType != null && !authType.isEmpty()) {
+            params.put(AuthenticationFilter.AUTH_TYPE, authType);
+        }
+        String principal = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY);
+        if (principal != null && !principal.isEmpty()) {
+            try {
+                principal = SecurityUtil.getServerPrincipal(principal,
+                    getHttpsAddress().getHostName());
+            } catch (IOException e) {
+                LOG.warn("Errors occurred when get server principal. " + e.getMessage());
+            }
+            params.put(KerberosAuthenticationHandler.PRINCIPAL, principal);
+        }
+        String keytab = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY);
+        if (keytab != null && !keytab.isEmpty()) {
+            params.put(KerberosAuthenticationHandler.KEYTAB, keytab);
+        }
+        String rule = conf.getString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_NAME_RULES);
+        if (rule != null && !rule.isEmpty()) {
+            params.put(KerberosAuthenticationHandler.NAME_RULES, rule);
+        } else {
+            params.put(KerberosAuthenticationHandler.NAME_RULES, "DEFAULT");
+        }
+        return params;
+    }
+
+    public InetSocketAddress getBindAddress() {
+        if (httpAddress != null) {
+            return httpAddress;
+        } else if (httpsAddress != null) {
+            return httpsAddress;
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * for information related to the different configuration options and
+     * Http Policy is decided.
+     */
+    public void start() throws HasException {
+
+        HttpConfig.Policy policy = getHttpPolicy(conf);
+
+        final String bindHost =
+            conf.getString(WebConfigKey.HAS_HTTPS_BIND_HOST_KEY);
+        InetSocketAddress httpAddr = null;
+        if (policy.isHttpEnabled()) {
+            final String httpAddrString = conf.getString(
+                WebConfigKey.HAS_HTTP_ADDRESS_KEY,
+                WebConfigKey.HAS_HTTP_ADDRESS_DEFAULT);
+            httpAddr = NetUtils.createSocketAddr(httpAddrString);
+            if (bindHost != null && !bindHost.isEmpty()) {
+                httpAddr = new InetSocketAddress(bindHost, httpAddr.getPort());
+            }
+            LOG.info("Get the http address: " + httpAddr);
+        }
+
+        InetSocketAddress httpsAddr = null;
+        if (policy.isHttpsEnabled()) {
+            final String httpsAddrString = conf.getString(
+                WebConfigKey.HAS_HTTPS_ADDRESS_KEY,
+                WebConfigKey.HAS_HTTPS_ADDRESS_DEFAULT);
+            httpsAddr = NetUtils.createSocketAddr(httpsAddrString);
+
+            if (bindHost != null && !bindHost.isEmpty()) {
+                httpsAddr = new InetSocketAddress(bindHost, httpsAddr.getPort());
+            }
+            LOG.info("Get the https address: " + httpsAddr);
+        }
+
+        HttpServer2.Builder builder = httpServerTemplateForHAS(conf, httpAddr, httpsAddr, "has");
+
+        try {
+            httpServer = builder.build();
+        } catch (IOException e) {
+            throw new HasException("Errors occurred when building http server. " + e.getMessage());
+        }
+
+        try {
+            httpServer.start();
+        } catch (IOException e) {
+            throw new HasException("Errors occurred when starting http server. " + e.getMessage());
+        }
+        int connIdx = 0;
+        if (policy.isHttpEnabled()) {
+            httpAddress = httpServer.getConnectorAddress(connIdx++);
+            conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY,
+                NetUtils.getHostPortString(httpAddress));
+        }
+
+        if (policy.isHttpsEnabled()) {
+            httpsAddress = httpServer.getConnectorAddress(connIdx);
+            conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY,
+                NetUtils.getHostPortString(httpsAddress));
+        }
+    }
+
+    public void setWebServerAttribute(HasServer hasServer) {
+        httpServer.setAttribute(HAS_SERVER_ATTRIBUTE_KEY, hasServer);
+    }
+
+    public static HasServer getHasServerFromContext(ServletContext context) {
+        return (HasServer) context.getAttribute(HAS_SERVER_ATTRIBUTE_KEY);
+    }
+
+    /**
+     * Get http policy.
+     */
+    public HttpConfig.Policy getHttpPolicy(HasConfig conf) {
+        String policyStr = conf.getString(WebConfigKey.HAS_HTTP_POLICY_KEY,
+            WebConfigKey.HAS_HTTP_POLICY_DEFAULT);
+        HttpConfig.Policy policy = HttpConfig.Policy.fromString(policyStr);
+        if (policy == null) {
+            throw new HadoopIllegalArgumentException("Unrecognized value '"
+                + policyStr + "' for " + WebConfigKey.HAS_HTTP_POLICY_KEY);
+        }
+
+        conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, policy.name());
+        return policy;
+    }
+
+    /**
+     * Return a HttpServer.Builder that the ssm can use to
+     * initialize their HTTP / HTTPS server.
+     */
+    public HttpServer2.Builder httpServerTemplateForHAS(
+        HasConfig conf, final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr,
+        String name) throws HasException {
+        HttpConfig.Policy policy = getHttpPolicy(conf);
+
+        HttpServer2.Builder builder = new HttpServer2.Builder().setName(name);
+
+        if (policy.isHttpEnabled()) {
+            if (httpAddr.getPort() == 0) {
+                builder.setFindPort(true);
+            }
+
+            URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr));
+            builder.addEndpoint(uri);
+            LOG.info("Starting Web-server for " + name + " at: " + uri);
+        }
+
+        if (policy.isHttpsEnabled() && httpsAddr != null) {
+            HasConfig sslConf = loadSslConfiguration(conf);
+            loadSslConfToHttpServerBuilder(builder, sslConf);
+
+            if (httpsAddr.getPort() == 0) {
+                builder.setFindPort(true);
+            }
+
+            URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr));
+            builder.addEndpoint(uri);
+            LOG.info("Starting Web-server for " + name + " at: " + uri);
+        }
+
+        return builder;
+    }
+
+    /**
+     * Load HTTPS-related configuration.
+     */
+    public HasConfig loadSslConfiguration(HasConfig conf) throws HasException {
+        HasConfig sslConf = new HasConfig();
+
+        String sslConfigString = conf.getString(
+            WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY,
+            WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_DEFAULT);
+        LOG.info("Get the ssl config file: " + sslConfigString);
+        try {
+            sslConf.addIniConfig(new File(sslConfigString));
+        } catch (IOException e) {
+            throw new HasException("Errors occurred when adding config. " + e.getMessage());
+        }
+
+        final String[] reqSslProps = {
+            WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_LOCATION_KEY,
+            WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_LOCATION_KEY,
+            WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY,
+            WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY
+        };
+
+        // Check if the required properties are included
+        for (String sslProp : reqSslProps) {
+            if (sslConf.getString(sslProp) == null) {
+                LOG.warn("SSL config " + sslProp + " is missing. If "
+                    + WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY
+                    + " is specified, make sure it is a relative path");
+            }
+        }
+
+        boolean requireClientAuth = conf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY,
+            WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT);
+        sslConf.setBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY, requireClientAuth);
+        return sslConf;
+    }
+
+    public HttpServer2.Builder loadSslConfToHttpServerBuilder(HttpServer2.Builder builder,
+                                                              HasConfig sslConf) {
+        return builder
+            .needsClientAuth(
+                sslConf.getBoolean(WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_KEY,
+                    WebConfigKey.HAS_CLIENT_HTTPS_NEED_AUTH_DEFAULT))
+            .keyPassword(getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYPASSWORD_KEY))
+            .keyStore(sslConf.getString("ssl.server.keystore.location"),
+                getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_PASSWORD_KEY),
+                sslConf.getString("ssl.server.keystore.type", "jks"))
+            .trustStore(sslConf.getString("ssl.server.truststore.location"),
+                getPassword(sslConf, WebConfigKey.HAS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY),
+                sslConf.getString("ssl.server.truststore.type", "jks"))
+            .excludeCiphers(
+                sslConf.getString("ssl.server.exclude.cipher.list"));
+    }
+
+    /**
+     * Leverages the Configuration.getPassword method to attempt to get
+     * passwords from the CredentialProvider API before falling back to
+     * clear text in config - if falling back is allowed.
+     *
+     * @param conf  Configuration instance
+     * @param alias name of the credential to retreive
+     * @return String credential value or null
+     */
+    public String getPassword(HasConfig conf, String alias) {
+
+        return conf.getString(alias);
+    }
+
+    public void stop() throws Exception {
+        if (httpServer != null) {
+            httpServer.stop();
+        }
+    }
+
+    public InetSocketAddress getHttpAddress() {
+        return httpAddress;
+    }
+
+    public InetSocketAddress getHttpsAddress() {
+        return httpsAddress;
+    }
+}


Mime
View raw message