@Override
    public String run() throws HttpAuthenticationException {
      // Get own Kerberos credentials for accepting connection
      GSSManager manager = GSSManager.getInstance();
      GSSContext gssContext = null;
      String serverPrincipal = getPrincipalWithoutRealm(serviceUGI.getUserName());
      try {
        // This Oid for Kerberos GSS-API mechanism.
        Oid kerberosMechOid = new Oid("1.2.840.113554.1.2.2");
        // Oid for SPNego GSS-API mechanism.
        Oid spnegoMechOid = new Oid("1.3.6.1.5.5.2");
        // Oid for kerberos principal name
        Oid krb5PrincipalOid = new Oid("1.2.840.113554.1.2.2.1");

        // GSS name for server
        GSSName serverName = manager.createName(serverPrincipal, krb5PrincipalOid);

        // GSS credentials for server
        GSSCredential serverCreds =
            manager.createCredential(
                serverName,
                GSSCredential.DEFAULT_LIFETIME,
                new Oid[] {kerberosMechOid, spnegoMechOid},
                GSSCredential.ACCEPT_ONLY);

        // Create a GSS context
        gssContext = manager.createContext(serverCreds);
        // Get service ticket from the authorization header
        String serviceTicketBase64 = getAuthHeader(request, authType);
        byte[] inToken = Base64.decodeBase64(serviceTicketBase64.getBytes());
        gssContext.acceptSecContext(inToken, 0, inToken.length);
        // Authenticate or deny based on its context completion
        if (!gssContext.isEstablished()) {
          throw new HttpAuthenticationException(
              "Kerberos authentication failed: "
                  + "unable to establish context with the service ticket "
                  + "provided by the client.");
        } else {
          return getPrincipalWithoutRealmAndHost(gssContext.getSrcName().toString());
        }
      } catch (GSSException e) {
        throw new HttpAuthenticationException("Kerberos authentication failed: ", e);
      } finally {
        if (gssContext != null) {
          try {
            gssContext.dispose();
          } catch (GSSException e) {
            // No-op
          }
        }
      }
    }
Beispiel #2
0
  public String getValidatedPrincipal() {
    if (validatedContext == null) {
      return null;
    }

    try {
      return validatedContext.getSrcName().toString();
    } catch (GSSException e) {
      logger.error("Error getting name: " + e);
    }

    return null;
  }
  public void authorize(GSSContext context, String host) throws AuthorizationException {

    String localID = this.getLocalID(context, host);
    if (localID == null) {
      String srcName;
      try {
        srcName = context == null ? "" : context.getSrcName().toString();
      } catch (GSSException e) {
        srcName = "";
      }
      throw new AuthorizationException("No local mapping for :" + srcName);
    }
    peerSubject = new Subject();
    GlobusPrincipal nm;
    try {
      nm = JaasGssUtil.toGlobusPrincipal(context.getSrcName());
    } catch (GSSException e) {
      throw new AuthorizationException("Cannot get peer DN");
    }
    peerSubject.getPrincipals().add(nm);
    peerSubject.getPrincipals().add(new UserNamePrincipal(localID));
  }
    Principal getPrincipal() {
      if (isEstablished() == false) {
        throw new IllegalStateException("No established GSSContext to use for the Principal.");
      }

      if (principal == null) {
        try {
          principal = new KerberosPrincipal(gssContext.getSrcName().toString());
        } catch (GSSException e) {
          throw new IllegalStateException("Unable to create Principal", e);
        }
      }

      return principal;
    }
  /** {@inheritDoc} */
  @Override
  public Principal authenticate(GSSContext gssContext, boolean storeCred) {
    if (gssContext.isEstablished()) {
      GSSName gssName = null;
      try {
        gssName = gssContext.getSrcName();
      } catch (GSSException e) {
        log.warn(sm.getString("realmBase.gssNameFail"), e);
      }

      if (gssName != null) {
        String name = gssName.toString();

        if (isStripRealmForGss()) {
          int i = name.indexOf('@');
          if (i > 0) {
            // Zero so we don;t leave a zero length name
            name = name.substring(0, i);
          }
        }
        GSSCredential gssCredential = null;
        if (storeCred && gssContext.getCredDelegState()) {
          try {
            gssCredential = gssContext.getDelegCred();
          } catch (GSSException e) {
            if (log.isDebugEnabled()) {
              log.debug(sm.getString("realmBase.delegatedCredentialFail", name), e);
            }
          }
        }
        return getPrincipal(name, gssCredential);
      }
    }

    // Fail in all other cases
    return null;
  }
  public void authenticate(AuthenticationProtocolClient authenticationprotocolclient, String s)
      throws IOException, TerminatedStateException {
    try {
      logger.finest("Registering gss-ssh return messages.");
      authenticationprotocolclient.registerMessage(
          com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiResponse.class, 60);
      authenticationprotocolclient.registerMessage(
          com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiToken.class, 61);
      authenticationprotocolclient.registerMessage(
          com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiError.class, 64);
      authenticationprotocolclient.registerMessage(
          com.sshtools.j2ssh.authentication.SshMsgUserauthGssapiErrtok.class, 65);
      logger.finest("Sending gssapi user auth request.");
      ByteArrayWriter bytearraywriter = new ByteArrayWriter();
      bytearraywriter.writeUINT32(new UnsignedInteger32(1L));
      byte abyte0[] = GSSConstants.MECH_OID.getDER();
      bytearraywriter.writeBinaryString(abyte0);
      logger.finest("Username:"******"gssapi", bytearraywriter.toByteArray());
      authenticationprotocolclient.sendMessage(sshmsguserauthrequest);
      logger.finest("Receiving user auth response:");
      SshMsgUserauthGssapiResponse sshmsguserauthgssapiresponse =
          (SshMsgUserauthGssapiResponse) authenticationprotocolclient.readMessage(60);
      ByteArrayReader bytearrayreader =
          new ByteArrayReader(sshmsguserauthgssapiresponse.getRequestData());
      byte abyte1[] = bytearrayreader.readBinaryString();
      if (logger.isLoggable(Level.FINEST)) {
        logger.log(Level.FINEST, "Mechanism requested: " + GSSConstants.MECH_OID);
        logger.log(Level.FINEST, "Mechanism selected: " + new Oid(abyte1));
        logger.log(Level.FINEST, "Verify that selected mechanism is GSSAPI.");
      }
      if (!GSSConstants.MECH_OID.equals(new Oid(abyte1))) {
        logger.warning("Mechanism do not match!");
        throw new IOException("Mechanism do not match!");
      }
      logger.finest("Creating GSS context base on grid credentials.");
      GlobusGSSManagerImpl globusgssmanagerimpl = new GlobusGSSManagerImpl();

      HostAuthorization gssAuth = new HostAuthorization(null);
      GSSName targetName = gssAuth.getExpectedName(null, hostname);

      GSSContext gsscontext =
          globusgssmanagerimpl.createContext(
              targetName, new Oid(abyte1), gsscredential, GSSCredential.INDEFINITE_LIFETIME - 1);
      gsscontext.requestCredDeleg(true);
      gsscontext.requestMutualAuth(true);
      gsscontext.requestReplayDet(true);
      gsscontext.requestSequenceDet(true);
      // MOD
      // gsscontext.requestConf(false);
      gsscontext.requestConf(true);

      Object type = GSIConstants.DELEGATION_TYPE_LIMITED;
      gsscontext.requestCredDeleg(false);
      ((ExtendedGSSContext) gsscontext).setOption(GSSConstants.DELEGATION_TYPE, type);

      logger.finest("Starting GSS token exchange.");
      byte abyte2[] = new byte[0];
      do {
        if (gsscontext.isEstablished()) break;
        byte abyte3[] = gsscontext.initSecContext(abyte2, 0, abyte2.length);
        if (abyte3 != null) {
          ByteArrayWriter bytearraywriter1 = new ByteArrayWriter();
          bytearraywriter1.writeBinaryString(abyte3);
          SshMsgUserauthGssapiToken sshmsguserauthgssapitoken =
              new SshMsgUserauthGssapiToken(bytearraywriter1.toByteArray());
          authenticationprotocolclient.sendMessage(sshmsguserauthgssapitoken);
        }
        if (!gsscontext.isEstablished()) {
          SshMsgUserauthGssapiToken sshmsguserauthgssapitoken1 =
              (SshMsgUserauthGssapiToken) authenticationprotocolclient.readMessage(61);
          ByteArrayReader bytearrayreader1 =
              new ByteArrayReader(sshmsguserauthgssapitoken1.getRequestData());
          abyte2 = bytearrayreader1.readBinaryString();
        }
      } while (true);
      logger.log(Level.FINEST, "Sending gssapi exchange complete.");
      SshMsgUserauthGssapiExchangeComplete sshmsguserauthgssapiexchangecomplete =
          new SshMsgUserauthGssapiExchangeComplete();
      authenticationprotocolclient.sendMessage(sshmsguserauthgssapiexchangecomplete);
      if (logger.isLoggable(Level.FINEST)) {
        logger.log(
            Level.FINEST,
            "Context established.\nInitiator : "
                + gsscontext.getSrcName()
                + "\nAcceptor  : "
                + gsscontext.getTargName()
                + "\nLifetime  : "
                + gsscontext.getLifetime()
                + "\nIntegrity   : "
                + gsscontext.getIntegState()
                + "\nConfidentiality   : "
                + gsscontext.getConfState()
                + "\nAnonymity : "
                + gsscontext.getAnonymityState());
      }
    } catch (Throwable t) {
      logger.log(Level.WARNING, "Got Exception: ", t);
      throw new TerminatedStateException(AuthenticationProtocolState.FAILED);
    }
  }
 public SpnegoAuthUser(GSSContext context) throws GSSException {
   this.principal = context.getSrcName().toString();
   this.expiration = new Date().getTime() + 1000L * context.getLifetime();
 }