示例#1
0
 private void Listen()
 {
     PDLogger.Log($"Starting HTTP Listener on port {_port.ToString()}", 4);
     _listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
     PDLogger.Log($"Started listening from endpoint http://*:{ _port.ToString()}/", 3);
     try
     {
         _listener.Start();
         while (true)
         {
             try
             {
                 HttpListenerContext context = _listener.GetContext();
                 Process(context);
             }
             catch (Exception ex)
             {
                 PDLogger.Log($"Non breaking listener Error:: {ex.Message}", 5);
             }
         }
     }
     catch (Exception ex)
     {
         PDLogger.Log($"Listener error: {ex.Message} ({ex.HResult.ToString()})", 1, ex.StackTrace);
         return;
     }
 }
示例#2
0
 private void Initialize(string path, int port)
 {
     this._rootDirectory = path;
     this._port          = port;
     _serverThread       = new Thread(this.Listen);
     PDLogger.Log($"CREATING THREAD:: {_serverThread.Name} ", 5);
     _serverThread.Start();
 }
示例#3
0
 public void createApplicationEndpoint(string endpoint, string folder)
 {
     currentApp.appFolder = folder;
     p.Webpages.Add(new CSharpWebpage(endpoint + "/form", currentApp.runForm));
     PDLogger.Log($"CREATED APPLICATION ENDPOINT {endpoint + "/form"}", 5);
     p.Webpages.Add(new CSharpWebpage(endpoint + "/run", currentApp.runScript));
     PDLogger.Log($"CREATED APPLICATION ENDPOINT {endpoint + "/run"}", 5);
     p.Webpages.Add(new CSharpWebpage(endpoint + "/assets", currentApp.assets));
     PDLogger.Log($"CREATED APPLICATION ENDPOINT {endpoint + "/assets"}", 5);
     p.Webpages.Add(new CSharpWebpage(endpoint, currentApp.cback));
     PDLogger.Log($"CREATED APPLICATION ENDPOINT {endpoint}", 5);
 }
示例#4
0
        private PluginEngine.Plugin.PluginArrayScope getScope(string plugin)
        {
            PDLogger.Log($"GETTING PLUGIN SCOPE:: {plugin}.cs", 5);
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters param    = new CompilerParameters {
                GenerateExecutable = false, GenerateInMemory = true
            };

            param.ReferencedAssemblies.Add("Peridot.dll");
            param.ReferencedAssemblies.Add("System.dll");
            string appFolder = "plugins/";

            foreach (string file in Directory.GetFiles("plugins/"))
            {
                FileInfo f = new FileInfo(file);
                if (f.Name.Contains(".dll"))
                {
                    param.ReferencedAssemblies.Add(f.Name);
                }
            }
            PDLogger.Log($"Loaded internal librarys for {plugin}", 5);
            string          scriptToExecute = plugin + ".cs";
            string          src             = File.ReadAllText(appFolder + "/" + scriptToExecute);
            CompilerResults results         = provider.CompileAssemblyFromSource(param, src);

            if (results.Errors.Count != 0)
            {
                PDLogger.Log($"Failed to load plugin: {scriptToExecute} (Compiler errors)", 1);
                foreach (CompilerError error in results.Errors)
                {
                    PDLogger.Log($"{error.ErrorText} in line {error.Line} ({error.ErrorNumber})", 1);
                }
                return(PluginEngine.Plugin.PluginArrayScope.None);
            }
            PDLogger.Log($"COMPILED SCRIPT:: {plugin}.cs", 5);
            try
            {
                object     o  = results.CompiledAssembly.CreateInstance("PeridotApp." + plugin);
                MethodInfo mi = o.GetType().GetMethod("scope");
                PluginEngine.Plugin.PluginArrayScope scope = (PluginEngine.Plugin.PluginArrayScope)mi.Invoke(o, null);
            }
            catch (Exception ex)
            {
                PDLogger.Log($"Failed to run script: {scriptToExecute} ({ex.Message})", 1);
            }
            return(PluginEngine.Plugin.PluginArrayScope.None);
        }
示例#5
0
 public void addPlugin(string pluginName)
 {
     PDLogger.Log($"Registered Plugin:: {pluginName}", 3);
     p.Plugins.Add(pluginName);
 }
示例#6
0
        private void Process(HttpListenerContext context)
        {
            PDLogger.Log($"Traffic on {context.Request.Url} by {context.Request.RemoteEndPoint.Address.ToString()} ({context.Request.UserHostName})", 4);
            string filename = context.Request.Url.AbsolutePath;
            bool   found    = false;

            foreach (CSharpWebpage pe in Webpages)
            {
                PDLogger.Log($"FINDING CANDIDATE: {pe.PageLink} &&  IN ({filename})", 5);
                if (filename.Contains("/" + pe.PageLink))
                {
                    found = true;
                    PDLogger.Log($"Setting Traffic to PDX Endpoint", 4);
                    PDLogger.Log($"Executing PDX Endpoint ID:: {pe.PageLink}", 5);

                    pe.WEBPAGE_Callback(new Session(context));

                    PDLogger.Log($"Finished Processing PDX Endpoint ID:: {pe.PageLink}", 5);
                    return;
                }
            }
            if (!found)
            {
                //Console.WriteLine(filename);


                filename = filename.Substring(1);

                foreach (CustomEndpoint end in customEndpoints)
                {
                    if (end.Hostname + ":" + end.port.ToString() == context.Request.UserHostName || end.Hostname == context.Request.UserHostName)
                    {
                        bool   allow  = true;
                        string reason = "NONE GIVEN";
                        PDLogger.Log($"Entering custom endpoint {end.Hostname}", 4);
                        if (end.IPWhitelist.Count > 0)
                        {
                            allow = false;
                            foreach (string ip in end.IPWhitelist)
                            {
                                if (ip == context.Request.RemoteEndPoint.Address.ToString())
                                {
                                    reason = "IP_WHITELIST_ENABLED";
                                    allow  = true;
                                }
                            }
                        }
                        foreach (string blacklist in end.IPBlacklist)
                        {
                            if (blacklist == context.Request.RemoteEndPoint.Address.ToString())
                            {
                                reason = "IP_BLACKLIST_MATCH";
                                allow  = false;
                            }
                        }

                        if (end.UserCredentials.Count > 0)
                        {
                            bool    authed   = false;
                            Session iSession = new Session(context);
                            string  auth     = iSession.GetCookie("PERIDOT_USER_BASIC_AUTH");
                            if (auth == null || auth == "")
                            {
                                iSession.CreateCookie("PERIDOT_USER_BASIC_AUTH", "request");
                                writeHtml(context, Config.ErrorConfig.Login, HttpStatusCode.OK);
                                return;
                            }
                            else if (auth == "request")
                            {
                                string text;
                                using (var reader = new StreamReader(context.Request.InputStream,
                                                                     context.Request.ContentEncoding))
                                {
                                    text = reader.ReadToEnd();
                                }
                                if (getFormEncode(text, "username") != null && getFormEncode(text, "password") != null)
                                {
                                    foreach (AuthCredentials authc in end.UserCredentials)
                                    {
                                        if (authc.Username == getFormEncode(text, "username") && getFormEncode(text, "password") == authc.Password)
                                        {
                                            authed = true;
                                            string newtoken = RandomString(40);

                                            iSession.CreateCookie("PERIDOT_USER_BASIC_AUTH", newtoken);
                                            authc.Token = newtoken;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                foreach (AuthCredentials authc in end.UserCredentials)
                                {
                                    if (authc.Token == auth)
                                    {
                                        authed = true;
                                    }
                                }
                            }
                            if (!authed)
                            {
                                PDLogger.Log("ERROR 401 GIVEN - REASON: INVALID CREDENTIALS/AUTH TOKEN. REAUTHORIZATION REQUIRED.", 4);
                                iSession.CreateCookie("PERIDOT_USER_BASIC_AUTH", "request");
                                writeHtml(context, Config.ErrorConfig.Error401, HttpStatusCode.Unauthorized);

                                return;
                            }
                        }
                        if (!allow)
                        {
                            PDLogger.Log($"ERROR 404 GIVEN - REASON: {reason}", 4);
                            writeHtml(context, Config.ErrorConfig.Error403, HttpStatusCode.Forbidden);
                            return;
                        }
                        filename = Path.Combine(end.Directory, filename);
                        if (filename.Contains(".") == false)
                        {
                            filename += "/index.html";
                        }
                        if (File.Exists(filename))
                        {
                            try
                            {
                                Stream input = new FileStream(filename, FileMode.Open);

                                //Adding permanent http response headers
                                string mime;
                                context.Response.ContentType     = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime) ? mime : "application/octet-stream";
                                context.Response.ContentLength64 = input.Length;
                                context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                                context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));
                                context.Response.AddHeader("Cache-Control", "no-cache");
                                byte[] buffer = new byte[1024 * 16];
                                int    nbytes;
                                while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    context.Response.OutputStream.Write(buffer, 0, nbytes);
                                }
                                input.Close();

                                context.Response.StatusCode = (int)HttpStatusCode.OK;
                                context.Response.OutputStream.Flush();
                            }
                            catch (Exception ex)
                            {
                                PDLogger.Log($"Internal Server Error:: {ex.Message} in PERIDOT_HTTP_FEEDBACK_SENDER", 1);
                                writeHtml(context, Config.ErrorConfig.Error500, HttpStatusCode.InternalServerError);
                                // context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                            }
                        }
                        else
                        {
                            PDLogger.Log($"Error 404 on request {context.Request.Url}", 4);
                            writeHtml(context, Config.ErrorConfig.Error404, HttpStatusCode.NotFound);
                            // context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        }
                    }
                }

                filename = Path.Combine(_rootDirectory, filename);
                if (filename.Contains(".") == false)
                {
                    PDLogger.Log($"Resolving URL to {filename}/index.html", 5);
                    filename += "/index.html";
                }
                if (File.Exists(filename))
                {
                    try
                    {
                        Stream input = new FileStream(filename, FileMode.Open);

                        //Adding permanent http response headers
                        string mime;
                        context.Response.ContentType     = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime) ? mime : "application/octet-stream";
                        context.Response.ContentLength64 = input.Length;
                        context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                        context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));
                        context.Response.AddHeader("Cache-Control", "no-cache");
                        byte[] buffer = new byte[1024 * 16];
                        int    nbytes;
                        while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            context.Response.OutputStream.Write(buffer, 0, nbytes);
                        }
                        input.Close();

                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.OutputStream.Flush();
                    }
                    catch (Exception ex)
                    {
                        PDLogger.Log($"Internal Server Error:: {ex.Message} in PERIDOT_HTTP_FEEDBACK_SENDER", 1);
                        writeHtml(context, Config.ErrorConfig.Error500, HttpStatusCode.InternalServerError);
                        // context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    }
                }
                else
                {
                    PDLogger.Log($"Error 404 on request {context.Request.Url}", 4);
                    writeHtml(context, Config.ErrorConfig.Error404, HttpStatusCode.NotFound);
                    // context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                }

                context.Response.OutputStream.Close();
            }
        }
示例#7
0
 public void addCustomEndpoint(CustomEndpoint e)
 {
     customEndpoints.Add(e);
     _listener.Prefixes.Add($"http://{e.Hostname}:{e.port}/");
     PDLogger.Log($"Started listening from endpoint http://{e.Hostname}:{e.port}/", 3);
 }