use of org.exist.security.AuthenticationException in project exist by eXist-db.
the class LDAPRealm method getAccount.
@Override
public final synchronized Account getAccount(String name) {
name = ensureCase(name);
// first attempt to get the cached account
final Account acct = super.getAccount(name);
if (acct != null) {
return acct;
} else {
LdapContext ctx = null;
try {
ctx = getContext(getSecurityManager().getDatabase().getActiveBroker().getCurrentSubject());
return getAccount(ctx, name);
} catch (final NamingException ne) {
if (LOG.isDebugEnabled()) {
LOG.debug(ne.getMessage(), ne);
}
LOG.error(new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage()));
return null;
} finally {
if (ctx != null) {
LdapUtils.closeContext(ctx);
}
}
}
}
use of org.exist.security.AuthenticationException in project exist by eXist-db.
the class LDAPRealm method findUsernamesWhereUsernameStarts.
@Override
public List<String> findUsernamesWhereUsernameStarts(final String startsWith) {
final String sWith = escapeSearchAttribute(ensureCase(startsWith));
final List<String> usernames = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = getContext(getSecurityManager().getCurrentSubject());
final LDAPSearchContext search = ensureContextFactory().getSearch();
final SearchAttribute sa = new SearchAttribute(search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.NAME), sWith + "*");
final String searchFilter = buildSearchFilter(search.getSearchAccount().getSearchFilterPrefix(), sa);
final SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setReturningAttributes(new String[] { search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.NAME) });
final NamingEnumeration<SearchResult> results = ctx.search(search.getBase(), searchFilter, searchControls);
while (results.hasMoreElements()) {
final SearchResult searchResult = results.nextElement();
final String username = ensureCase(addDomainPostfix((String) searchResult.getAttributes().get(search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.NAME)).get()));
if (checkAccountRestrictionList(username)) {
usernames.add(username);
}
}
} catch (final NamingException ne) {
LOG.error(new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage()));
} finally {
if (ctx != null) {
LdapUtils.closeContext(ctx);
}
}
return usernames;
}
use of org.exist.security.AuthenticationException in project exist by eXist-db.
the class LDAPRealm method createAccountInDatabase.
private Account createAccountInDatabase(final LdapContext ctx, final String username, final SearchResult ldapUser, final String primaryGroupName) throws AuthenticationException {
try {
return executeAsSystemUser(ctx, (ctx2, broker) -> {
if (LOG.isDebugEnabled()) {
LOG.debug("Saving account '{}'.", username);
}
// get (or create) the primary group if it doesnt exist
final Group primaryGroup = getGroup(ctx, broker, primaryGroupName);
// get (or create) member groups
/*LDAPSearchContext search = ensureContextFactory().getSearch();
String userDistinguishedName = (String)ldapUser.getAttributes().get(search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.DN)).get();
List<String> memberOf_groupNames = findGroupnamesForUserDistinguishedName(invokingUser, userDistinguishedName);
List<Group> memberOf_groups = new ArrayList<Group>();
for(String memberOf_groupName : memberOf_groupNames) {
memberOf_groups.add(getGroup(invokingUser, memberOf_groupName));
}*/
// create the user account
final UserAider userAider = new UserAider(ID, username, primaryGroup);
// add the member groups
for (final Group memberOf_group : getGroupMembershipForLdapUser(ctx, broker, ldapUser)) {
userAider.addGroup(memberOf_group);
}
// store any requested metadata
for (final SimpleEntry<AXSchemaType, String> metadata : getMetadataForLdapUser(ldapUser)) {
userAider.setMetadataValue(metadata.getKey(), metadata.getValue());
}
final Account account = getSecurityManager().addAccount(userAider);
return account;
});
} catch (final Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug(e);
}
throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e.getMessage(), e);
}
}
use of org.exist.security.AuthenticationException in project exist by eXist-db.
the class LDAPRealm method getGroup.
public final synchronized Group getGroup(final Subject invokingUser, final DBBroker broker, String name) {
name = ensureCase(name);
final Group grp = getGroup(name);
if (grp != null) {
return grp;
} else {
// if the group is not cached, we should try and find it in LDAP and cache it if it exists
LdapContext ctx = null;
try {
ctx = getContext(invokingUser);
return getGroup(ctx, broker, name);
} catch (final NamingException ne) {
LOG.error(new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage()));
return null;
} finally {
if (ctx != null) {
LdapUtils.closeContext(ctx);
}
}
}
}
use of org.exist.security.AuthenticationException in project exist by eXist-db.
the class XQueryServlet method process.
/**
* Processes incoming HTTP requests for XQuery.
*
* @param request the http request
* @param response the http response
*
* @throws ServletException if the servlet raises an exception
* @throws IOException if an I/O error occurs
*/
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// first, adjust the path
String path = request.getPathTranslated();
if (path == null) {
path = request.getRequestURI().substring(request.getContextPath().length());
final int p = path.lastIndexOf(';');
if (p != Constants.STRING_NOT_FOUND) {
path = path.substring(0, p);
}
path = getServletContext().getRealPath(path);
}
// second, perform descriptor actions
final Descriptor descriptor = Descriptor.getDescriptorSingleton();
if (descriptor != null && !descriptor.requestsFiltered()) {
// logs the request if specified in the descriptor
descriptor.doLogRequestInReplayLog(request);
// map's the path if a mapping is specified in the descriptor
path = descriptor.mapPath(path);
}
// if (request.getCharacterEncoding() == null)
// try {
// request.setCharacterEncoding(formEncoding);
// } catch (IllegalStateException e) {
// }
final ServletOutputStream sout = response.getOutputStream();
final PrintWriter output = new PrintWriter(new OutputStreamWriter(sout, getFormEncoding()));
// response.setContentType(contentType + "; charset=" + formEncoding);
response.addHeader("pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
String requestPath = request.getRequestURI();
final int p = requestPath.lastIndexOf('/');
if (p != Constants.STRING_NOT_FOUND) {
requestPath = requestPath.substring(0, p);
}
String moduleLoadPath;
final Object loadPathAttrib = request.getAttribute(ATTR_MODULE_LOAD_PATH);
if (loadPathAttrib != null) {
moduleLoadPath = getValue(loadPathAttrib);
} else {
moduleLoadPath = getServletContext().getRealPath(requestPath.substring(request.getContextPath().length()));
}
Subject user = getDefaultUser();
// to determine the user, first check the request attribute "xquery.user", then
// the current session attribute "user"
final Object userAttrib = request.getAttribute(ATTR_XQUERY_USER);
final HttpSession session = request.getSession(false);
if (userAttrib != null || (session != null && request.isRequestedSessionIdValid())) {
final Object passwdAttrib = request.getAttribute(ATTR_XQUERY_PASSWORD);
String username;
String password;
if (userAttrib != null) {
username = getValue(userAttrib);
password = getValue(passwdAttrib);
} else {
username = getSessionAttribute(session, "user");
password = getSessionAttribute(session, "password");
}
// TODO authentication should use super.authenticate(...) !!!
try {
if (username != null && password != null) {
Subject newUser = getPool().getSecurityManager().authenticate(username, password);
if (newUser != null && newUser.isAuthenticated()) {
user = newUser;
}
}
} catch (final AuthenticationException e) {
getLog().error("User can not be authenticated ({}).", username);
}
}
if (user == getDefaultUser()) {
Subject requestUser = HttpAccount.getUserFromServletRequest(request);
if (requestUser != null) {
user = requestUser;
} else {
requestUser = getAuthenticator().authenticate(request, response, false);
if (requestUser != null) {
user = requestUser;
}
}
}
Source source = null;
final Object sourceAttrib = request.getAttribute(ATTR_XQUERY_SOURCE);
final Object urlAttrib = request.getAttribute(ATTR_XQUERY_URL);
if (sourceAttrib != null) {
String s;
if (sourceAttrib instanceof Item)
try {
s = ((Item) sourceAttrib).getStringValue();
} catch (final XPathException e) {
throw new ServletException("Failed to read XQuery source string from " + "request attribute '" + ATTR_XQUERY_SOURCE + "': " + e.getMessage(), e);
}
else {
s = sourceAttrib.toString();
}
source = new StringSource(s);
} else if (urlAttrib != null) {
try (final DBBroker broker = getPool().get(Optional.ofNullable(user))) {
source = SourceFactory.getSource(broker, moduleLoadPath, urlAttrib.toString(), true);
if (source == null) {
final String msg = "Could not read source: context=" + moduleLoadPath + ", location=" + urlAttrib.toString();
getLog().error(msg);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", msg);
}
} catch (final Exception e) {
getLog().error(e.getMessage(), e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", e.getMessage());
}
} else {
final Path f = Paths.get(path);
if (!Files.isReadable(f)) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
sendError(output, "Cannot read source file", path);
return;
}
source = new FileSource(f, Charset.forName(encoding), true);
}
if (source == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
sendError(output, "Source not found", path);
}
boolean reportErrors = false;
final String errorOpt = (String) request.getAttribute(ATTR_XQUERY_REPORT_ERRORS);
if (errorOpt != null) {
reportErrors = errorOpt.equalsIgnoreCase("YES");
}
// allow source viewing for GET?
if ("GET".equals(request.getMethod().toUpperCase())) {
String option;
boolean allowSource = false;
if ((option = request.getParameter("_source")) != null)
allowSource = "yes".equals(option);
// Should we display the source of the XQuery or execute it
if (allowSource && descriptor != null) {
// System.out.println("path="+path);
if (descriptor.allowSource(path)) {
if (source instanceof DBSource) {
try {
((DBSource) source).validate(user, Permission.READ);
} catch (final PermissionDeniedException e) {
if (getDefaultUser().equals(user)) {
getAuthenticator().sendChallenge(request, response);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission to view XQuery source for: " + path + " denied. (no read access)");
}
return;
}
}
// Show the source of the XQuery
// writeResourceAs(resource, broker, stylesheet, encoding, "text/plain", outputProperties, response);
response.setContentType("text/plain; charset=" + getFormEncoding());
output.write(source.getContent());
output.flush();
return;
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Permission to view XQuery source for: " + path + " denied. Must be explicitly defined in descriptor.xml");
return;
}
}
}
// -------------------------------
// URI baseUri;
// try {
// baseUri = new URI(request.getScheme(),
// null/*user info?*/, request.getLocalPart(), request.getLocalPort(),
// request.getRequestURI(), null, null);
// } catch(URISyntaxException e) {
// baseUri = null;
// }
final String requestAttr = (String) request.getAttribute(ATTR_XQUERY_ATTRIBUTE);
try (final DBBroker broker = getPool().get(Optional.ofNullable(user))) {
final XQuery xquery = broker.getBrokerPool().getXQueryService();
CompiledXQuery query = getPool().getXQueryPool().borrowCompiledXQuery(broker, source);
XQueryContext context;
if (query == null) {
context = new XQueryContext(getPool());
context.setModuleLoadPath(moduleLoadPath);
try {
query = xquery.compile(context, source);
} catch (final XPathException ex) {
throw new EXistException("Cannot compile xquery: " + ex.getMessage(), ex);
} catch (final IOException ex) {
throw new EXistException("I/O exception while compiling xquery: " + ex.getMessage(), ex);
}
} else {
context = query.getContext();
context.setModuleLoadPath(moduleLoadPath);
context.prepareForReuse();
}
final Properties outputProperties = new Properties();
outputProperties.put("base-uri", collectionURI.toString());
final HttpRequestWrapper reqw = new HttpRequestWrapper(request, getFormEncoding(), getContainerEncoding());
final ResponseWrapper respw = new HttpResponseWrapper(response);
context.setHttpContext(new XQueryContext.HttpContext(reqw, respw, session != null ? new HttpSessionWrapper(session) : null));
final String timeoutOpt = (String) request.getAttribute(ATTR_TIMEOUT);
if (timeoutOpt != null) {
try {
final long timeout = Long.parseLong(timeoutOpt);
context.getWatchDog().setTimeout(timeout);
} catch (final NumberFormatException e) {
throw new EXistException("Bad timeout option: " + timeoutOpt);
}
}
final String maxNodesOpt = (String) request.getAttribute(ATTR_MAX_NODES);
if (maxNodesOpt != null) {
try {
final int maxNodes = Integer.parseInt(maxNodesOpt);
context.getWatchDog().setMaxNodes(maxNodes);
} catch (final NumberFormatException e) {
throw new EXistException("Bad max-nodes option: " + maxNodesOpt);
}
}
DebuggeeFactory.checkForDebugRequest(request, context);
Sequence resultSequence;
try {
resultSequence = xquery.execute(broker, query, null, outputProperties);
} finally {
context.runCleanupTasks();
getPool().getXQueryPool().returnCompiledXQuery(source, query);
}
final String mediaType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
if (mediaType != null) {
if (!response.isCommitted()) {
if (MimeTable.getInstance().isTextContent(mediaType)) {
response.setContentType(mediaType + "; charset=" + getFormEncoding());
response.setCharacterEncoding(getFormEncoding());
} else
response.setContentType(mediaType);
}
} else {
String contentType = this.contentType;
try {
contentType = getServletContext().getMimeType(path);
if (contentType == null) {
contentType = this.contentType;
}
} catch (final Throwable e) {
contentType = this.contentType;
} finally {
if (MimeTable.getInstance().isTextContent(contentType)) {
contentType += "; charset=" + getFormEncoding();
}
response.setContentType(contentType);
}
}
if (requestAttr != null && (XmldbURI.API_LOCAL.equals(collectionURI.getApiName()))) {
request.setAttribute(requestAttr, resultSequence);
} else {
XQuerySerializer serializer = new XQuerySerializer(broker, outputProperties, output);
serializer.serialize(resultSequence);
}
} catch (final PermissionDeniedException e) {
if (getDefaultUser().equals(user)) {
getAuthenticator().sendChallenge(request, response);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "No permission to execute XQuery for: " + path + " denied.");
}
return;
} catch (final XPathException e) {
final Logger logger = getLog();
if (logger.isDebugEnabled()) {
logger.debug(e.getMessage(), e);
}
if (reportErrors) {
writeError(output, e);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", e.getMessage());
}
} catch (final Throwable e) {
getLog().error(e.getMessage(), e);
if (reportErrors) {
writeError(output, e);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
sendError(output, "Error", e.getMessage());
}
}
output.flush();
output.close();
}
Aggregations