コード例 #1
0
 private static void GetLogin(IDictionary<string, string> parameters, HttpRequestEventArgs e)
 {
     if (Session.IsAuthenticated(e))
         DefaultResponses.RedirectResponse(e, "/admin");
     else
         DefaultResponses.FileResponse(e, Path.Combine(_base_directory.FullName, "login.html"));
 }
コード例 #2
0
ファイル: HelpServer.cs プロジェクト: netide/netide
        void _server_RequestReceived(object sender, HttpRequestEventArgs e)
        {
            try
            {
                using (var stream = Manager.Load(e.Request.RawUrl))
                {
                    if (stream != null)
                    {
                        e.Response.Status = "200 OK";

                        stream.CopyTo(e.Response.OutputStream);
                    }
                    else
                    {
                        e.Response.Status = "404 Not Found";
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn("Problem while loading help page", ex);

                e.Response.Status = "500 Internal Server Error";
            }
        }
コード例 #3
0
ファイル: HttpServer.cs プロジェクト: Cyber-Forensic/Potato
        protected virtual void OnRequestReceived(HttpRequestEventArgs e)
        {
            var ev = RequestReceived;

            if (ev != null)
                ev(this, e);
        }
コード例 #4
0
 protected override void OnRequestReceived(HttpRequestEventArgs e)
 {
     if (e.Request.Path.StartsWith("/odata", StringComparison.OrdinalIgnoreCase))
         ProcessODataRequest(e.Context);
     else
         ProcessStaticRequest(e.Context);
 }
コード例 #5
0
ファイル: Server.cs プロジェクト: Mellowz/nfsw-server
        private void nServer_RequestReceived(object sender, HttpRequestEventArgs e)
        {
            /*if (e.Request.Path != "/favicon.ico")*/ oldPath = e.Request.Path.Remove(0, 1); // because I'm using Chrome for debug ... it will work without it too since it's Async though

            e.Response.Headers.Add("Connection", "close");
            e.Response.Headers.Add("Content-Encoding", "gzip");
            e.Response.Headers.Add("Content-Type", "application/xml;charset=utf-8");
            e.Response.Headers.Add("Status-Code", "200");

            Byte[] baResponseArray = null;

            if (e.Request.Path.EndsWith("/carslots"))
            {
                baResponseArray = GetResponseData(MainWindow.CurrentSession.ActivePersona.GetCompleteGarage());
            }
            else if (File.Exists(oldPath))
            {
                baResponseArray = GetResponseData(oldPath);
            }

            e.Response.OutputStream.Write(baResponseArray, 0, baResponseArray.Length);
            e.Response.OutputStream.Flush();

            // e.Request.RequestType gives the method used, GET - POST - PUSH etc.
            // e.Request.Url gives the full Uri including EVERYTHING
            // e.Request.RawUrl gives the Path following the IP. EX: if 127.0.0.1:4444/test/path.xml?test=true then /test/path.xml?test=true
            // e.Request.Path gives only the Path, not adding the params at the end. EX: if 127.0.0.1:4444/test/path.xml?test=true then /test/path.xml
            // e.Request.Params gives only the Params, not adding anything else.
        }
コード例 #6
0
        private static void GetJsonData(IDictionary<string, string> parameters, HttpRequestEventArgs e)
        {
            if (!Session.IsAuthenticated(e))
            {
                DefaultResponses.RedirectResponse(e, "/admin/login");
                return;
            }

            DefaultResponses.Json(e, Db.Entries);
        }
コード例 #7
0
        protected void http_RequestReceived(object sender, HttpRequestEventArgs e)
        {
            WSRConfig.GetInstance().logInfo("HTTP", "Request received: " + e.Request.Url.AbsoluteUri);

              // Handle custom request
              WSRConfig.GetInstance().GetWSRMicro().HandleCustomRequest(e);

              // Fake response
              using (var writer = new StreamWriter(e.Response.OutputStream)) {
            writer.Write(" ");
            writer.Flush();
            writer.Close();
              }
        }
コード例 #8
0
 public override bool IsSatisfied(HttpRequestEventArgs request)
 {
     if (!CheckHttpMethod(request)) return false;
     var actualBody = new StreamReader(request.Request.InputStream).ReadToEnd();
     var decodedBody = WebUtility.UrlDecode(actualBody);
     Console.WriteLine(decodedBody);
     return ExpectedBody.Equals(decodedBody);
 }
コード例 #9
0
 public override bool IsSatisfied(HttpRequestEventArgs request)
 {
     return CheckHttpMethod(request);
 }
コード例 #10
0
		private byte[] ServeRunExercise(HttpRequestEventArgs context, string path)
		{
			var code = context.Request.InputStream.GetString();
			var index = int.Parse(path.Substring(1, 3));
			var exercise = ((ExerciseSlide)course.Slides[index]).Exercise;
			var runResult = GetRunResult(exercise, code);
			context.Response.ContentType = "application/json; charset=utf-8";
			return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(runResult));
		}
コード例 #11
0
ファイル: HTTPServer.cs プロジェクト: berkay2578/nfsw-server
        private void nServer_RequestReceived(object sender, HttpRequestEventArgs e)
        {
            e.Response.Headers.Add("Connection", "close");
            e.Response.Headers.Add("Content-Encoding", "gzip");
            e.Response.Headers.Add("Content-Type", "application/xml;charset=utf-8");
            e.Response.Headers.Add("Status-Code", "200");

            log.Info(String.Format("Received Http-{0} request from {1}.", e.Request.HttpMethod, e.Request.RawUrl));

            Byte[] baResponseArray = null;
            List<String> splittedPath = new List<String>(e.Request.Path.Split('/'));

            String ioPath = Path.Combine(DataEx.dir_Server, e.Request.Path.Substring(1) + ".xml");

            if (splittedPath.Count >= 3)
            {
                String targetClassString = changeCaseFirst(splittedPath[2], true);
                if (splittedPath.Count == 3)
                {
                    splittedPath.Insert(0, "");
                    targetClassString = "Root";
                }
                Double dummy;
                Boolean isNumber = Double.TryParse(splittedPath[3], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dummy);
                String targetMethodString = changeCaseFirst(isNumber ? splittedPath[4] : splittedPath[3], false);
                if (!supportedMethods.Contains(targetMethodString))
                {
                    log.Warn(String.Format("Method for {0} wasn't found, using fallback XML method.", targetMethodString));
                    if (File.Exists(ioPath))
                    {
                        log.Info(String.Format("Reading XML file {0}.", ioPath));
                        baResponseArray = getResponseData(File.ReadAllText(ioPath, Encoding.UTF8));
                    }
                    else
                    {
                        log.Warn(String.Format("File {0} wasn't found, sending only 200OK.", ioPath));
                    }
                }
                else
                {
                    Type targetClass = Type.GetType("OfflineServer.Servers.Http.Classes." + targetClassString);
                    MethodInfo targetMethod = targetClass.GetMethod(targetMethodString);
                    request = e.Request;
                    log.Info(String.Format("Processing OfflineServer.HttpServer.Classes.{0}.{1}().", targetClassString, targetMethodString));
                    baResponseArray = getResponseData((string)targetMethod.Invoke(null, null));
                }
            }
            else
            {
                if (File.Exists(ioPath))
                {
                    log.Info(String.Format("Reading XML file {0}.", ioPath));
                    baResponseArray = getResponseData(File.ReadAllText(ioPath, Encoding.UTF8));
                }
                else
                {
                    log.Warn(String.Format("File {0} wasn't found, sending only 200OK.", ioPath));
                }
            }

            if (baResponseArray == null) baResponseArray = getResponseData(" ");
            e.Response.OutputStream.Write(baResponseArray, 0, baResponseArray.Length);
            e.Response.OutputStream.Flush();

            // e.Request.RequestType gives the method used, GET - POST - PUSH etc.
            // e.Request.Url gives the full Uri including EVERYTHING
            // e.Request.RawUrl gives the Path following the IP. EX: if 127.0.0.1:4444/test/path.xml?test=true then /test/path.xml?test=true
            // e.Request.Path gives only the Path, not adding the params at the end. EX: if 127.0.0.1:4444/test/path.xml?test=true then /test/path.xml
            // e.Request.Params gives only the Params, not adding anything else.
        }
コード例 #12
0
 protected virtual void OnRequestReceived(HttpRequestEventArgs e)
 {
     RequestReceived?.Invoke(this, e);
 }
コード例 #13
0
 private static void PostLogin(IDictionary<string, string> parameters, HttpRequestEventArgs e)
 {
     Session.Authenticate(e,
         x =>
         {
             DefaultResponses.RedirectResponse(x, "/admin");
             Console.WriteLine("User successfully authenticated");
         }, x =>
         {
             DefaultResponses.RedirectResponse(x, "/admin/login");
             Console.WriteLine("User failed login");
         });
 }
コード例 #14
0
        private static void PostForm(IDictionary<string, string> parameters, HttpRequestEventArgs e)
        {
            var entry = new Model.AOCEntry();
            Console.WriteLine("Entry received");

            bool avail = false;
            int score = 0;
            int.TryParse(e.Request.Form["Score"] ?? string.Empty, out score);

            var a = e.Request.Form["Availability"];
            if (!string.IsNullOrEmpty(a))
            {
                a = a.ToLowerInvariant();
                avail = a == "checked" || a == "true";
            }

            entry.FirstName = e.Request.Form["FirstName"] ?? string.Empty;
            entry.LastName = e.Request.Form["LastName"] ?? string.Empty;
            entry.Email = e.Request.Form["Email"] ?? string.Empty;
            entry.Role = e.Request.Form["Role"] ?? string.Empty;
            entry.LineManager = e.Request.Form["LineManager"] ?? string.Empty;
            entry.Reason = e.Request.Form["Reason"] ?? string.Empty;
            entry.Answers = e.Request.Form["Answers"] ?? string.Empty;
            entry.Organisation = e.Request.Form["Organisation"] ?? string.Empty;
            entry.Region = e.Request.Form["Region"] ?? string.Empty;
            entry.Available = avail;
            entry.Score = score;
            entry.Answers = e.Request.Form["Answers"] ?? string.Empty;
            entry.Submitted = DateTime.UtcNow;

            Dictionary<string, object> errors = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            if (string.IsNullOrEmpty(entry.FirstName) || entry.FirstName.Length < 2)
                errors["FirstName"] = "Please enter a first name";
            if (string.IsNullOrEmpty(entry.LastName) || entry.LastName.Length < 2)
                errors["LastName"] = "Please enter a last name";
            if (string.IsNullOrEmpty(entry.Email) || entry.Email.Length < 5)
                errors["Email"] = "Please enter an email address";
            else if (!entry.Email.ValidateEmail())
                errors["Email"] = "Please enter a valid email address";
            if (string.IsNullOrEmpty(entry.Role) || entry.Role.Length < 2)
                errors["Role"] = "Please enter a role";
            if (string.IsNullOrEmpty(entry.LineManager) || entry.LineManager.Length < 2)
                errors["LineManager"] = "Please enter the name of your line manager";
            if (string.IsNullOrEmpty(entry.Reason) || entry.Reason.Length < 2)
                errors["Reason"] = "Please tell us why you should be an Agent of Change";
            if (string.IsNullOrEmpty(entry.Organisation) || entry.Organisation.Length < 2)
                errors["Organisation"] = "Please select an organisation";
            if (string.IsNullOrEmpty(entry.Region) || entry.Region.Length < 2)
                errors["Region"] = "Please select a region";

            if (errors.Count > 0)
            {
                errors["result"] = false;
                DefaultResponses.Json(e, errors);
                Console.WriteLine("Failed entry: {0}", JsonConvert.SerializeObject(errors));
            }
            else
            {
                Db.AddEntry(entry);
                if (string.IsNullOrEmpty(Config.SuccessRedirect))
                    DefaultResponses.Json(e, new Dictionary<string, object>() { { "result", true } });
                else
                    DefaultResponses.RedirectResponse(e, Config.SuccessRedirect);
                Console.WriteLine("Successful entry from {0}", entry.Email);
            }
        }
コード例 #15
0
        private static void PostExportData(IDictionary<string, string> parameters, HttpRequestEventArgs e)
        {
            if (!Session.IsAuthenticated(e))
            {
                DefaultResponses.RedirectResponse(e, "/admin/login");
                return;
            }

            using (StringWriter sw = new StringWriter())
            {
                sw.Write("\"First name\",");
                sw.Write("\"Last name\",");
                sw.Write("\"Email\",");
                sw.Write("\"Role\",");
                sw.Write("\"Line Manager\",");
                sw.Write("\"Organisation\",");
                sw.Write("\"Region\",");
                sw.Write("\"Available\",");
                sw.Write("\"Score\",");
                sw.WriteLine("\"Reason\"");

                foreach (var entry in Db.Entries)
                {
                    sw.Write("\"" + entry.FirstName + "\",");
                    sw.Write("\"" + entry.LastName + "\",");
                    sw.Write("\"" + entry.Email + "\",");
                    sw.Write("\"" + entry.Role + "\",");
                    sw.Write("\"" + entry.LineManager + "\",");
                    sw.Write("\"" + entry.Organisation + "\",");
                    sw.Write("\"" + entry.Region + "\",");
                    sw.Write("\"" + entry.Available + "\",");
                    sw.Write("\"" + entry.Score + "\",");
                    sw.WriteLine("\"" + entry.Reason + "\"");
                }

                DefaultResponses.TextFile(e, sw.ToString(), "agents_of_change.csv", content_type: "text/csv");
            }
        }
コード例 #16
0
		private void OnHttpRequest(object sender, HttpRequestEventArgs context)
		{
			var query = context.Request.QueryString["query"];
			var path = context.Request.Url.LocalPath;
			byte[] response;
			var requestTime = DateTime.Now;
			var reloaded = ReloadCourseIfChanged(requestTime);
			if (!new[] { ".js", ".css", ".png", ".jpg", ".woff" }.Any(ext => path.EndsWith(ext)))
				Console.WriteLine($"{requestTime.ToString("T")} {context.Request.HttpMethod} {context.Request.Url}");
			switch (query)
			{
				case "needRefresh":
					response = ServeNeedRefresh(reloaded, requestTime).Result;
					break;
				case "submit":
					response = ServeRunExercise(context, path);
					break;
				default:
					response = ServeStatic(context, path);
					break;
			}
			context.Response.OutputStream.WriteAsync(response, 0, response.Length).Wait();
			context.Response.OutputStream.Close();
		}
コード例 #17
0
		private byte[] ServeStatic(HttpRequestEventArgs context, string path)
		{
			byte[] response;
			try
			{
				response = File.ReadAllBytes(htmlDir + "/" + path);
				if (path.EndsWith(".css"))
					context.Response.ContentType = "text/css; charset=utf-8";
				if (path.EndsWith(".js"))
					context.Response.ContentType = "application/x-javascript; charset=utf-8";
			}
			catch (IOException e)
			{
				context.Response.StatusCode = 404;
				context.Response.Headers["Content-Type"] = "text/plain; charset=utf-8";
				response = Encoding.UTF8.GetBytes(e.ToString());
			}
			return response;
		}
コード例 #18
0
ファイル: Program.cs プロジェクト: smile921/hak_blog
        public void recvRequest(object sender, HttpRequestEventArgs e)
        {
            using (var writer = new StreamWriter(e.Response.OutputStream))
            {

                HttpRequest request = e.Request;
                // Obtain a response object.
                HttpResponse response = e.Response;
                // Construct a response.
                System.Collections.Specialized.NameValueCollection headers = request.Headers;
                Console.WriteLine("Got Request: "+request.HttpMethod+" "+request.Url.AbsoluteUri.ToString()+"!");

                if (request.HttpMethod.ToLower().Equals("head") || request.HttpMethod.ToLower().Equals("get") || request.HttpMethod.ToLower().Equals("post") || request.HttpMethod.ToLower().Equals("options") || request.HttpMethod.ToLower().Equals("put"))
                {
                    if (request.Url.AbsoluteUri.ToString().Contains("localhost/GETHASHES"))
                    {
                        Console.WriteLine("Sending 401...");
                        if (headers["Authorization"] == null && workingUri == null)
                        {
                            Console.WriteLine("Got request for hashes...");
                            response.Headers.Add("WWW-Authenticate","NTLM");
                            response.StatusCode = 401;
                            state = 0;
                        }

                        else
                        {
                            String authHeader = headers["Authorization"];
                            byte[] ntlmBlock = getNtlmBlock(authHeader);
                            if (ntlmBlock != null && (workingUri == null || workingUri == request.Url.AbsoluteUri.ToString()))
                            {
                                workingUri = request.Url.AbsoluteUri.ToString();
                                if (state == 0)
                                {
                                    Console.WriteLine("Parsing initial NTLM auth...\n"+authHeader);
                                    smbRelayThread = new Thread(()=>smbRelay.startSMBRelay(ntlmQueue,this.cmd));
                                    smbRelayThread.Start();
                                    ntlmQueue.Enqueue(ntlmBlock);
                                    byte[] challenge = null;
                                    Config.signalHandlerClient.WaitOne();
                                    challenge = ntlmQueue.Dequeue();
                                    Console.WriteLine("Got SMB challenge " + Convert.ToBase64String(challenge));
                                    if(challenge != null){
                                        response.Headers.Add("WWW-Authenticate","NTLM " + Convert.ToBase64String(challenge));
                                        state = state + 1;
                                        response.StatusCode = 401;
                                    }
                                }
                                else if (state == 1 && request.Url.AbsoluteUri.ToString().Equals(workingUri))
                                {
                                    Console.WriteLine("Parsing final auth...");
                                    if (ntlmBlock[8] == 3)
                                    {
                                        Console.WriteLine(Convert.ToBase64String(ntlmBlock));
                                    }
                                    ntlmQueue.Enqueue(ntlmBlock);
                                    Config.signalHandler.Set();
                                    response.StatusCode = 200;
                                    state = state + 1;
                                    Config.signalHandlerClient.WaitOne();
                                    byte[] checkStatus = ntlmQueue.Dequeue();
                                    if (checkStatus[0] == 99)
                                    {
                                        writer.Close();
                                        smbRelayThread.Abort();
                                        finished.Set();
                                        return;
                                    }
                                    else
                                    {
                                        workingUri = null;
                                    }
                                }
                            }
                        }
                        writer.Close();
                        return;
                    }
                    else if (request.Url.AbsoluteUri.ToString().Equals("http://127.0.0.1/wpad.dat") || request.Url.AbsoluteUri.ToString().Equals("http://wpad/wpad.dat"))
                    {
                        Console.WriteLine("Spoofing wpad...");
                        response.StatusCode = 200;
                        String responseTxt = "function FindProxyForURL(url,host){if (dnsDomainIs(host, \"localhost\")) return \"DIRECT\";";
                        for (int i = 0; i < wpad_exclude.Length;i++ )
                        {
                            responseTxt = responseTxt + "if (dnsDomainIs(host, \"" + wpad_exclude[i] + "\")) return \"DIRECT\";";
                        }
                        responseTxt = responseTxt + "return \"PROXY 127.0.0.1:80\";}";
                        writer.Write(responseTxt);
                    }
                    else if (workingUri == null && !request.Url.AbsoluteUri.ToString().Contains("wpad") && !request.Url.AbsoluteUri.ToString().Contains("favicon"))
                    {
                        Random rnd = new Random();
                        int sess = rnd.Next(1, 1000000);
                        response.Headers.Add("Location", "http://localhost/GETHASHES"+sess);
                        Console.WriteLine("Redirecting to target.."+response.Headers["Location"]);
                        response.StatusCode = 302;
                        writer.Close();
                    }

                }
                else if (request.HttpMethod.ToLower().Equals("propfind"))
                {
                    if (request.Url.AbsoluteUri.ToString().Equals("http://localhost/test"))
                    {
                        Console.WriteLine("Got PROPFIND for /test... Responding");
                        response.StatusCode = 207;
                        response.ContentType = "application/xml";
                        writer.Write("<?xml version='1.0' encoding='UTF-8'?><ns0:multistatus xmlns:ns0=\"DAV:\"><ns0:response><ns0:href>/test/</ns0:href><ns0:propstat><ns0:prop><ns0:resourcetype><ns0:collection /></ns0:resourcetype><ns0:creationdate>2015-08-03T14:53:38Z</ns0:creationdate><ns0:getlastmodified>Tue, 11 Aug 2015 15:48:25 GMT</ns0:getlastmodified><ns0:displayname>test</ns0:displayname><ns0:lockdiscovery /><ns0:supportedlock><ns0:lockentry><ns0:lockscope><ns0:exclusive /></ns0:lockscope><ns0:locktype><ns0:write /></ns0:locktype></ns0:lockentry><ns0:lockentry><ns0:lockscope><ns0:shared /></ns0:lockscope><ns0:locktype><ns0:write /></ns0:locktype></ns0:lockentry></ns0:supportedlock></ns0:prop><ns0:status>HTTP/1.1 200 OK</ns0:status></ns0:propstat></ns0:response></ns0:multistatus>");
                        writer.Close();
                    }
                    else
                    {
                        Console.WriteLine("Got PROPFIND for "+request.Url.AbsoluteUri.ToString()+" returning 404");
                        response.StatusCode = 404;
                        writer.Close();
                    }
                }
                else
                {
                    Console.WriteLine("Got " + request.HttpMethod + " for " + request.Url.AbsoluteUri.ToString()+" replying 404");
                    response.StatusCode = 404;
                    writer.Close();
                }

            }
        }
コード例 #19
0
 private static void GetRegions(IDictionary<string, string> parameters, HttpRequestEventArgs e)
 {
     DefaultResponses.Json(e, Db.Regions.Select(p => p.Value.Name).Distinct().OrderBy(p => p, StringComparer.OrdinalIgnoreCase));
 }
コード例 #20
0
 private void OnRequestReceived(object sender, HttpRequestEventArgs e)
 {
     if (e.Request.Path != null)
     {
         using (var writer = new StreamWriter(e.Response.OutputStream))
         {
             if (!ReferenceEquals(Program.HtmlTemplate, null))
             {
                 // Render the last avaliable report
                 writer.Write(Program.HtmlTemplate.TemplateHTML);
             }
             else
             {
                 writer.Write("<h1>The report is not avaliable right now, please wait until it get generated and try again latter.</h1>");
             }
         }
     }
     else
     {
         using (var writer = new StreamWriter(e.Response.OutputStream))
         {
             writer.Write("<h1>Invalid request!</h1>");
         }
     }
 }
コード例 #21
0
 public abstract bool IsSatisfied(HttpRequestEventArgs request);
コード例 #22
0
    protected void http_RequestReceived(object sender, HttpRequestEventArgs e) {
      Log("Request received: " + e.Request.Url.AbsoluteUri);

      var qs = e.Request.Url.Query;
      var parameters = e.Request.Params;
      var files = new Dictionary<string, string>();
      var temp = ConfigManager.GetInstance().Find("http.local.temp", "AddOns/http/temp/");

      // Dump all files in a temporary directory
      foreach (string key in e.Request.Files.Keys) {
        var file = e.Request.Files.Get(key);
        if (file == null) continue;

        using (var reader = new BinaryReader(file.InputStream)) {
          var data = reader.ReadBytes(file.ContentLength);
          var path = temp + file.FileName;
          if (File.Exists(path)) { File.Delete(path); }
          File.WriteAllBytes(path, data);
          files.Add(key, path);
        }
      }

      // Fake response
      using (var writer = new StreamWriter(e.Response.OutputStream)) {

        // Handle custom request
        AddOnManager.GetInstance().BeforeHTTPRequest(qs, parameters, files, writer);

        // Write to stream
        writer.Write(" ");
        writer.Flush();
        writer.Close();
      }
      AddOnManager.GetInstance().AfterHTTPRequest(qs, parameters, files);
    }
コード例 #23
0
        protected bool CheckHttpMethod(HttpRequestEventArgs request)
        {
            var actualMethod = request.Request.HttpMethod.ToUpper();
            var result = actualMethod.Equals(HttpHttpMethod);

            if (!result) Console.WriteLine("Expected GET method but was {0}", actualMethod);
            
            return result;
        }