/**
  * Create credentials from a validated userId.
  *
  * @param req The request to sniff for a user.
  * @return
  */
 private Credentials createCredentials(String userId, String tokenType) {
   SimpleCredentials sc = new SimpleCredentials(userId, new char[0]);
   TrustedUser user = new TrustedUser(userId);
   sc.setAttribute(CA_AUTHENTICATION_USER, user);
   sc.setAttribute(CA_AUTHENTICATION_ATTRIBUTES, tokenType);
   return sc;
 }
Exemple #2
0
  /** @see FlowService#executeJob(String, String, String, long, long, String) */
  @Override
  public Job executeJob(
      Credentials credentials,
      String token,
      String name,
      String description,
      long flowInstanceId,
      long userId,
      String userEmail) {
    FlowDao flowDao = daoFactory.getFlowDao();
    JobDao jobDao = daoFactory.getJobDao();

    Flow flowInstance = flowDao.findById(flowInstanceId, false);

    Job job = new Job();
    job.setToken(token);
    job.setName(name);
    job.setDescription(description);
    job.setFlow(flowInstance);
    job.setOwnerId(userId);
    job.setOwnerEmail(userEmail);
    SimpleCredentials simpleCreds = (SimpleCredentials) credentials;
    String serializedCreds = simpleCreds.getUserID() + ":" + new String(simpleCreds.getPassword());
    job.setCredentials(serializedCreds);
    jobDao.makePersistent(job);

    jobScheduler.scheduleJob(job);
    job.setJobStatus(JobStatus.SCHEDULED);
    job.setScheduleTimestamp(new Date());
    jobDao.makePersistent(job);

    jobStatusMonitor.start(job, notificationCreator);

    return job;
  }
  @Test
  public void testGetCredentialsValid() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Cookie[] cookies =
        new Cookie[] {
          new Cookie("sdfsd", "fsdfs"),
          new Cookie("sdfsd1", "fsdfs"),
          null,
          new Cookie("sdfsd3", "fsdfs"),
          new Cookie("sdfsd4", "fsdfs"),
        };
    EasyMock.expect(request.getCookies()).andReturn(cookies);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    replay();
    trustedTokenService.activate(context);
    Cookie secureCookie = new Cookie("secure-cookie", trustedTokenService.encodeCookie("ieb"));
    cookies[2] = secureCookie;
    Credentials ieb = trustedTokenService.getCredentials(request, response);
    Assert.assertTrue(ieb instanceof SimpleCredentials);
    SimpleCredentials sc = (SimpleCredentials) ieb;
    TrustedUser tu = (TrustedUser) sc.getAttribute(TrustedTokenService.CA_AUTHENTICATION_USER);
    Assert.assertNotNull(tu);
    Assert.assertEquals("ieb", tu.getUser());
    verify();
  }
  public void testGetPassword2() throws NoSuchAlgorithmException, UnsupportedEncodingException {
    CryptedSimpleCredentials prev = cCreds.get(0);
    // build crypted credentials from the uid and the crypted pw contained
    // in simple credentials -> simple-c-password must be treated plain-text
    SimpleCredentials sc = new SimpleCredentials(userID, prev.getPassword().toCharArray());
    CryptedSimpleCredentials diff = new CryptedSimpleCredentials(sc);

    assertFalse(prev.getPassword().equals(diff.getPassword()));
    assertFalse(String.valueOf(sc.getPassword()).equals(diff.getPassword()));
  }
 public void logout() {
   for (Session session : sessions.values()) {
     session.logout();
   }
   if (credentials instanceof SimpleCredentials) {
     SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
     JahiaLoginModule.removeToken(
         simpleCredentials.getUserID(), new String(simpleCredentials.getPassword()));
   }
   isLive = false;
   activeSessions.decrementAndGet();
 }
  /**
   * {@inheritDoc}
   *
   * <p>Creates a {@code UsernamePasswordAuthenticationToken} from the given {@code principal} and
   * {@code credentials} and passes to Spring Security {@code AuthenticationManager}.
   */
  @Override
  protected Authentication getAuthentication(
      final Principal principal, final Credentials credentials) throws RepositoryException {

    // only handles SimpleCredential instances; DefaultLoginModule behaves the same way (albeit
    // indirectly)
    if (!(credentials instanceof SimpleCredentials)) {
      logger.debug("credentials not instance of SimpleCredentials; returning null"); // $NON-NLS-1$
      return null;
    }

    SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;

    UsernamePasswordAuthenticationToken token =
        new UsernamePasswordAuthenticationToken(
            simpleCredentials.getUserID(), String.valueOf(simpleCredentials.getPassword()));

    boolean authenticated = false;

    try {
      org.springframework.security.Authentication authentication =
          SecurityContextHolder.getContext().getAuthentication();
      if (authentication != null
          && authentication.getName().equals(simpleCredentials.getUserID())) {
        // see if there's already an active Authentication for this user.
        authenticated = true;
      } else {
        // delegate to Spring Security
        getAuthenticationManager().authenticate(token);
        authenticated = true;
      }
    } catch (AuthenticationException e) {
      logger.debug("authentication exception", e); // $NON-NLS-1$
    }

    final boolean authenticateResult = authenticated;

    return new Authentication() {
      public boolean canHandle(Credentials credentials) {
        // this is decided earlier in getAuthentication
        return true;
      }

      public boolean authenticate(Credentials credentials) throws RepositoryException {
        return authenticateResult;
      }
    };
  }
  @Override
  public boolean login() throws LoginException {
    Credentials credentials = getCredentials();
    if (!(credentials instanceof SimpleCredentials)) {
      return super.login();
    }

    Principal principal = getPrincipal(credentials);
    if (principal == null) {
      SimpleCredentials cred = (SimpleCredentials) credentials;
      if (!createLogin(getUserID(credentials), String.valueOf(cred.getPassword()))) {
        return false;
      }
    }

    return super.login();
  }
  public Session getProviderSession(JCRStoreProvider provider) throws RepositoryException {
    if (sessions.get(provider) == null) {
      Session s = null;

      if (credentials instanceof SimpleCredentials) {
        SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
        JahiaLoginModule.Token t =
            JahiaLoginModule.getToken(
                simpleCredentials.getUserID(), new String(simpleCredentials.getPassword()));

        s = provider.getSession(credentials, workspace.getName());

        credentials =
            JahiaLoginModule.getCredentials(
                simpleCredentials.getUserID(), t != null ? t.deniedPath : null);
      } else {
        s = provider.getSession(credentials, workspace.getName());
      }

      sessions.put(provider, s);
      for (String token : tokens) {
        s.addLockToken(token);
      }

      NamespaceRegistry namespaceRegistryWrapper = getWorkspace().getNamespaceRegistry();
      NamespaceRegistry providerNamespaceRegistry = s.getWorkspace().getNamespaceRegistry();

      if (providerNamespaceRegistry != null) {
        for (String prefix : namespaceRegistryWrapper.getPrefixes()) {
          try {
            providerNamespaceRegistry.getURI(prefix);
          } catch (NamespaceException ne) {
            providerNamespaceRegistry.registerNamespace(
                prefix, namespaceRegistryWrapper.getURI(prefix));
          }
        }
      }

      for (String prefix : prefixToNs.keySet()) {
        s.setNamespacePrefix(prefix, prefixToNs.get(prefix));
      }
    }
    return sessions.get(provider);
  }
 @Override
 protected boolean isPreAuthenticated(final Credentials creds) {
   if (super.isPreAuthenticated(creds)) {
     SimpleCredentials simpleCreds = (SimpleCredentials) creds;
     String preAuth = (String) simpleCreds.getAttribute(getPreAuthAttributeName());
     boolean preAuthenticated = preAuthenticationTokens.contains(preAuth);
     if (preAuthenticated) {
       if (logger.isDebugEnabled()) {
         logger.debug(simpleCreds.getUserID() + " is pre-authenticated"); // $NON-NLS-1$
       }
     } else {
       if (logger.isDebugEnabled()) {
         logger.debug("pre-authentication token rejected"); // $NON-NLS-1$
       }
     }
     return preAuthenticated;
   }
   return false;
 }
  @Override
  protected String getUserID(Credentials credentials) {
    if (!(credentials instanceof SimpleCredentials)) {
      return super.getUserID(credentials);
    }

    SimpleCredentials cred = (SimpleCredentials) credentials;
    String id = cred.getUserID();
    if (id == null) {
      return super.getUserID(credentials);
    }

    String key = id + String.valueOf(cred.getPassword());
    String userId = ids.get(key);
    if (userId != null) {
      return userId;
    }

    boolean realId = false;
    Object realIdAttr = cred.getAttribute(JackrabbitConstants.REAL_USER_ID_USED);
    if (realIdAttr instanceof String) {
      realId = Boolean.valueOf((String) realIdAttr);
    }

    if (!realId) {
      try {
        LoginTable loginTable = LoginDBHandler.getUserLoginByUserName(id);
        userId = loginTable == null ? null : String.valueOf(loginTable.getUserId());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (userId == null) {
      userId = super.getUserID(credentials);
    }

    if (userId != null) {
      ids.put(key, userId);
    }

    return userId;
  }
  @Test
  public void testGetCredentialsValidSession() {
    ComponentContext context = configureForSession();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpSession session = createMock(HttpSession.class);
    EasyMock.expect(request.getSession(true)).andReturn(session);

    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn(null);
    EasyMock.expect(request.getRemoteUser()).andReturn("ieb");
    Capture<SimpleCredentials> attributeValue = new Capture<SimpleCredentials>();
    Capture<String> attributeName = new Capture<String>();
    session.setAttribute(EasyMock.capture(attributeName), EasyMock.capture(attributeValue));

    HttpServletResponse response = createMock(HttpServletResponse.class);

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response);
    Assert.assertTrue(attributeName.hasCaptured());
    Assert.assertTrue(attributeValue.hasCaptured());
    Credentials credentials = attributeValue.getValue();

    verify();
    reset();

    EasyMock.expect(request.getSession(false)).andReturn(session);
    EasyMock.expect(session.getAttribute(TrustedTokenService.SA_AUTHENTICATION_CREDENTIALS))
        .andReturn(credentials);

    replay();
    Credentials ieb = trustedTokenService.getCredentials(request, response);
    Assert.assertTrue(ieb instanceof SimpleCredentials);
    SimpleCredentials sc = (SimpleCredentials) ieb;
    TrustedUser tu = (TrustedUser) sc.getAttribute(TrustedTokenService.CA_AUTHENTICATION_USER);
    Assert.assertNotNull(tu);
    Assert.assertEquals("ieb", tu.getUser());
    verify();
  }
 /**
  * Method tries to acquire an Impersonator in the following order:
  *
  * <ul>
  *   <li>Try to access it from the {@link Credentials} via {@link
  *       SimpleCredentials#getAttribute(String)}
  *   <li>Ask CallbackHandler for Impersonator with use of {@link ImpersonationCallback}.
  * </ul>
  *
  * @param credentials which, may contain an impersonation Subject
  * @return impersonation subject or null if non contained
  * @see #login()
  * @see #impersonate(java.security.Principal, javax.jcr.Credentials)
  */
 protected Subject getImpersonatorSubject(Credentials credentials) {
   Subject impersonator = null;
   if (credentials == null) {
     try {
       ImpersonationCallback impers = new ImpersonationCallback();
       callbackHandler.handle(new Callback[] {impers});
       impersonator = impers.getImpersonator();
     } catch (UnsupportedCallbackException e) {
       log.warn(
           e.getCallback().getClass().getName()
               + " not supported: Unable to perform Impersonation.");
     } catch (IOException e) {
       log.error(
           "Impersonation-Callback failed: "
               + e.getMessage()
               + ": Unable to perform Impersonation.");
     }
   } else if (credentials instanceof SimpleCredentials) {
     SimpleCredentials sc = (SimpleCredentials) credentials;
     impersonator = (Subject) sc.getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE);
   }
   return impersonator;
 }
  /**
   * Extract credentials from the request.
   *
   * @param req
   * @return credentials associated with the request.
   */
  public Credentials getCredentials(HttpServletRequest req, HttpServletResponse response) {
    if (testing) {
      calls.add(new Object[] {"getCredentials", req, response});
      return new SimpleCredentials("testing", "testing".toCharArray());
    }
    Credentials cred = null;
    String userId = null;
    String sakaiTrustedHeader = req.getHeader("x-sakai-token");
    if (trustedTokenEnabled
        && sakaiTrustedHeader != null
        && sakaiTrustedHeader.trim().length() > 0) {
      String host = req.getRemoteAddr();
      if (!safeHostAddrSet.contains(host)) {
        LOG.warn("Ignoring Trusted Token request from {} ", host);
      } else {
        // we have a HMAC based token, we should see if it is valid against the key we
        // have
        // and if so create some credentials.
        String[] parts = sakaiTrustedHeader.split(";");
        if (parts.length == 3) {
          try {
            String hash = parts[0];
            String user = parts[1];
            String timestamp = parts[2];
            String hmac = Signature.calculateRFC2104HMAC(user + ";" + timestamp, sharedSecret);
            if (hmac.equals(hash)) {
              // the user is Ok, we will trust it.
              userId = user;
              cred = createCredentials(userId, TrustedTokenTypes.TRUSTED_TOKEN);
            } else {
              LOG.debug("HMAC Match Failed {} != {} ", hmac, hash);
            }
          } catch (SignatureException e) {
            LOG.warn(
                "Failed to validate server token : {} {} ", sakaiTrustedHeader, e.getMessage());
          }
        } else {
          LOG.warn(
              "Illegal number of elements in trusted server token:{} {}  ",
              sakaiTrustedHeader,
              parts.length);
        }
      }
    }
    if (userId == null) {
      if (usingSession) {
        HttpSession session = req.getSession(false);
        if (session != null) {
          Credentials testCredentials =
              (Credentials) session.getAttribute(SA_AUTHENTICATION_CREDENTIALS);
          if (testCredentials instanceof SimpleCredentials) {
            SimpleCredentials sc = (SimpleCredentials) testCredentials;
            Object o = sc.getAttribute(CA_AUTHENTICATION_USER);
            if (o instanceof TrustedUser) {
              TrustedUser tu = (TrustedUser) o;
              if (tu.getUser() != null) {
                userId = tu.getUser();
                cred = testCredentials;
              }
            }
          }
        } else {
          cred = null;
        }
      } else {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
          for (Cookie c : cookies) {
            if (trustedAuthCookieName.equals(c.getName())) {
              if (secureCookie && !c.getSecure()) {
                continue;
              }
              String cookieValue = c.getValue();
              String[] decodedToken = decodeCookie(c.getValue());
              if (decodedToken != null) {
                userId = decodedToken[0];
                String tokenType = decodedToken[1];
                TokenTrustValidator ttv = registeredTypes.get(tokenType);
                if (ttv == null || ttv.isTrusted(req)) {
                  LOG.debug("Token is valid and decoded to {} ", userId);
                  cred = createCredentials(userId, tokenType);
                  refreshToken(response, c.getValue(), userId, tokenType);
                  break;
                } else {
                  LOG.debug("Cookie cant be trusted for this request {} ", cookieValue);
                }
              } else {
                LOG.debug("Invalid Cookie {} ", cookieValue);
                clearCookie(response);
              }
            }
          }
        }
      }
    }
    if (userId != null) {
      LOG.debug("Trusted Authentication for {} with credentials {}  ", userId, cred);
    }

    return cred;
  }