/// <exception cref="System.Exception"/>
            public string Call()
            {
                GSSManager gssManager = GSSManager.GetInstance();
                GSSContext gssContext = null;

                try
                {
                    string  servicePrincipal = KerberosTestUtils.GetServerPrincipal();
                    Oid     oid         = KerberosUtil.GetOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.CreateName(servicePrincipal, oid);
                    oid        = KerberosUtil.GetOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.CreateContext(serviceName, oid, null, GSSContext.
                                                          DefaultLifetime);
                    gssContext.RequestCredDeleg(true);
                    gssContext.RequestMutualAuth(true);
                    byte[] inToken  = new byte[0];
                    byte[] outToken = gssContext.InitSecContext(inToken, 0, inToken.Length);
                    Base64 base64   = new Base64(0);
                    return(base64.EncodeToString(outToken));
                }
                finally
                {
                    if (gssContext != null)
                    {
                        gssContext.Dispose();
                    }
                }
            }
Exemple #2
0
        public virtual void TestDefaultRealmValid()
        {
            string defaultRealm = KerberosUtil.GetDefaultRealm();

            AssertNotEmpty("No default Kerberos Realm", defaultRealm);
            Log.Info("Default Realm '{}'", defaultRealm);
        }
Exemple #3
0
        /// <summary>Set the static configuration to get the rules.</summary>
        /// <remarks>
        /// Set the static configuration to get the rules.
        /// <p/>
        /// IMPORTANT: This method does a NOP if the rules have been set already.
        /// If there is a need to reset the rules, the
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Util.KerberosName.SetRules(string)
        ///     "/>
        /// method should be invoked directly.
        /// </remarks>
        /// <param name="conf">the new configuration</param>
        /// <exception cref="System.IO.IOException"/>
        public static void SetConfiguration(Configuration conf)
        {
            string defaultRule;

            switch (SecurityUtil.GetAuthenticationMethod(conf))
            {
            case UserGroupInformation.AuthenticationMethod.Kerberos:
            case UserGroupInformation.AuthenticationMethod.KerberosSsl:
            {
                try
                {
                    KerberosUtil.GetDefaultRealm();
                }
                catch (Exception ke)
                {
                    throw new ArgumentException("Can't get Kerberos realm", ke);
                }
                defaultRule = "DEFAULT";
                break;
            }

            default:
            {
                // just extract the simple user name
                defaultRule = "RULE:[1:$1] RULE:[2:$1]";
                break;
            }
            }
            string ruleString = conf.Get(CommonConfigurationKeysPublic.HadoopSecurityAuthToLocal
                                         , defaultRule);

            SetRules(ruleString);
        }
Exemple #4
0
 /// <summary>
 /// Get the default kerberos realm —returning "" if there
 /// is no realm or other problem
 /// </summary>
 /// <returns>
 /// the default realm of the system if it
 /// could be determined
 /// </returns>
 public static string GetDefaultRealmInJVM()
 {
     try
     {
         return(KerberosUtil.GetDefaultRealm());
     }
     catch (TypeLoadException)
     {
     }
     catch (MissingMethodException)
     {
     }
     catch (MemberAccessException)
     {
     }
     catch (TargetInvocationException)
     {
     }
     // JDK7
     // ignored
     // ignored
     // ignored
     // ignored
     return(string.Empty);
 }
Exemple #5
0
            /// <exception cref="System.Exception"/>
            public Void Run()
            {
                GSSContext gssContext = null;

                try
                {
                    GSSManager gssManager       = GSSManager.GetInstance();
                    string     servicePrincipal = KerberosUtil.GetServicePrincipal("HTTP", this._enclosing
                                                                                   .url.GetHost());
                    Oid     oid         = KerberosUtil.GetOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.CreateName(servicePrincipal, oid);
                    oid        = KerberosUtil.GetOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.CreateContext(serviceName, oid, null, GSSContext.
                                                          DefaultLifetime);
                    gssContext.RequestCredDeleg(true);
                    gssContext.RequestMutualAuth(true);
                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    bool   established = false;
                    while (!established)
                    {
                        outToken = gssContext.InitSecContext(inToken, 0, inToken.Length);
                        if (outToken != null)
                        {
                            this._enclosing.SendToken(outToken);
                        }
                        if (!gssContext.IsEstablished())
                        {
                            inToken = this._enclosing.ReadToken();
                        }
                        else
                        {
                            established = true;
                        }
                    }
                }
                finally
                {
                    if (gssContext != null)
                    {
                        gssContext.Dispose();
                        gssContext = null;
                    }
                }
                return(null);
            }
            public override AppConfigurationEntry[] GetAppConfigurationEntry(string name)
            {
                IDictionary <string, string> options = new Dictionary <string, string>();

                if (PlatformName.IbmJava)
                {
                    options["useKeytab"] = keytab.StartsWith("file://") ? keytab : "file://" + keytab;
                    options["principal"] = principal;
                    options["credsType"] = "acceptor";
                }
                else
                {
                    options["keyTab"]         = keytab;
                    options["principal"]      = principal;
                    options["useKeyTab"]      = "true";
                    options["storeKey"]       = "true";
                    options["doNotPrompt"]    = "true";
                    options["useTicketCache"] = "true";
                    options["renewTGT"]       = "true";
                    options["isInitiator"]    = "false";
                }
                options["refreshKrb5Config"] = "true";
                string ticketCache = Runtime.Getenv("KRB5CCNAME");

                if (ticketCache != null)
                {
                    if (PlatformName.IbmJava)
                    {
                        options["useDefaultCcache"] = "true";
                        // The first value searched when "useDefaultCcache" is used.
                        Runtime.SetProperty("KRB5CCNAME", ticketCache);
                        options["renewTGT"]  = "true";
                        options["credsType"] = "both";
                    }
                    else
                    {
                        options["ticketCache"] = ticketCache;
                    }
                }
                if (Log.IsDebugEnabled())
                {
                    options["debug"] = "true";
                }
                return(new AppConfigurationEntry[] { new AppConfigurationEntry(KerberosUtil.GetKrb5LoginModuleName
                                                                                   (), AppConfigurationEntry.LoginModuleControlFlag.Required, options) });
            }
            public override AppConfigurationEntry[] GetAppConfigurationEntry(string name)
            {
                IDictionary <string, string> options = new Dictionary <string, string>();

                options["keyTab"]            = KerberosTestUtils.GetKeytabFile();
                options["principal"]         = principal;
                options["useKeyTab"]         = "true";
                options["storeKey"]          = "true";
                options["doNotPrompt"]       = "true";
                options["useTicketCache"]    = "true";
                options["renewTGT"]          = "true";
                options["refreshKrb5Config"] = "true";
                options["isInitiator"]       = "true";
                string ticketCache = Runtime.Getenv("KRB5CCNAME");

                if (ticketCache != null)
                {
                    options["ticketCache"] = ticketCache;
                }
                options["debug"] = "true";
                return(new AppConfigurationEntry[] { new AppConfigurationEntry(KerberosUtil.GetKrb5LoginModuleName
                                                                                   (), AppConfigurationEntry.LoginModuleControlFlag.Required, options) });
            }
            /// <exception cref="System.Exception"/>
            public AuthenticationToken Run()
            {
                AuthenticationToken token      = null;
                GSSContext          gssContext = null;
                GSSCredential       gssCreds   = null;

                try
                {
                    gssCreds = this._enclosing.gssManager.CreateCredential(this._enclosing.gssManager
                                                                           .CreateName(KerberosUtil.GetServicePrincipal("HTTP", serverName), KerberosUtil.GetOidInstance
                                                                                           ("NT_GSS_KRB5_PRINCIPAL")), GSSCredential.IndefiniteLifetime, new Oid[] { KerberosUtil
                                                                                                                                                                     .GetOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.GetOidInstance("GSS_KRB5_MECH_OID"
                                                                                                                                                                                                                                         ) }, GSSCredential.AcceptOnly);
                    gssContext = this._enclosing.gssManager.CreateContext(gssCreds);
                    byte[] serverToken = gssContext.AcceptSecContext(clientToken, 0, clientToken.Length
                                                                     );
                    if (serverToken != null && serverToken.Length > 0)
                    {
                        string authenticate = base64.EncodeToString(serverToken);
                        response.SetHeader(KerberosAuthenticator.WwwAuthenticate, KerberosAuthenticator.Negotiate
                                           + " " + authenticate);
                    }
                    if (!gssContext.IsEstablished())
                    {
                        response.SetStatus(HttpServletResponse.ScUnauthorized);
                        KerberosAuthenticationHandler.Log.Trace("SPNEGO in progress");
                    }
                    else
                    {
                        string       clientPrincipal = gssContext.GetSrcName().ToString();
                        KerberosName kerberosName    = new KerberosName(clientPrincipal);
                        string       userName        = kerberosName.GetShortName();
                        token = new AuthenticationToken(userName, clientPrincipal, this._enclosing.GetType
                                                            ());
                        response.SetStatus(HttpServletResponse.ScOk);
                        KerberosAuthenticationHandler.Log.Trace("SPNEGO completed for principal [{}]", clientPrincipal
                                                                );
                    }
                }
                finally
                {
                    if (gssContext != null)
                    {
                        gssContext.Dispose();
                    }
                    if (gssCreds != null)
                    {
                        gssCreds.Dispose();
                    }
                }
                return(token);
            }
 /// <summary>Initializes the authentication handler instance.</summary>
 /// <remarks>
 /// Initializes the authentication handler instance.
 /// <p>
 /// It creates a Kerberos context using the principal and keytab specified in the configuration.
 /// <p>
 /// This method is invoked by the
 /// <see cref="AuthenticationFilter.Init(Javax.Servlet.FilterConfig)"/>
 /// method.
 /// </remarks>
 /// <param name="config">configuration properties to initialize the handler.</param>
 /// <exception cref="Javax.Servlet.ServletException">thrown if the handler could not be initialized.
 ///     </exception>
 public override void Init(Properties config)
 {
     try
     {
         string principal = config.GetProperty(Principal);
         if (principal == null || principal.Trim().Length == 0)
         {
             throw new ServletException("Principal not defined in configuration");
         }
         keytab = config.GetProperty(Keytab, keytab);
         if (keytab == null || keytab.Trim().Length == 0)
         {
             throw new ServletException("Keytab not defined in configuration");
         }
         if (!new FilePath(keytab).Exists())
         {
             throw new ServletException("Keytab does not exist: " + keytab);
         }
         // use all SPNEGO principals in the keytab if a principal isn't
         // specifically configured
         string[] spnegoPrincipals;
         if (principal.Equals("*"))
         {
             spnegoPrincipals = KerberosUtil.GetPrincipalNames(keytab, Pattern.Compile
                                                                   ("HTTP/.*"));
             if (spnegoPrincipals.Length == 0)
             {
                 throw new ServletException("Principals do not exist in the keytab");
             }
         }
         else
         {
             spnegoPrincipals = new string[] { principal };
         }
         string nameRules = config.GetProperty(NameRules, null);
         if (nameRules != null)
         {
             KerberosName.SetRules(nameRules);
         }
         foreach (string spnegoPrincipal in spnegoPrincipals)
         {
             Log.Info("Login using keytab {}, for principal {}", keytab, spnegoPrincipal);
             KerberosAuthenticationHandler.KerberosConfiguration kerberosConfiguration = new KerberosAuthenticationHandler.KerberosConfiguration
                                                                                             (keytab, spnegoPrincipal);
             LoginContext loginContext = new LoginContext(string.Empty, serverSubject, null, kerberosConfiguration
                                                          );
             try
             {
                 loginContext.Login();
             }
             catch (LoginException le)
             {
                 Log.Warn("Failed to login as [{}]", spnegoPrincipal, le);
                 throw new AuthenticationException(le);
             }
             loginContexts.AddItem(loginContext);
         }
         try
         {
             gssManager = Subject.DoAs(serverSubject, new _PrivilegedExceptionAction_229());
         }
         catch (PrivilegedActionException ex)
         {
             throw ex.GetException();
         }
     }
     catch (Exception ex)
     {
         throw new ServletException(ex);
     }
 }