1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.codelibs.fess.sso.aad;
17
18 import static org.codelibs.core.stream.StreamUtil.split;
19
20 import java.io.IOException;
21 import java.net.URI;
22 import java.net.URLEncoder;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.Map;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.Future;
34 import java.util.concurrent.TimeUnit;
35 import java.util.stream.Collectors;
36
37 import javax.annotation.PostConstruct;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpSession;
40
41 import org.apache.commons.lang3.StringUtils;
42 import org.codelibs.core.lang.StringUtil;
43 import org.codelibs.core.misc.Pair;
44 import org.codelibs.core.net.UuidUtil;
45 import org.codelibs.core.stream.StreamUtil;
46 import org.codelibs.curl.Curl;
47 import org.codelibs.curl.CurlResponse;
48 import org.codelibs.elasticsearch.runner.net.EcrCurl;
49 import org.codelibs.fess.app.web.base.login.ActionResponseCredential;
50 import org.codelibs.fess.app.web.base.login.AzureAdCredential;
51 import org.codelibs.fess.app.web.base.login.AzureAdCredential.AzureAdUser;
52 import org.codelibs.fess.app.web.base.login.FessLoginAssist.LoginCredentialResolver;
53 import org.codelibs.fess.crawler.Constants;
54 import org.codelibs.fess.exception.SsoLoginException;
55 import org.codelibs.fess.sso.SsoAuthenticator;
56 import org.codelibs.fess.util.ComponentUtil;
57 import org.codelibs.fess.util.DocumentUtil;
58 import org.dbflute.optional.OptionalEntity;
59 import org.lastaflute.web.login.credential.LoginCredential;
60 import org.lastaflute.web.response.HtmlResponse;
61 import org.lastaflute.web.util.LaRequestUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 import com.google.common.cache.Cache;
66 import com.google.common.cache.CacheBuilder;
67 import com.microsoft.aad.adal4j.AuthenticationContext;
68 import com.microsoft.aad.adal4j.AuthenticationResult;
69 import com.microsoft.aad.adal4j.ClientCredential;
70 import com.nimbusds.jwt.JWTClaimsSet;
71 import com.nimbusds.jwt.JWTParser;
72 import com.nimbusds.oauth2.sdk.AuthorizationCode;
73 import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse;
74 import com.nimbusds.openid.connect.sdk.AuthenticationResponse;
75 import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser;
76 import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse;
77
78 public class AzureAdAuthenticator implements SsoAuthenticator {
79
80 private static final Logger logger = LoggerFactory.getLogger(AzureAdAuthenticator.class);
81
82 protected static final String AZUREAD_STATE_TTL = "aad.state.ttl";
83
84 protected static final String AZUREAD_AUTHORITY = "aad.authority";
85
86 protected static final String AZUREAD_TENANT = "aad.tenant";
87
88 protected static final String AZUREAD_CLIENT_SECRET = "aad.client.secret";
89
90 protected static final String AZUREAD_CLIENT_ID = "aad.client.id";
91
92 protected static final String AZUREAD_REPLY_URL = "aad.reply.url";
93
94 protected static final String STATES = "aadStates";
95
96 protected static final String STATE = "state";
97
98 protected static final String ERROR = "error";
99
100 protected static final String ERROR_DESCRIPTION = "error_description";
101
102 protected static final String ERROR_URI = "error_uri";
103
104 protected static final String ID_TOKEN = "id_token";
105
106 protected static final String CODE = "code";
107
108 protected long acquisitionTimeout = 30 * 1000L;
109
110 protected Cache<String, Pair<String[], String[]>> groupCache;
111
112 protected long groupCacheExpiry = 10 * 60L;
113
114 @PostConstruct
115 public void init() {
116 ComponentUtil.getSsoManager().register(this);
117 groupCache = CacheBuilder.newBuilder().expireAfterWrite(groupCacheExpiry, TimeUnit.SECONDS).build();
118 }
119
120 @Override
121 public LoginCredential getLoginCredential() {
122 return LaRequestUtil.getOptionalRequest().map(request -> {
123 final HttpSession session = request.getSession(false);
124 if (session != null && containsAuthenticationData(request)) {
125 try {
126 return processAuthenticationData(request);
127 } catch (final Exception e) {
128 if (logger.isDebugEnabled()) {
129 logger.debug("Failed to process a login request on AzureAD.", e);
130 }
131 }
132 return null;
133 }
134
135 return new ActionResponseCredential(() -> HtmlResponse.fromRedirectPathAsIs(getAuthUrl(request)));
136 }).orElse(null);
137 }
138
139 protected String getAuthUrl(final HttpServletRequest request) {
140 final String state = UuidUtil.create();
141 final String nonce = UuidUtil.create();
142 storeStateInSession(request.getSession(), state, nonce);
143 final String authUrl =
144 getAuthority() + getTenant()
145 + "/oauth2/authorize?response_type=code&scope=directory.read.all&response_mode=form_post&redirect_uri="
146 + URLEncoder.encode(getReplyUrl(request), Constants.UTF_8_CHARSET) + "&client_id=" + getClientId()
147 + "&resource=https%3a%2f%2fgraph.microsoft.com" + "&state=" + state + "&nonce=" + nonce;
148 if (logger.isDebugEnabled()) {
149 logger.debug("redirect to: {}", authUrl);
150 }
151 return authUrl;
152
153 }
154
155 protected void storeStateInSession(final HttpSession session, final String state, final String nonce) {
156 @SuppressWarnings("unchecked")
157 Map<String, StateData> stateMap = (Map<String, StateData>) session.getAttribute(STATES);
158 if (stateMap == null) {
159 stateMap = new HashMap<>();
160 session.setAttribute(STATES, stateMap);
161 }
162 final StateData stateData = new StateData(nonce, System.currentTimeMillis());
163 if (logger.isDebugEnabled()) {
164 logger.debug("store {} in session", stateData);
165 }
166 stateMap.put(state, stateData);
167 }
168
169 protected LoginCredential processAuthenticationData(final HttpServletRequest request) {
170 final StringBuffer urlBuf = request.getRequestURL();
171 final String queryStr = request.getQueryString();
172 if (queryStr != null) {
173 urlBuf.append('?').append(queryStr);
174 }
175
176 final Map<String, List<String>> params = new HashMap<>();
177 for (final Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
178 if (e.getValue().length > 0) {
179 params.put(e.getKey(), Arrays.asList(e.getValue()));
180 }
181 }
182 if (logger.isDebugEnabled()) {
183 logger.debug("process authentication: url: {}, params: {}", urlBuf, params);
184 }
185
186
187 final StateData stateData = validateState(request.getSession(), params.containsKey(STATE) ? params.get(STATE).get(0) : null);
188 if (logger.isDebugEnabled()) {
189 logger.debug("load {}", stateData);
190 }
191
192 final AuthenticationResponse authResponse = parseAuthenticationResponse(urlBuf.toString(), params);
193 if (authResponse instanceof AuthenticationSuccessResponse) {
194 final AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse) authResponse;
195 validateAuthRespMatchesCodeFlow(oidcResponse);
196 final AuthenticationResult authData = getAccessToken(oidcResponse.getAuthorizationCode(), getReplyUrl(request));
197 validateNonce(stateData, authData);
198
199 return new AzureAdCredential(authData);
200 } else {
201 final AuthenticationErrorResponse oidcResponse = (AuthenticationErrorResponse) authResponse;
202 throw new SsoLoginException(String.format("Request for auth code failed: %s - %s", oidcResponse.getErrorObject().getCode(),
203 oidcResponse.getErrorObject().getDescription()));
204 }
205 }
206
207 protected AuthenticationResponse parseAuthenticationResponse(final String url, final Map<String, List<String>> params) {
208 if (logger.isDebugEnabled()) {
209 logger.debug("Parse: {} : {}", url, params);
210 }
211 try {
212 return AuthenticationResponseParser.parse(new URI(url), params);
213 } catch (final Exception e) {
214 throw new SsoLoginException("Failed to parse an authentication response.", e);
215 }
216 }
217
218 protected void validateNonce(final StateData stateData, final AuthenticationResult authData) {
219 final String idToken = authData.getIdToken();
220 if (logger.isDebugEnabled()) {
221 logger.debug("idToken: {}", idToken);
222 }
223 try {
224 final JWTClaimsSet claimsSet = JWTParser.parse(idToken).getJWTClaimsSet();
225 if (claimsSet == null) {
226 throw new SsoLoginException("could not validate nonce");
227 }
228
229 final String nonce = (String) claimsSet.getClaim("nonce");
230 if (logger.isDebugEnabled()) {
231 logger.debug("nonce: {}", nonce);
232 }
233 if (StringUtils.isEmpty(nonce) || !nonce.equals(stateData.getNonce())) {
234 throw new SsoLoginException("could not validate nonce");
235 }
236 } catch (final SsoLoginException e) {
237 throw e;
238 } catch (final Exception e) {
239 throw new SsoLoginException("could not validate nonce", e);
240 }
241 }
242
243 public AuthenticationResult getAccessToken(final String refreshToken) {
244 final String authority = getAuthority() + getTenant() + "/";
245 if (logger.isDebugEnabled()) {
246 logger.debug("refreshToken: {}, authority: {}", refreshToken, authority);
247 }
248 ExecutorService service = null;
249 try {
250 service = Executors.newFixedThreadPool(1);
251 final AuthenticationContext context = new AuthenticationContext(authority, true, service);
252 final Future<AuthenticationResult> future =
253 context.acquireTokenByRefreshToken(refreshToken, new ClientCredential(getClientId(), getClientSecret()), null, null);
254 final AuthenticationResult result = future.get(acquisitionTimeout, TimeUnit.MILLISECONDS);
255 if (result == null) {
256 throw new SsoLoginException("authentication result was null");
257 }
258 return result;
259 } catch (final Exception e) {
260 throw new SsoLoginException("Failed to get a token.", e);
261 } finally {
262 if (service != null) {
263 service.shutdown();
264 }
265 }
266 }
267
268 protected AuthenticationResult getAccessToken(final AuthorizationCode authorizationCode, final String currentUri) {
269 final String authority = getAuthority() + getTenant() + "/";
270 final String authCode = authorizationCode.getValue();
271 if (logger.isDebugEnabled()) {
272 logger.debug("authCode: {}, authority: {}, uri: {}", authCode, authority, currentUri);
273 }
274 final ClientCredential credential = new ClientCredential(getClientId(), getClientSecret());
275 ExecutorService service = null;
276 try {
277 service = Executors.newFixedThreadPool(1);
278 final AuthenticationContext context = new AuthenticationContext(authority, true, service);
279 final Future<AuthenticationResult> future =
280 context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null);
281 final AuthenticationResult result = future.get(acquisitionTimeout, TimeUnit.MILLISECONDS);
282 if (result == null) {
283 throw new SsoLoginException("authentication result was null");
284 }
285 return result;
286 } catch (final Exception e) {
287 throw new SsoLoginException("Failed to get a token.", e);
288 } finally {
289 if (service != null) {
290 service.shutdown();
291 }
292 }
293 }
294
295 protected void validateAuthRespMatchesCodeFlow(final AuthenticationSuccessResponse oidcResponse) {
296 if (oidcResponse.getIDToken() != null || oidcResponse.getAccessToken() != null || oidcResponse.getAuthorizationCode() == null) {
297 throw new SsoLoginException("unexpected set of artifacts received");
298 }
299 }
300
301 protected StateData validateState(final HttpSession session, final String state) {
302 if (StringUtils.isNotEmpty(state)) {
303 final StateData stateDataInSession = removeStateFromSession(session, state);
304 if (stateDataInSession != null) {
305 return stateDataInSession;
306 }
307 }
308 throw new SsoLoginException("could not validate state");
309 }
310
311 protected StateData removeStateFromSession(final HttpSession session, final String state) {
312 @SuppressWarnings("unchecked")
313 final Map<String, StateData> states = (Map<String, StateData>) session.getAttribute(STATES);
314 if (states != null) {
315 final long now = System.currentTimeMillis();
316 states.entrySet().stream().filter(e -> (now - e.getValue().getExpiration()) / 1000L > getStateTtl()).map(Map.Entry::getKey)
317 .collect(Collectors.toList()).forEach(s -> {
318 if (logger.isDebugEnabled()) {
319 logger.debug("remove old state: {}", s);
320 }
321 states.remove(s);
322 });
323 final StateData stateData = states.get(state);
324 if (stateData != null) {
325 if (logger.isDebugEnabled()) {
326 logger.debug("restore {} from session", stateData);
327 }
328 states.remove(state);
329 return stateData;
330 }
331 }
332 return null;
333 }
334
335 protected boolean containsAuthenticationData(final HttpServletRequest request) {
336 if (!request.getMethod().equalsIgnoreCase("POST")) {
337 return false;
338 }
339 final Map<String, String[]> params = request.getParameterMap();
340 return params.containsKey(ERROR) || params.containsKey(ID_TOKEN) || params.containsKey(CODE);
341 }
342
343 public void updateMemberOf(final AzureAdUser user) {
344 final List<String> groupList = new ArrayList<>();
345 final List<String> roleList = new ArrayList<>();
346 groupList.addAll(getDefaultGroupList());
347 roleList.addAll(getDefaultRoleList());
348 processMemberOf(user, groupList, roleList, "https://graph.microsoft.com/v1.0/me/memberOf");
349 user.setGroups(groupList.stream().distinct().toArray(n -> new String[n]));
350 user.setRoles(roleList.stream().distinct().toArray(n -> new String[n]));
351 }
352
353 protected void processMemberOf(final AzureAdUser user, final List<String> groupList, final List<String> roleList, final String url) {
354 if (logger.isDebugEnabled()) {
355 logger.debug("url: {}", url);
356 }
357 try (CurlResponse response =
358 Curl.get(url).header("Authorization", "Bearer " + user.getAuthenticationResult().getAccessToken())
359 .header("Accept", "application/json").execute()) {
360 final Map<String, Object> contentMap = response.getContent(EcrCurl.jsonParser());
361 if (logger.isDebugEnabled()) {
362 logger.debug("response: {}", contentMap);
363 }
364 if (contentMap.containsKey("value")) {
365 @SuppressWarnings("unchecked")
366 final List<Map<String, Object>> memberOfList = (List<Map<String, Object>>) contentMap.get("value");
367 for (final Map<String, Object> memberOf : memberOfList) {
368 if (logger.isDebugEnabled()) {
369 logger.debug("member: {}", memberOf);
370 }
371 String memberType = (String) memberOf.get("@odata.type");
372 if (memberType == null) {
373 logger.warn("@odata.type is null: {}", memberOf);
374 continue;
375 }
376 memberType = memberType.toLowerCase(Locale.ENGLISH);
377 final String id = (String) memberOf.get("id");
378 if (StringUtil.isNotBlank(id)) {
379 if (memberType.contains("group")) {
380 groupList.add(id);
381 } else if (memberType.contains("role")) {
382 roleList.add(id);
383 } else {
384 if (logger.isDebugEnabled()) {
385 logger.debug("unknown @odata.type: {}", memberOf);
386 }
387 groupList.add(id);
388 }
389 processParentGroup(user, groupList, roleList, id);
390 } else {
391 logger.warn("id is empty: {}", memberOf);
392 }
393 final String mail = (String) memberOf.get("mail");
394 if (StringUtil.isNotBlank(mail)) {
395 if (memberType.contains("group")) {
396 groupList.add(mail);
397 } else if (memberType.contains("role")) {
398 roleList.add(mail);
399 } else {
400 if (logger.isDebugEnabled()) {
401 logger.debug("unknown @odata.type: {}", memberOf);
402 }
403 groupList.add(mail);
404 }
405 } else if (logger.isDebugEnabled()) {
406 logger.debug("mail is empty: {}", memberOf);
407 }
408 }
409 final String nextLink = (String) contentMap.get("@odata.nextLink");
410 if (StringUtil.isNotBlank(nextLink)) {
411 processMemberOf(user, groupList, roleList, nextLink);
412 }
413 } else if (contentMap.containsKey("error")) {
414 logger.warn("Failed to access groups/roles: {}", contentMap);
415 }
416 } catch (final IOException e) {
417 logger.warn("Failed to access groups/roles in AzureAD.", e);
418 }
419 }
420
421 protected void processParentGroup(final AzureAdUser user, final List<String> groupList, final List<String> roleList, final String id) {
422 final Pair<String[], String[]> groupsAndRoles = getParentGroup(user, id);
423 StreamUtil.stream(groupsAndRoles.getFirst()).of(stream -> stream.forEach(groupList::add));
424 StreamUtil.stream(groupsAndRoles.getSecond()).of(stream -> stream.forEach(roleList::add));
425 }
426
427 protected Pair<String[], String[]> getParentGroup(final AzureAdUser user, final String id) {
428 try {
429 return groupCache.get(
430 id,
431 () -> {
432 final List<String> groupList = new ArrayList<>();
433 final List<String> roleList = new ArrayList<>();
434 final String url = "https://graph.microsoft.com/v1.0/groups/" + id + "/getMemberGroups";
435 if (logger.isDebugEnabled()) {
436 logger.debug("url: {}", url);
437 }
438 try (CurlResponse response =
439 Curl.post(url).header("Authorization", "Bearer " + user.getAuthenticationResult().getAccessToken())
440 .header("Accept", "application/json").header("Content-type", "application/json")
441 .body("{\"securityEnabledOnly\":false}").execute()) {
442 final Map<String, Object> contentMap = response.getContent(EcrCurl.jsonParser());
443 if (logger.isDebugEnabled()) {
444 logger.debug("response: {}", contentMap);
445 }
446 if (contentMap.containsKey("value")) {
447 final String[] values = DocumentUtil.getValue(contentMap, "value", String[].class);
448 if (values != null) {
449 for (final String value : values) {
450 processGroup(user, groupList, roleList, value);
451 if (!groupList.contains(value) && !roleList.contains(value)) {
452 final Pair<String[], String[]> groupsAndRoles = getParentGroup(user, value);
453 StreamUtil.stream(groupsAndRoles.getFirst()).of(stream1 -> stream1.forEach(groupList::add));
454 StreamUtil.stream(groupsAndRoles.getSecond()).of(stream2 -> stream2.forEach(roleList::add));
455 }
456 }
457 }
458 } else if (contentMap.containsKey("error")) {
459 logger.warn("Failed to access parent groups: {}", contentMap);
460 }
461 } catch (final IOException e) {
462 logger.warn("Failed to access groups/roles in AzureAD.", e);
463 }
464 return new Pair<>(groupList.stream().distinct().toArray(n1 -> new String[n1]), roleList.stream().distinct()
465 .toArray(n2 -> new String[n2]));
466 });
467 } catch (final ExecutionException e) {
468 logger.warn("Failed to process a group cache.", e);
469 return new Pair<>(StringUtil.EMPTY_STRINGS, StringUtil.EMPTY_STRINGS);
470 }
471 }
472
473 protected void processGroup(final AzureAdUser user, final List<String> groupList, final List<String> roleList, final String id) {
474 final String url = "https://graph.microsoft.com/v1.0/groups/" + id;
475 if (logger.isDebugEnabled()) {
476 logger.debug("url: {}", url);
477 }
478 try (CurlResponse response =
479 Curl.get(url).header("Authorization", "Bearer " + user.getAuthenticationResult().getAccessToken())
480 .header("Accept", "application/json").execute()) {
481 final Map<String, Object> contentMap = response.getContent(EcrCurl.jsonParser());
482 if (logger.isDebugEnabled()) {
483 logger.debug("response: {}", contentMap);
484 }
485 groupList.add(id);
486 if (contentMap.containsKey("error")) {
487 logger.warn("Failed to access parent groups: {}", contentMap);
488 } else {
489 final String mail = (String) contentMap.get("mail");
490 if (StringUtil.isNotBlank(mail)) {
491 groupList.add(mail);
492 }
493 }
494 } catch (final IOException e) {
495 logger.warn("Failed to access groups/roles in AzureAD.", e);
496 }
497 }
498
499 protected List<String> getDefaultGroupList() {
500 final String value = ComponentUtil.getFessConfig().getSystemProperty("aad.default.groups");
501 if (StringUtil.isBlank(value)) {
502 return Collections.emptyList();
503 } else {
504 return split(value, ",").get(stream -> stream.filter(StringUtil::isNotBlank).map(s -> s.trim()).collect(Collectors.toList()));
505 }
506 }
507
508 protected List<String> getDefaultRoleList() {
509 final String value = ComponentUtil.getFessConfig().getSystemProperty("aad.default.roles");
510 if (StringUtil.isBlank(value)) {
511 return Collections.emptyList();
512 } else {
513 return split(value, ",").get(stream -> stream.filter(StringUtil::isNotBlank).map(s -> s.trim()).collect(Collectors.toList()));
514 }
515 }
516
517 protected class StateData {
518 private final String nonce;
519 private final long expiration;
520
521 public StateData(final String nonce, final long expiration) {
522 this.nonce = nonce;
523 this.expiration = expiration;
524 }
525
526 public String getNonce() {
527 return nonce;
528 }
529
530 public long getExpiration() {
531 return expiration;
532 }
533
534 @Override
535 public String toString() {
536 return "StateData [nonce=" + nonce + ", expiration=" + expiration + "]";
537 }
538 }
539
540 protected String getClientId() {
541 return ComponentUtil.getFessConfig().getSystemProperty(AZUREAD_CLIENT_ID, StringUtil.EMPTY);
542 }
543
544 protected String getClientSecret() {
545 return ComponentUtil.getFessConfig().getSystemProperty(AZUREAD_CLIENT_SECRET, StringUtil.EMPTY);
546 }
547
548 protected String getTenant() {
549 return ComponentUtil.getFessConfig().getSystemProperty(AZUREAD_TENANT, StringUtil.EMPTY);
550 }
551
552 protected String getAuthority() {
553 return ComponentUtil.getFessConfig().getSystemProperty(AZUREAD_AUTHORITY, "https://login.microsoftonline.com/");
554 }
555
556 protected long getStateTtl() {
557 return Long.parseLong(ComponentUtil.getFessConfig().getSystemProperty(AZUREAD_STATE_TTL, "3600"));
558 }
559
560 protected String getReplyUrl(final HttpServletRequest request) {
561 final String value = ComponentUtil.getFessConfig().getSystemProperty(AZUREAD_REPLY_URL, StringUtil.EMPTY);
562 if (StringUtil.isNotBlank(value)) {
563 return value;
564 }
565 return request.getRequestURL().toString();
566 }
567
568 @Override
569 public void resolveCredential(final LoginCredentialResolver resolver) {
570 resolver.resolve(AzureAdCredential.class, credential -> {
571 return OptionalEntity.of(credential.getUser());
572 });
573 }
574
575 public void setAcquisitionTimeout(final long acquisitionTimeout) {
576 this.acquisitionTimeout = acquisitionTimeout;
577 }
578
579 public void setGroupCacheExpiry(long groupCacheExpiry) {
580 this.groupCacheExpiry = groupCacheExpiry;
581 }
582 }