View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.sso.spnego;
17  
18  import java.io.File;
19  import java.util.Enumeration;
20  
21  import javax.annotation.PostConstruct;
22  import javax.servlet.FilterConfig;
23  import javax.servlet.ServletContext;
24  import javax.servlet.http.HttpServletResponse;
25  
26  import org.codelibs.core.io.ResourceUtil;
27  import org.codelibs.core.lang.StringUtil;
28  import org.codelibs.fess.app.web.base.login.ActionResponseCredential;
29  import org.codelibs.fess.app.web.base.login.FessLoginAssist.LoginCredentialResolver;
30  import org.codelibs.fess.app.web.base.login.SpnegoCredential;
31  import org.codelibs.fess.exception.SsoLoginException;
32  import org.codelibs.fess.mylasta.direction.FessConfig;
33  import org.codelibs.fess.sso.SsoAuthenticator;
34  import org.codelibs.fess.util.ComponentUtil;
35  import org.codelibs.spnego.SpnegoFilterConfig;
36  import org.codelibs.spnego.SpnegoHttpFilter;
37  import org.codelibs.spnego.SpnegoHttpFilter.Constants;
38  import org.codelibs.spnego.SpnegoHttpServletResponse;
39  import org.codelibs.spnego.SpnegoPrincipal;
40  import org.dbflute.optional.OptionalEntity;
41  import org.lastaflute.web.login.credential.LoginCredential;
42  import org.lastaflute.web.servlet.filter.RequestLoggingFilter;
43  import org.lastaflute.web.util.LaRequestUtil;
44  import org.lastaflute.web.util.LaResponseUtil;
45  import org.slf4j.Logger;
46  import org.slf4j.LoggerFactory;
47  
48  public class SpnegoAuthenticator implements SsoAuthenticator {
49  
50      private static final Logger logger = LoggerFactory.getLogger(SpnegoAuthenticator.class);
51  
52      protected static final String SPNEGO_INITIALIZED = "spnego.initialized";
53      protected static final String SPNEGO_EXCLUDE_DIRS = "spnego.exclude.dirs";
54      protected static final String SPNEGO_ALLOW_DELEGATION = "spnego.allow.delegation";
55      protected static final String SPNEGO_ALLOW_LOCALHOST = "spnego.allow.localhost";
56      protected static final String SPNEGO_PROMPT_NTLM = "spnego.prompt.ntlm";
57      protected static final String SPNEGO_ALLOW_UNSECURE_BASIC = "spnego.allow.unsecure.basic";
58      protected static final String SPNEGO_ALLOW_BASIC = "spnego.allow.basic";
59      protected static final String SPNEGO_PREAUTH_PASSWORD = "spnego.preauth.password";
60      protected static final String SPNEGO_PREAUTH_USERNAME = "spnego.preauth.username";
61      protected static final String SPNEGO_LOGIN_SERVER_MODULE = "spnego.login.server.module";
62      protected static final String SPNEGO_LOGIN_CLIENT_MODULE = "spnego.login.client.module";
63      protected static final String SPNEGO_KRB5_CONF = "spnego.krb5.conf";
64      protected static final String SPNEGO_LOGIN_CONF = "spnego.login.conf";
65      protected static final String SPNEGO_LOGGER_LEVEL = "spnego.logger.level";
66  
67      protected org.codelibs.spnego.SpnegoAuthenticator authenticator = null;
68  
69      @PostConstruct
70      public void init() {
71          ComponentUtil.getSsoManager().register(this);
72      }
73  
74      protected synchronized org.codelibs.spnego.SpnegoAuthenticator getAuthenticator() {
75          final FessConfig fessConfig = ComponentUtil.getFessConfig();
76          if (authenticator != null && fessConfig.getSystemPropertyAsBoolean(SPNEGO_INITIALIZED, false)) {
77              return authenticator;
78          }
79          try {
80              // set some System properties
81              final SpnegoFilterConfig config = SpnegoFilterConfig.getInstance(new SpengoConfig());
82  
83              // pre-authenticate
84              authenticator = new org.codelibs.spnego.SpnegoAuthenticator(config);
85  
86              fessConfig.setSystemPropertyAsBoolean(SPNEGO_INITIALIZED, true);
87              fessConfig.storeSystemProperties();
88              return authenticator;
89          } catch (final Exception e) {
90              throw new SsoLoginException("Failed to initialize SPNEGO.", e);
91          }
92      }
93  
94      /* (non-Javadoc)
95       * @see org.codelibs.fess.sso.spnego.SsoAuthenticator#getLoginCredential()
96       */
97      @Override
98      public LoginCredential getLoginCredential() {
99          return LaRequestUtil
100                 .getOptionalRequest()
101                 .map(request -> {
102                     final HttpServletResponse response = LaResponseUtil.getResponse();
103                     final SpnegoHttpServletResponse spnegoResponse = new SpnegoHttpServletResponse(response);
104 
105                     // client/caller principal
106                     final SpnegoPrincipal principal;
107                     try {
108                         principal = getAuthenticator().authenticate(request, spnegoResponse);
109                     } catch (final Exception e) {
110                         final String msg = "HTTP Authorization Header=" + request.getHeader(Constants.AUTHZ_HEADER);
111                         if (logger.isDebugEnabled()) {
112                             logger.debug(msg);
113                         }
114                         throw new SsoLoginException(msg, e);
115                     }
116 
117                     // context/auth loop not yet complete
118                     if (spnegoResponse.isStatusSet()) {
119                         return new ActionResponseCredential(() -> {
120                             throw new RequestLoggingFilter.RequestClientErrorException("Your request is not authorized.",
121                                     "401 Unauthorized", HttpServletResponse.SC_UNAUTHORIZED);
122                         });
123                     }
124 
125                     // assert
126                     if (null == principal) {
127                         final String msg = "Principal was null.";
128                         if (logger.isDebugEnabled()) {
129                             logger.debug(msg);
130                         }
131                         throw new SsoLoginException(msg);
132                     }
133 
134                     if (logger.isDebugEnabled()) {
135                         logger.debug("principal=" + principal);
136                     }
137 
138                     final String[] username = principal.getName().split("@", 2);
139                     return new SpnegoCredential(username[0]);
140                 }).orElseGet(() -> null);
141 
142     }
143 
144     protected class SpengoConfig implements FilterConfig {
145 
146         @Override
147         public String getFilterName() {
148             return SpnegoAuthenticator.class.getName();
149         }
150 
151         @Override
152         public ServletContext getServletContext() {
153             throw new UnsupportedOperationException();
154         }
155 
156         @Override
157         public String getInitParameter(final String name) {
158             if (SpnegoHttpFilter.Constants.LOGGER_LEVEL.equals(name)) {
159                 final String logLevel = getProperty(SPNEGO_LOGGER_LEVEL, StringUtil.EMPTY);
160                 if (StringUtil.isNotBlank(logLevel)) {
161                     return logLevel;
162                 } else if (logger.isDebugEnabled()) {
163                     return "3";
164                 } else if (logger.isInfoEnabled()) {
165                     return "5";
166                 } else if (logger.isWarnEnabled()) {
167                     return "6";
168                 } else if (logger.isErrorEnabled()) {
169                     return "7";
170                 } else {
171                     return "0";
172                 }
173             } else if (SpnegoHttpFilter.Constants.LOGIN_CONF.equals(name)) {
174                 return getResourcePath(getProperty(SPNEGO_LOGIN_CONF, "auth_login.conf"));
175             } else if (SpnegoHttpFilter.Constants.KRB5_CONF.equals(name)) {
176                 return getResourcePath(getProperty(SPNEGO_KRB5_CONF, "krb5.conf"));
177             } else if (SpnegoHttpFilter.Constants.CLIENT_MODULE.equals(name)) {
178                 return getProperty(SPNEGO_LOGIN_CLIENT_MODULE, "spnego-client");
179             } else if (SpnegoHttpFilter.Constants.SERVER_MODULE.equals(name)) {
180                 return getProperty(SPNEGO_LOGIN_SERVER_MODULE, "spnego-server");
181             } else if (SpnegoHttpFilter.Constants.PREAUTH_USERNAME.equals(name)) {
182                 return getProperty(SPNEGO_PREAUTH_USERNAME, "username");
183             } else if (SpnegoHttpFilter.Constants.PREAUTH_PASSWORD.equals(name)) {
184                 return getProperty(SPNEGO_PREAUTH_PASSWORD, "password");
185             } else if (SpnegoHttpFilter.Constants.ALLOW_BASIC.equals(name)) {
186                 return getProperty(SPNEGO_ALLOW_BASIC, "true");
187             } else if (SpnegoHttpFilter.Constants.ALLOW_UNSEC_BASIC.equals(name)) {
188                 return getProperty(SPNEGO_ALLOW_UNSECURE_BASIC, "true");
189             } else if (SpnegoHttpFilter.Constants.PROMPT_NTLM.equals(name)) {
190                 return getProperty(SPNEGO_PROMPT_NTLM, "true");
191             } else if (SpnegoHttpFilter.Constants.ALLOW_LOCALHOST.equals(name)) {
192                 return getProperty(SPNEGO_ALLOW_LOCALHOST, "true");
193             } else if (SpnegoHttpFilter.Constants.ALLOW_DELEGATION.equals(name)) {
194                 return getProperty(SPNEGO_ALLOW_DELEGATION, "false");
195             } else if (SpnegoHttpFilter.Constants.EXCLUDE_DIRS.equals(name)) {
196                 return getProperty(SPNEGO_EXCLUDE_DIRS, StringUtil.EMPTY);
197             }
198             return null;
199         }
200 
201         protected String getProperty(final String key, final String defaultValue) {
202             return ComponentUtil.getSystemProperties().getProperty(key, defaultValue);
203         }
204 
205         protected String getResourcePath(final String path) {
206             final File file = ResourceUtil.getResourceAsFileNoException(path);
207             if (file != null) {
208                 return file.getAbsolutePath();
209             }
210             return null;
211         }
212 
213         @Override
214         public Enumeration<String> getInitParameterNames() {
215             throw new UnsupportedOperationException();
216         }
217 
218     }
219 
220     @Override
221     public void resolveCredential(final LoginCredentialResolver resolver) {
222         resolver.resolve(SpnegoCredential.class, credential -> {
223             final String username = credential.getUserId();
224             if (!ComponentUtil.getFessConfig().isAdminUser(username)) {
225                 return ComponentUtil.getLdapManager().login(username);
226             }
227             return OptionalEntity.empty();
228         });
229     }
230 }