org.apache.hadoop.security.authorize.AuthorizationException Java Examples

The following examples show how to use org.apache.hadoop.security.authorize.AuthorizationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Server.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize the incoming client connection.
 * 
 * @param user client user
 * @param protocolName - the protocol
 * @param addr InetAddress of incoming connection
 * @throws AuthorizationException when the client isn't authorized to talk the protocol
 */
private void authorize(UserGroupInformation user, String protocolName,
    InetAddress addr) throws AuthorizationException {
  if (authorize) {
    if (protocolName == null) {
      throw new AuthorizationException("Null protocol not authorized");
    }
    Class<?> protocol = null;
    try {
      protocol = getProtocolClass(protocolName, getConf());
    } catch (ClassNotFoundException cfne) {
      throw new AuthorizationException("Unknown protocol: " + 
                                       protocolName);
    }
    serviceAuthorizationManager.authorize(user, protocol, getConf(), addr);
  }
}
 
Example #2
Source File: RMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/apps/{appid}/state")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppState getAppState(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) throws AuthorizationException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  String userName = "";
  if (callerUGI != null) {
    userName = callerUGI.getUserName();
  }
  RMApp app = null;
  try {
    app = getRMAppForAppId(appId);
  } catch (NotFoundException e) {
    RMAuditLogger.logFailure(userName, AuditConstants.KILL_APP_REQUEST,
      "UNKNOWN", "RMWebService",
      "Trying to get state of an absent application " + appId);
    throw e;
  }

  AppState ret = new AppState();
  ret.setState(app.getState().toString());

  return ret;
}
 
Example #3
Source File: RMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/delegation-token/expiration")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response
    postDelegationTokenExpiration(@Context HttpServletRequest hsr)
        throws AuthorizationException, IOException, InterruptedException,
        Exception {

  init();
  UserGroupInformation callerUGI;
  try {
    callerUGI = createKerberosUserGroupInformation(hsr);
  } catch (YarnException ye) {
    return Response.status(Status.FORBIDDEN).entity(ye.getMessage()).build();
  }

  DelegationToken requestToken = new DelegationToken();
  requestToken.setToken(extractToken(hsr).encodeToUrlString());
  return renewDelegationToken(requestToken, hsr, callerUGI);
}
 
Example #4
Source File: ServerRpcConnection.java    From hbase with Apache License 2.0 6 votes vote down vote up
private boolean authorizeConnection() throws IOException {
  try {
    // If auth method is DIGEST, the token was obtained by the
    // real user for the effective user, therefore not required to
    // authorize real user. doAs is allowed only for simple or kerberos
    // authentication
    if (ugi != null && ugi.getRealUser() != null
        && provider.supportsProtocolAuthentication()) {
      ProxyUsers.authorize(ugi, this.getHostAddress(), this.rpcServer.conf);
    }
    this.rpcServer.authorize(ugi, connectionHeader, getHostInetAddress());
    this.rpcServer.metrics.authorizationSuccess();
  } catch (AuthorizationException ae) {
    if (RpcServer.LOG.isDebugEnabled()) {
      RpcServer.LOG.debug("Connection authorization failed: " + ae.getMessage(), ae);
    }
    this.rpcServer.metrics.authorizationFailure();
    doRespond(getErrorResponse(ae.getMessage(), new AccessDeniedException(ae)));
    return false;
  }
  return true;
}
 
Example #5
Source File: RMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/apps/{appid}/queue")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppQueue getAppQueue(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) throws AuthorizationException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  String userName = "UNKNOWN-USER";
  if (callerUGI != null) {
    userName = callerUGI.getUserName();
  }
  RMApp app = null;
  try {
    app = getRMAppForAppId(appId);
  } catch (NotFoundException e) {
    RMAuditLogger.logFailure(userName, AuditConstants.KILL_APP_REQUEST,
      "UNKNOWN", "RMWebService",
      "Trying to get state of an absent application " + appId);
    throw e;
  }

  AppQueue ret = new AppQueue();
  ret.setQueue(app.getQueue());

  return ret;
}
 
Example #6
Source File: RMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a new ApplicationId which is then sent to the client
 * 
 * @param hsr
 *          the servlet request
 * @return Response containing the app id and the maximum resource
 *         capabilities
 * @throws AuthorizationException
 * @throws IOException
 * @throws InterruptedException
 */
@POST
@Path("/apps/new-application")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createNewApplication(@Context HttpServletRequest hsr)
    throws AuthorizationException, IOException, InterruptedException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  if (callerUGI == null) {
    throw new AuthorizationException("Unable to obtain user name, "
        + "user not authenticated");
  }
  if (UserGroupInformation.isSecurityEnabled() && isStaticUser(callerUGI)) {
    String msg = "The default static user cannot carry out this operation.";
    return Response.status(Status.FORBIDDEN).entity(msg).build();
  }

  NewApplication appId = createNewApplication();
  return Response.status(Status.OK).entity(appId).build();

}
 
Example #7
Source File: RMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/delegation-token")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response postDelegationToken(DelegationToken tokenData,
    @Context HttpServletRequest hsr) throws AuthorizationException,
    IOException, InterruptedException, Exception {

  init();
  UserGroupInformation callerUGI;
  try {
    callerUGI = createKerberosUserGroupInformation(hsr);
  } catch (YarnException ye) {
    return Response.status(Status.FORBIDDEN).entity(ye.getMessage()).build();
  }
  return createDelegationToken(tokenData, hsr, callerUGI);
}
 
Example #8
Source File: KeyAuthorizationKeyProvider.java    From ranger with Apache License 2.0 6 votes vote down vote up
private void authorizeCreateKey(String keyName, Options options,
    UserGroupInformation ugi) throws IOException{
  Preconditions.checkNotNull(ugi, "UserGroupInformation cannot be null");
  Map<String, String> attributes = options.getAttributes();
  String aclName = attributes.get(KEY_ACL_NAME);
  boolean success = false;
  if (Strings.isNullOrEmpty(aclName)) {
    if (acls.isACLPresent(keyName, KeyOpType.MANAGEMENT)) {
      options.setAttributes(ImmutableMap.<String, String> builder()
          .putAll(attributes).put(KEY_ACL_NAME, keyName).build());
      success =
          acls.hasAccessToKey(keyName, ugi, KeyOpType.MANAGEMENT)
              || acls.hasAccessToKey(keyName, ugi, KeyOpType.ALL);
    } else {
      success = false;
    }
  } else {
    success = acls.isACLPresent(aclName, KeyOpType.MANAGEMENT) &&
        (acls.hasAccessToKey(aclName, ugi, KeyOpType.MANAGEMENT)
        || acls.hasAccessToKey(aclName, ugi, KeyOpType.ALL));
  }
  if (!success)
    throw new AuthorizationException(String.format("User [%s] is not"
        + " authorized to create key !!", ugi.getShortUserName()));
}
 
Example #9
Source File: RangerKmsAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public void assertAccess(Type aclType, UserGroupInformation ugi, KMSOp operation, String key, String clientIp)
    throws AccessControlException {
   if(LOG.isDebugEnabled()) {
	LOG.debug("==> RangerKmsAuthorizer.assertAccess(" + key + ", " + ugi +", " + aclType + ")");
}
 	key = (key == null)?"":key;
 	if (!hasAccess(aclType, ugi, key, clientIp)) {
 		KMSWebApp.getUnauthorizedCallsMeter().mark();
 		KMSWebApp.getKMSAudit().unauthorized(ugi, operation, key);
 		throw new AuthorizationException(String.format(
 				(!key.equals("")) ? UNAUTHORIZED_MSG_WITH_KEY
                      : UNAUTHORIZED_MSG_WITHOUT_KEY,
                      ugi.getShortUserName(), operation, key));
 	}
}
 
Example #10
Source File: KeyAuthorizationKeyProvider.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void authorizeCreateKey(String keyName, Options options,
    UserGroupInformation ugi) throws IOException{
  Preconditions.checkNotNull(ugi, "UserGroupInformation cannot be null");
  Map<String, String> attributes = options.getAttributes();
  String aclName = attributes.get(KEY_ACL_NAME);
  boolean success = false;
  if (Strings.isNullOrEmpty(aclName)) {
    if (acls.isACLPresent(keyName, KeyOpType.MANAGEMENT)) {
      options.setAttributes(ImmutableMap.<String, String> builder()
          .putAll(attributes).put(KEY_ACL_NAME, keyName).build());
      success =
          acls.hasAccessToKey(keyName, ugi, KeyOpType.MANAGEMENT)
              || acls.hasAccessToKey(keyName, ugi, KeyOpType.ALL);
    } else {
      success = false;
    }
  } else {
    success = acls.isACLPresent(aclName, KeyOpType.MANAGEMENT) &&
        (acls.hasAccessToKey(aclName, ugi, KeyOpType.MANAGEMENT)
        || acls.hasAccessToKey(aclName, ugi, KeyOpType.ALL));
  }
  if (!success)
    throw new AuthorizationException(String.format("User [%s] is not"
        + " authorized to create key !!", ugi.getShortUserName()));
}
 
Example #11
Source File: TestRMProxyUsersConf.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testProxyUserConfiguration() throws Exception {
  MockRM rm = null;
  try {
    rm = new MockRM(conf);
    rm.start();
    // wait for web server starting
    Thread.sleep(10000);
    UserGroupInformation proxyUser =
        UserGroupInformation.createProxyUser(
            BAR_USER.getShortUserName(), FOO_USER);
    try {
      ProxyUsers.getDefaultImpersonationProvider().authorize(proxyUser,
          ipAddress);
    } catch (AuthorizationException e) {
      // Exception is not expected
      Assert.fail();
    }
  } finally {
    if (rm != null) {
      rm.stop();
      rm.close();
    }
  }
}
 
Example #12
Source File: ApplicationHistoryManagerOnTimelineStore.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void checkAccess(ApplicationReportExt app)
        throws YarnException, IOException {
  if (app.appViewACLs != null) {
    aclsManager.addApplication(
        app.appReport.getApplicationId(), app.appViewACLs);
    try {
      if (!aclsManager.checkAccess(UserGroupInformation.getCurrentUser(),
          ApplicationAccessType.VIEW_APP, app.appReport.getUser(),
          app.appReport.getApplicationId())) {
        throw new AuthorizationException("User "
            + UserGroupInformation.getCurrentUser().getShortUserName()
            + " does not have privilage to see this application "
            + app.appReport.getApplicationId());
      }
    } finally {
      aclsManager.removeApplication(app.appReport.getApplicationId());
    }
  }
}
 
Example #13
Source File: Server.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize proxy users to access this server
 * @throws WrappedRpcServerException - user is not allowed to proxy
 */
private void authorizeConnection() throws WrappedRpcServerException {
  try {
    // If auth method is TOKEN, the token was obtained by the
    // real user for the effective user, therefore not required to
    // authorize real user. doAs is allowed only for simple or kerberos
    // authentication
    if (user != null && user.getRealUser() != null
        && (authMethod != AuthMethod.TOKEN)) {
      ProxyUsers.authorize(user, this.getHostAddress());
    }
    authorize(user, protocolName, getHostInetAddress());
    if (LOG.isDebugEnabled()) {
      LOG.debug("Successfully authorized " + connectionContext);
    }
    rpcMetrics.incrAuthorizationSuccesses();
  } catch (AuthorizationException ae) {
    LOG.info("Connection from " + this
        + " for protocol " + connectionContext.getProtocol()
        + " is unauthorized for user " + user);
    rpcMetrics.incrAuthorizationFailures();
    throw new WrappedRpcServerException(
        RpcErrorCodeProto.FATAL_UNAUTHORIZED, ae);
  }
}
 
Example #14
Source File: Server.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize proxy users to access this server
 * @throws WrappedRpcServerException - user is not allowed to proxy
 */
private void authorizeConnection() throws WrappedRpcServerException {
  try {
    // If auth method is TOKEN, the token was obtained by the
    // real user for the effective user, therefore not required to
    // authorize real user. doAs is allowed only for simple or kerberos
    // authentication
    if (user != null && user.getRealUser() != null
        && (authMethod != AuthMethod.TOKEN)) {
      ProxyUsers.authorize(user, this.getHostAddress());
    }
    authorize(user, protocolName, getHostInetAddress());
    if (LOG.isDebugEnabled()) {
      LOG.debug("Successfully authorized " + connectionContext);
    }
    rpcMetrics.incrAuthorizationSuccesses();
  } catch (AuthorizationException ae) {
    LOG.info("Connection from " + this
        + " for protocol " + connectionContext.getProtocol()
        + " is unauthorized for user " + user);
    rpcMetrics.incrAuthorizationFailures();
    throw new WrappedRpcServerException(
        RpcErrorCodeProto.FATAL_UNAUTHORIZED, ae);
  }
}
 
Example #15
Source File: Server.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Authorize the incoming client connection.
 * 
 * @param user client user
 * @param protocolName - the protocol
 * @param addr InetAddress of incoming connection
 * @throws AuthorizationException when the client isn't authorized to talk the protocol
 */
private void authorize(UserGroupInformation user, String protocolName,
    InetAddress addr) throws AuthorizationException {
  if (authorize) {
    if (protocolName == null) {
      throw new AuthorizationException("Null protocol not authorized");
    }
    Class<?> protocol = null;
    try {
      protocol = getProtocolClass(protocolName, getConf());
    } catch (ClassNotFoundException cfne) {
      throw new AuthorizationException("Unknown protocol: " + 
                                       protocolName);
    }
    serviceAuthorizationManager.authorize(user, protocol, getConf(), addr);
  }
}
 
Example #16
Source File: ApplicationHistoryManagerOnTimelineStore.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void checkAccess(ApplicationReportExt app)
        throws YarnException, IOException {
  if (app.appViewACLs != null) {
    aclsManager.addApplication(
        app.appReport.getApplicationId(), app.appViewACLs);
    try {
      if (!aclsManager.checkAccess(UserGroupInformation.getCurrentUser(),
          ApplicationAccessType.VIEW_APP, app.appReport.getUser(),
          app.appReport.getApplicationId())) {
        throw new AuthorizationException("User "
            + UserGroupInformation.getCurrentUser().getShortUserName()
            + " does not have privilage to see this application "
            + app.appReport.getApplicationId());
      }
    } finally {
      aclsManager.removeApplication(app.appReport.getApplicationId());
    }
  }
}
 
Example #17
Source File: TestRMProxyUsersConf.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testProxyUserConfiguration() throws Exception {
  MockRM rm = null;
  try {
    rm = new MockRM(conf);
    rm.start();
    // wait for web server starting
    Thread.sleep(10000);
    UserGroupInformation proxyUser =
        UserGroupInformation.createProxyUser(
            BAR_USER.getShortUserName(), FOO_USER);
    try {
      ProxyUsers.getDefaultImpersonationProvider().authorize(proxyUser,
          ipAddress);
    } catch (AuthorizationException e) {
      // Exception is not expected
      Assert.fail();
    }
  } finally {
    if (rm != null) {
      rm.stop();
      rm.close();
    }
  }
}
 
Example #18
Source File: KeyAuthorizationKeyProvider.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void authorizeCreateKey(String keyName, Options options,
    UserGroupInformation ugi) throws IOException{
  Preconditions.checkNotNull(ugi, "UserGroupInformation cannot be null");
  Map<String, String> attributes = options.getAttributes();
  String aclName = attributes.get(KEY_ACL_NAME);
  boolean success = false;
  if (Strings.isNullOrEmpty(aclName)) {
    if (acls.isACLPresent(keyName, KeyOpType.MANAGEMENT)) {
      options.setAttributes(ImmutableMap.<String, String> builder()
          .putAll(attributes).put(KEY_ACL_NAME, keyName).build());
      success =
          acls.hasAccessToKey(keyName, ugi, KeyOpType.MANAGEMENT)
              || acls.hasAccessToKey(keyName, ugi, KeyOpType.ALL);
    } else {
      success = false;
    }
  } else {
    success = acls.isACLPresent(aclName, KeyOpType.MANAGEMENT) &&
        (acls.hasAccessToKey(aclName, ugi, KeyOpType.MANAGEMENT)
        || acls.hasAccessToKey(aclName, ugi, KeyOpType.ALL));
  }
  if (!success)
    throw new AuthorizationException(String.format("User [%s] is not"
        + " authorized to create key !!", ugi.getShortUserName()));
}
 
Example #19
Source File: RMWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/delegation-token/expiration")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response
    postDelegationTokenExpiration(@Context HttpServletRequest hsr)
        throws AuthorizationException, IOException, InterruptedException,
        Exception {

  init();
  UserGroupInformation callerUGI;
  try {
    callerUGI = createKerberosUserGroupInformation(hsr);
  } catch (YarnException ye) {
    return Response.status(Status.FORBIDDEN).entity(ye.getMessage()).build();
  }

  DelegationToken requestToken = new DelegationToken();
  requestToken.setToken(extractToken(hsr).encodeToUrlString());
  return renewDelegationToken(requestToken, hsr, callerUGI);
}
 
Example #20
Source File: RMWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/delegation-token")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response postDelegationToken(DelegationToken tokenData,
    @Context HttpServletRequest hsr) throws AuthorizationException,
    IOException, InterruptedException, Exception {

  init();
  UserGroupInformation callerUGI;
  try {
    callerUGI = createKerberosUserGroupInformation(hsr);
  } catch (YarnException ye) {
    return Response.status(Status.FORBIDDEN).entity(ye.getMessage()).build();
  }
  return createDelegationToken(tokenData, hsr, callerUGI);
}
 
Example #21
Source File: RMWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a new ApplicationId which is then sent to the client
 * 
 * @param hsr
 *          the servlet request
 * @return Response containing the app id and the maximum resource
 *         capabilities
 * @throws AuthorizationException
 * @throws IOException
 * @throws InterruptedException
 */
@POST
@Path("/apps/new-application")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createNewApplication(@Context HttpServletRequest hsr)
    throws AuthorizationException, IOException, InterruptedException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  if (callerUGI == null) {
    throw new AuthorizationException("Unable to obtain user name, "
        + "user not authenticated");
  }
  if (UserGroupInformation.isSecurityEnabled() && isStaticUser(callerUGI)) {
    String msg = "The default static user cannot carry out this operation.";
    return Response.status(Status.FORBIDDEN).entity(msg).build();
  }

  NewApplication appId = createNewApplication();
  return Response.status(Status.OK).entity(appId).build();

}
 
Example #22
Source File: RMWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/apps/{appid}/state")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppState getAppState(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) throws AuthorizationException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  String userName = "";
  if (callerUGI != null) {
    userName = callerUGI.getUserName();
  }
  RMApp app = null;
  try {
    app = getRMAppForAppId(appId);
  } catch (NotFoundException e) {
    RMAuditLogger.logFailure(userName, AuditConstants.KILL_APP_REQUEST,
      "UNKNOWN", "RMWebService",
      "Trying to get state of an absent application " + appId);
    throw e;
  }

  AppState ret = new AppState();
  ret.setState(app.getState().toString());

  return ret;
}
 
Example #23
Source File: RMWebServices.java    From big-c with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/apps/{appid}/queue")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppQueue getAppQueue(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) throws AuthorizationException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  String userName = "UNKNOWN-USER";
  if (callerUGI != null) {
    userName = callerUGI.getUserName();
  }
  RMApp app = null;
  try {
    app = getRMAppForAppId(appId);
  } catch (NotFoundException e) {
    RMAuditLogger.logFailure(userName, AuditConstants.KILL_APP_REQUEST,
      "UNKNOWN", "RMWebService",
      "Trying to get state of an absent application " + appId);
    throw e;
  }

  AppQueue ret = new AppQueue();
  ret.setQueue(app.getQueue());

  return ret;
}
 
Example #24
Source File: KeyAuthorizationKeyProvider.java    From big-c with Apache License 2.0 5 votes vote down vote up
private void checkAccess(String aclName, UserGroupInformation ugi,
    KeyOpType opType) throws AuthorizationException {
  Preconditions.checkNotNull(aclName, "Key ACL name cannot be null");
  Preconditions.checkNotNull(ugi, "UserGroupInformation cannot be null");
  if (acls.isACLPresent(aclName, opType) &&
      (acls.hasAccessToKey(aclName, ugi, opType)
          || acls.hasAccessToKey(aclName, ugi, KeyOpType.ALL))) {
    return;
  } else {
    throw new AuthorizationException(String.format("User [%s] is not"
        + " authorized to perform [%s] on key with ACL name [%s]!!",
        ugi.getShortUserName(), opType, aclName));
  }
}
 
Example #25
Source File: RMWebServices.java    From big-c with Apache License 2.0 5 votes vote down vote up
private Response createDelegationToken(DelegationToken tokenData,
    HttpServletRequest hsr, UserGroupInformation callerUGI)
    throws AuthorizationException, IOException, InterruptedException,
    Exception {

  final String renewer = tokenData.getRenewer();
  GetDelegationTokenResponse resp;
  try {
    resp =
        callerUGI
          .doAs(new PrivilegedExceptionAction<GetDelegationTokenResponse>() {
            @Override
            public GetDelegationTokenResponse run() throws IOException,
                YarnException {
              GetDelegationTokenRequest createReq =
                  GetDelegationTokenRequest.newInstance(renewer);
              return rm.getClientRMService().getDelegationToken(createReq);
            }
          });
  } catch (Exception e) {
    LOG.info("Create delegation token request failed", e);
    throw e;
  }

  Token<RMDelegationTokenIdentifier> tk =
      new Token<RMDelegationTokenIdentifier>(resp.getRMDelegationToken()
        .getIdentifier().array(), resp.getRMDelegationToken().getPassword()
        .array(), new Text(resp.getRMDelegationToken().getKind()), new Text(
        resp.getRMDelegationToken().getService()));
  RMDelegationTokenIdentifier identifier = tk.decodeIdentifier();
  long currentExpiration =
      rm.getRMContext().getRMDelegationTokenSecretManager()
        .getRenewDate(identifier);
  DelegationToken respToken =
      new DelegationToken(tk.encodeToUrlString(), renewer, identifier
        .getOwner().toString(), tk.getKind().toString(), currentExpiration,
        identifier.getMaxDate());
  return Response.status(Status.OK).entity(respToken).build();
}
 
Example #26
Source File: RpcServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Authorize the incoming client connection.
 * @param user client user
 * @param connection incoming connection
 * @param addr InetAddress of incoming connection
 * @throws AuthorizationException when the client isn't authorized to talk the protocol
 */
public synchronized void authorize(UserGroupInformation user, ConnectionHeader connection,
    InetAddress addr) throws AuthorizationException {
  if (authorize) {
    Class<?> c = getServiceInterface(services, connection.getServiceName());
    authManager.authorize(user, c, getConf(), addr);
  }
}
 
Example #27
Source File: RESTServletContainer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * This container is used only if authentication and
 * impersonation is enabled. The remote request user is used
 * as a proxy user for impersonation in invoking any REST service.
 */
@Override
public void service(final HttpServletRequest request,
    final HttpServletResponse response) throws ServletException, IOException {
  final String doAsUserFromQuery = request.getParameter("doAs");
  RESTServlet servlet = RESTServlet.getInstance();
  if (doAsUserFromQuery != null) {
    Configuration conf = servlet.getConfiguration();
    if (!servlet.supportsProxyuser()) {
      throw new ServletException("Support for proxyuser is not configured");
    }
    // Authenticated remote user is attempting to do 'doAs' proxy user.
    UserGroupInformation ugi = UserGroupInformation.createRemoteUser(request.getRemoteUser());
    // create and attempt to authorize a proxy user (the client is attempting
    // to do proxy user)
    ugi = UserGroupInformation.createProxyUser(doAsUserFromQuery, ugi);
    // validate the proxy user authorization
    try {
      ProxyUsers.authorize(ugi, request.getRemoteAddr(), conf);
    } catch(AuthorizationException e) {
      throw new ServletException(e.getMessage());
    }
    servlet.setEffectiveUser(doAsUserFromQuery);
  } else {
    String effectiveUser = request.getRemoteUser();
    servlet.setEffectiveUser(effectiveUser);
  }
  super.service(request, response);
}
 
Example #28
Source File: JobTracker.java    From RDFS with Apache License 2.0 5 votes vote down vote up
@Override
public void refreshServiceAcl() throws IOException {
  if (!conf.getBoolean(
          ServiceAuthorizationManager.SERVICE_AUTHORIZATION_CONFIG, false)) {
    throw new AuthorizationException("Service Level Authorization not enabled!");
  }
  SecurityUtil.getPolicy().refresh();
}
 
Example #29
Source File: TestRPC.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private void doRPCs(Configuration conf, boolean expectFailure) throws Exception {
  SecurityUtil.setPolicy(new ConfiguredPolicy(conf, new TestPolicyProvider()));
  
  Server server = RPC.getServer(new TestImpl(), ADDRESS, 0, 5, true, conf);

  TestProtocol proxy = null;

  server.start();

  InetSocketAddress addr = NetUtils.getConnectAddress(server);
  
  try {
    proxy = (TestProtocol)RPC.getProxy(
        TestProtocol.class, TestProtocol.versionID, addr, conf);
    proxy.ping();

    if (expectFailure) {
      fail("Expect RPC.getProxy to fail with AuthorizationException!");
    }
  } catch (RemoteException e) {
    if (expectFailure) {
      assertTrue(e.unwrapRemoteException() instanceof AuthorizationException);
    } else {
      throw e;
    }
  } finally {
    server.stop();
    if (proxy != null) {
      RPC.stopProxy(proxy);
    }
  }
}
 
Example #30
Source File: TestApplicationHistoryManagerOnTimelineStore.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetApplicationAttempts() throws Exception {
  final ApplicationId appId = ApplicationId.newInstance(0, 1);
  Collection<ApplicationAttemptReport> appAttempts;
  if (callerUGI == null) {
    appAttempts = historyManager.getApplicationAttempts(appId).values();
  } else {
    try {
      appAttempts = callerUGI.doAs(
          new PrivilegedExceptionAction<Collection<ApplicationAttemptReport>> () {
        @Override
        public Collection<ApplicationAttemptReport> run() throws Exception {
          return historyManager.getApplicationAttempts(appId).values();
        }
      });
      if (callerUGI != null && callerUGI.getShortUserName().equals("user3")) {
        // The exception is expected
        Assert.fail();
      }
    } catch (AuthorizationException e) {
      if (callerUGI != null && callerUGI.getShortUserName().equals("user3")) {
        // The exception is expected
        return;
      }
      throw e;
    }
  }
  Assert.assertNotNull(appAttempts);
  Assert.assertEquals(SCALE, appAttempts.size());
}