Beispiel #1
0
        //Empty
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Javax.Servlet.ServletException"/>
        public virtual void DoFilter(ServletRequest req, ServletResponse resp, FilterChain
                                     chain)
        {
            ProxyUtils.RejectNonHttpRequests(req);
            HttpServletRequest  httpReq  = (HttpServletRequest)req;
            HttpServletResponse httpResp = (HttpServletResponse)resp;

            if (Log.IsDebugEnabled())
            {
                Log.Debug("Remote address for request is: {}", httpReq.GetRemoteAddr());
            }
            if (!GetProxyAddresses().Contains(httpReq.GetRemoteAddr()))
            {
                string redirectUrl = FindRedirectUrl();
                string target      = redirectUrl + httpReq.GetRequestURI();
                ProxyUtils.SendRedirect(httpReq, httpResp, target);
                return;
            }
            string user = null;

            if (httpReq.GetCookies() != null)
            {
                foreach (Cookie c in httpReq.GetCookies())
                {
                    if (WebAppProxyServlet.ProxyUserCookieName.Equals(c.GetName()))
                    {
                        user = c.GetValue();
                        break;
                    }
                }
            }
            if (user == null)
            {
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("Could not find " + WebAppProxyServlet.ProxyUserCookieName + " cookie, so user will not be set"
                              );
                }
                chain.DoFilter(req, resp);
            }
            else
            {
                AmIpPrincipal  principal      = new AmIpPrincipal(user);
                ServletRequest requestWrapper = new AmIpServletRequestWrapper(httpReq, principal);
                chain.DoFilter(requestWrapper, resp);
            }
        }
Beispiel #2
0
        /// <summary>Test AmIpFilter</summary>
        /// <exception cref="System.Exception"/>
        public virtual void TestFilter()
        {
            IDictionary <string, string> @params = new Dictionary <string, string>();

            @params[AmIpFilter.ProxyHost]    = proxyHost;
            @params[AmIpFilter.ProxyUriBase] = proxyUri;
            FilterConfig config = new TestAmFilter.DummyFilterConfig(@params);
            // dummy filter
            FilterChain chain      = new _FilterChain_135(this);
            AmIpFilter  testFilter = new AmIpFilter();

            testFilter.Init(config);
            TestAmFilter.HttpServletResponseForTest response = new TestAmFilter.HttpServletResponseForTest
                                                                   (this);
            // Test request should implements HttpServletRequest
            ServletRequest failRequest = Org.Mockito.Mockito.Mock <ServletRequest>();

            try
            {
                testFilter.DoFilter(failRequest, response, chain);
                NUnit.Framework.Assert.Fail();
            }
            catch (ServletException e)
            {
                NUnit.Framework.Assert.AreEqual(ProxyUtils.EHttpHttpsOnly, e.Message);
            }
            // request with HttpServletRequest
            HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>();

            Org.Mockito.Mockito.When(request.GetRemoteAddr()).ThenReturn("redirect");
            Org.Mockito.Mockito.When(request.GetRequestURI()).ThenReturn("/redirect");
            testFilter.DoFilter(request, response, chain);
            // address "redirect" is not in host list
            NUnit.Framework.Assert.AreEqual(302, response.status);
            string redirect = response.GetHeader(ProxyUtils.Location);

            NUnit.Framework.Assert.AreEqual("http://bogus/redirect", redirect);
            // "127.0.0.1" contains in host list. Without cookie
            Org.Mockito.Mockito.When(request.GetRemoteAddr()).ThenReturn("127.0.0.1");
            testFilter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(doFilterRequest.Contains("javax.servlet.http.HttpServletRequest"
                                                                   ));
            // cookie added
            Cookie[] cookies = new Cookie[1];
            cookies[0] = new Cookie(WebAppProxyServlet.ProxyUserCookieName, "user");
            Org.Mockito.Mockito.When(request.GetCookies()).ThenReturn(cookies);
            testFilter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.AreEqual("org.apache.hadoop.yarn.server.webproxy.amfilter.AmIpServletRequestWrapper"
                                            , doFilterRequest);
            // request contains principal from cookie
            NUnit.Framework.Assert.AreEqual("user", servletWrapper.GetUserPrincipal().GetName
                                                ());
            NUnit.Framework.Assert.AreEqual("user", servletWrapper.GetRemoteUser());
            NUnit.Framework.Assert.IsFalse(servletWrapper.IsUserInRole(string.Empty));
        }
Beispiel #3
0
 private int SetCookieParams(Controller.RequestContext rc, HttpServletRequest req)
 {
     Cookie[] cookies = req.GetCookies();
     if (cookies != null)
     {
         foreach (Cookie cookie in cookies)
         {
             rc.Cookies()[cookie.GetName()] = cookie;
         }
         return(cookies.Length);
     }
     return(0);
 }
Beispiel #4
0
 // OK
 public virtual IDictionary <string, Cookie> Cookies()
 {
     if (cookies == null)
     {
         cookies = Maps.NewHashMap();
         Cookie[] rcookies = request.GetCookies();
         if (rcookies != null)
         {
             foreach (Cookie cookie in rcookies)
             {
                 cookies[cookie.GetName()] = cookie;
             }
         }
     }
     return(cookies);
 }
Beispiel #5
0
        /// <exception cref="System.Exception"/>
        public virtual void FilterNullCookies()
        {
            HttpServletRequest request = Org.Mockito.Mockito.Mock <HttpServletRequest>();

            Org.Mockito.Mockito.When(request.GetCookies()).ThenReturn(null);
            Org.Mockito.Mockito.When(request.GetRemoteAddr()).ThenReturn(proxyHost);
            HttpServletResponse          response = Org.Mockito.Mockito.Mock <HttpServletResponse>();
            AtomicBoolean                invoked  = new AtomicBoolean();
            FilterChain                  chain    = new _FilterChain_104(invoked);
            IDictionary <string, string> @params  = new Dictionary <string, string>();

            @params[AmIpFilter.ProxyHost]    = proxyHost;
            @params[AmIpFilter.ProxyUriBase] = proxyUri;
            FilterConfig conf   = new TestAmFilter.DummyFilterConfig(@params);
            Filter       filter = new TestAmFilter.TestAmIpFilter(this);

            filter.Init(conf);
            filter.DoFilter(request, response, chain);
            NUnit.Framework.Assert.IsTrue(invoked.Get());
            filter.Destroy();
        }
        /// <summary>
        /// Returns the
        /// <see cref="AuthenticationToken"/>
        /// for the request.
        /// <p>
        /// It looks at the received HTTP cookies and extracts the value of the
        /// <see cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticatedURL.AuthCookie
        ///     "/>
        /// if present. It verifies the signature and if correct it creates the
        /// <see cref="AuthenticationToken"/>
        /// and returns
        /// it.
        /// <p>
        /// If this method returns <code>null</code> the filter will invoke the configured
        /// <see cref="AuthenticationHandler"/>
        /// to perform user authentication.
        /// </summary>
        /// <param name="request">request object.</param>
        /// <returns>the Authentication token if the request is authenticated, <code>null</code> otherwise.
        ///     </returns>
        /// <exception cref="System.IO.IOException">thrown if an IO error occurred.</exception>
        /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException
        ///     ">thrown if the token is invalid or if it has expired.</exception>
        protected internal virtual AuthenticationToken GetToken(HttpServletRequest request
                                                                )
        {
            AuthenticationToken token = null;
            string tokenStr           = null;

            Cookie[] cookies = request.GetCookies();
            if (cookies != null)
            {
                foreach (Cookie cookie in cookies)
                {
                    if (cookie.GetName().Equals(AuthenticatedURL.AuthCookie))
                    {
                        tokenStr = cookie.GetValue();
                        try
                        {
                            tokenStr = signer.VerifyAndExtract(tokenStr);
                        }
                        catch (SignerException ex)
                        {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null)
            {
                token = ((AuthenticationToken)AuthenticationToken.Parse(tokenStr));
                if (!token.GetType().Equals(authHandler.GetType()))
                {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.IsExpired())
                {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return(token);
        }
        /// <exception cref="System.IO.IOException"/>
        protected override void DoGet(HttpServletRequest req, HttpServletResponse resp)
        {
            try
            {
                string   userApprovedParamS = req.GetParameter(ProxyUriUtils.ProxyApprovalParam);
                bool     userWasWarned      = false;
                bool     userApproved       = Sharpen.Extensions.ValueOf(userApprovedParamS);
                bool     securityEnabled    = IsSecurityEnabled();
                string   remoteUser         = req.GetRemoteUser();
                string   pathInfo           = req.GetPathInfo();
                string[] parts = pathInfo.Split("/", 3);
                if (parts.Length < 2)
                {
                    Log.Warn("{} gave an invalid proxy path {}", remoteUser, pathInfo);
                    NotFound(resp, "Your path appears to be formatted incorrectly.");
                    return;
                }
                //parts[0] is empty because path info always starts with a /
                string        appId = parts[1];
                string        rest  = parts.Length > 2 ? parts[2] : string.Empty;
                ApplicationId id    = Apps.ToAppID(appId);
                if (id == null)
                {
                    Log.Warn("{} attempting to access {} that is invalid", remoteUser, appId);
                    NotFound(resp, appId + " appears to be formatted incorrectly.");
                    return;
                }
                if (securityEnabled)
                {
                    string   cookieName = GetCheckCookieName(id);
                    Cookie[] cookies    = req.GetCookies();
                    if (cookies != null)
                    {
                        foreach (Cookie c in cookies)
                        {
                            if (cookieName.Equals(c.GetName()))
                            {
                                userWasWarned = true;
                                userApproved  = userApproved || Sharpen.Extensions.ValueOf(c.GetValue());
                                break;
                            }
                        }
                    }
                }
                bool checkUser = securityEnabled && (!userWasWarned || !userApproved);
                AppReportFetcher.FetchedAppReport fetchedAppReport = null;
                ApplicationReport applicationReport = null;
                try
                {
                    fetchedAppReport = GetApplicationReport(id);
                    if (fetchedAppReport != null)
                    {
                        if (fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Rm &&
                            fetchedAppReport.GetAppReportSource() != AppReportFetcher.AppReportSource.Ahs)
                        {
                            throw new NotSupportedException("Application report not " + "fetched from RM or history server."
                                                            );
                        }
                        applicationReport = fetchedAppReport.GetApplicationReport();
                    }
                }
                catch (ApplicationNotFoundException)
                {
                    applicationReport = null;
                }
                if (applicationReport == null)
                {
                    Log.Warn("{} attempting to access {} that was not found", remoteUser, id);
                    URI toFetch = ProxyUriUtils.GetUriFromTrackingPlugins(id, this.trackingUriPlugins
                                                                          );
                    if (toFetch != null)
                    {
                        ProxyUtils.SendRedirect(req, resp, toFetch.ToString());
                        return;
                    }
                    NotFound(resp, "Application " + appId + " could not be found " + "in RM or history server"
                             );
                    return;
                }
                string original = applicationReport.GetOriginalTrackingUrl();
                URI    trackingUri;
                if (original == null || original.Equals("N/A") || original.Equals(string.Empty))
                {
                    if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Rm)
                    {
                        // fallback to ResourceManager's app page if no tracking URI provided
                        // and Application Report was fetched from RM
                        Log.Debug("Original tracking url is '{}'. Redirecting to RM app page", original ==
                                  null ? "NULL" : original);
                        ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(rmAppPageUrlBase, id.ToString
                                                                                  ()));
                    }
                    else
                    {
                        if (fetchedAppReport.GetAppReportSource() == AppReportFetcher.AppReportSource.Ahs)
                        {
                            // fallback to Application History Server app page if the application
                            // report was fetched from AHS
                            Log.Debug("Original tracking url is '{}'. Redirecting to AHS app page", original
                                      == null ? "NULL" : original);
                            ProxyUtils.SendRedirect(req, resp, StringHelper.Pjoin(ahsAppPageUrlBase, id.ToString
                                                                                      ()));
                        }
                    }
                    return;
                }
                else
                {
                    if (ProxyUriUtils.GetSchemeFromUrl(original).IsEmpty())
                    {
                        trackingUri = ProxyUriUtils.GetUriFromAMUrl(WebAppUtils.GetHttpSchemePrefix(conf)
                                                                    , original);
                    }
                    else
                    {
                        trackingUri = new URI(original);
                    }
                }
                string runningUser = applicationReport.GetUser();
                if (checkUser && !runningUser.Equals(remoteUser))
                {
                    Log.Info("Asking {} if they want to connect to the " + "app master GUI of {} owned by {}"
                             , remoteUser, appId, runningUser);
                    WarnUserPage(resp, ProxyUriUtils.GetPathAndQuery(id, rest, req.GetQueryString(),
                                                                     true), runningUser, id);
                    return;
                }
                // Append the user-provided path and query parameter to the original
                // tracking url.
                IList <NameValuePair> queryPairs = URLEncodedUtils.Parse(req.GetQueryString(), null
                                                                         );
                UriBuilder builder = UriBuilder.FromUri(trackingUri);
                foreach (NameValuePair pair in queryPairs)
                {
                    builder.QueryParam(pair.GetName(), pair.GetValue());
                }
                URI toFetch_1 = builder.Path(rest).Build();
                Log.Info("{} is accessing unchecked {}" + " which is the app master GUI of {} owned by {}"
                         , remoteUser, toFetch_1, appId, runningUser);
                switch (applicationReport.GetYarnApplicationState())
                {
                case YarnApplicationState.Killed:
                case YarnApplicationState.Finished:
                case YarnApplicationState.Failed:
                {
                    ProxyUtils.SendRedirect(req, resp, toFetch_1.ToString());
                    return;
                }

                default:
                {
                    break;
                }
                }
                // fall out of the switch
                Cookie c_1 = null;
                if (userWasWarned && userApproved)
                {
                    c_1 = MakeCheckCookie(id, true);
                }
                ProxyLink(req, resp, toFetch_1, c_1, GetProxyHost());
            }
            catch (Exception e)
            {
                throw new IOException(e);
            }
        }