Skip to content

Commit

Permalink
fix some mssql connectio error,
Browse files Browse the repository at this point in the history
prevent sql injection by addind parameters to execute queries,
add authentication sample,
auto install required modues on startup
  • Loading branch information
mehdika2 committed Dec 26, 2024
1 parent 7c9380c commit 38580ef
Show file tree
Hide file tree
Showing 23 changed files with 6,258 additions and 62 deletions.
2 changes: 1 addition & 1 deletion Core/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace Mahi.Core
{
internal class Logger : IDisposable
public class Logger : IDisposable
{
private StreamWriter writer;

Expand Down
20 changes: 19 additions & 1 deletion Core/LuaInvoker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using NLua;
using Mahi.HtmLua;
using System.Data.SqlClient;
using System.Collections.Specialized;

namespace Mahi.Core
{
Expand All @@ -26,12 +27,14 @@ public static void Run(string script, MemoryStream stream, HttpRequest request,
lua.RegisterFunction("go", builtInFunctions, typeof(BuiltInFunctions).GetMethod("go"));

// register response helpers
lua.RegisterFunction("log", builtInFunctions, typeof(BuiltInFunctions).GetMethod("log"));
lua.RegisterFunction("setStatus", builtInFunctions, typeof(BuiltInFunctions).GetMethod("setStatus"));
lua.RegisterFunction("redirect", builtInFunctions, typeof(BuiltInFunctions).GetMethod("redirect"));
lua.RegisterFunction("addHeader", builtInFunctions, typeof(BuiltInFunctions).GetMethod("addHeader"));
lua.RegisterFunction("setCookie", builtInFunctions, typeof(BuiltInFunctions).GetMethod("setCookie"));
lua.RegisterFunction("deleteCookie", builtInFunctions, typeof(BuiltInFunctions).GetMethod("deleteCookie"));
lua.RegisterFunction("create_mssql_connection", builtInFunctions, typeof(BuiltInFunctions).GetMethod("create_mssql_connection"));
lua.RegisterFunction("isNullOrEmpty", builtInFunctions, typeof(BuiltInFunctions).GetMethod("isNullOrEmpty"));

// contains key built in function
lua.DoString("function containsKey(table, key) return table[key] ~= nil end");
Expand All @@ -43,11 +46,13 @@ public static void Run(string script, MemoryStream stream, HttpRequest request,
httpVersion = request.HttpVersion,
headers = ConvertDictionaryToLuaTable(lua, request.Headers.ToDictionary(i => i.Name, i => i.Value)),
cookies = ConvertDictionaryToLuaTable(lua, request.Cookies.ToDictionary(i => i.Name, i => i.Value)),
post = ConvertDictionaryToLuaTable(lua, request.RequestParameters),
get = ConvertDictionaryToLuaTable(lua, request.UrlParameters),
isMultipartRequest = request.IsMultipartRequest,
content = request.Content,
items = request.Items,
userAddress = request.Items["R_IP_ADDRESS"],
userPort = request.Items["R_IP_PORT"]
userPort = request.Items["R_IP_PORT"],
};

lua["response"] = new ResponseContext(lua, response);
Expand Down Expand Up @@ -79,5 +84,18 @@ public static LuaTable ConvertDictionaryToLuaTable(Lua lua, Dictionary<string, s

return table;
}

public static LuaTable ConvertDictionaryToLuaTable(Lua lua, NameValueCollection collection)
{
var table = lua.DoString("return {}")[0] as LuaTable;

if (collection == null)
return table;

foreach (var key in collection.AllKeys)
table[key] = collection[key];

return table;
}
}
}
8 changes: 7 additions & 1 deletion Core/RequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using NLua;
using Mahi.HtmLua;
using Mahi.Properties;
using static Mahi.Core.Logger;
using NLua.Exceptions;

namespace Mahi.Core
{
Expand Down Expand Up @@ -86,6 +86,12 @@ static void HandleContext(HttpRequest request, HttpResponse response, MemoryStre

LuaInvoker.Run(script, stream, request, response);
}
catch (LuaScriptException ex)
{
response.StatusCode = 500;
response.StatusText = "Internal Server Error";
HandleException(ex.InnerException ?? ex, stream);
}
catch (Exception ex)
{
response.StatusCode = 500;
Expand Down
11 changes: 11 additions & 0 deletions HtmLua/BuiltInFunctions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Fardin;
using Mahi.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLua;
Expand Down Expand Up @@ -32,6 +33,11 @@ public void go(object html)
_html += html?.ToString();
}

public void log(string text)
{
Program.Log(text);
}

public void setStatus(int status, string text = null)
{
response.StatusCode = status;
Expand Down Expand Up @@ -83,5 +89,10 @@ public SqlConnection create_mssql_connection(string connectionString)
{
return new SqlConnection(connectionString);
}

public bool isNullOrEmpty(string input)
{
return string.IsNullOrWhiteSpace(input);
}
}
}
3 changes: 3 additions & 0 deletions HtmLua/HtmLuaParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ void ParseIdentifier()
stringOpen = !stringOpen;
break;
case '\r':
case '<':
case ' ':
if (!stringOpen && openParentheses == 0)
{
Expand Down Expand Up @@ -323,6 +324,8 @@ string GetTagName()
case '$':
Parse();
break;
case '\n':
case '\r':
case ' ':
if (!endTagName)
endTagName = true;
Expand Down
4 changes: 3 additions & 1 deletion HtmLua/SelfClosingTags.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ public static class SelfClosingTags
"keygen",
"param",
"source",
"track"
"track",
"path",
"!--"
};
}
}
18 changes: 13 additions & 5 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ static void Main()
Console.Title = "Mahi1.0.0";

// installing default modules
if (Environment.GetCommandLineArgs().Contains("-i"))
InstallModules();
InstallModules();

// var server = new HttpServer(IPAddress.Parse(ip), port, "cert.pfx", Resources.CertificationPassword);
var server = new HttpServer(IPAddress.Parse(ip), port);
Expand Down Expand Up @@ -60,9 +59,18 @@ static void InstallModules()
if (!Directory.Exists(moduesDirectory))
Directory.CreateDirectory(moduesDirectory);

File.WriteAllText(Path.Combine(moduesDirectory, "json.lua"), Resources.dkjson);
File.WriteAllText(Path.Combine(moduesDirectory, "mssql.lua"), Resources.mssql);
}
string jsonModulePath = Path.Combine(moduesDirectory, "json.lua");
if (!File.Exists(jsonModulePath))
File.WriteAllText(jsonModulePath, Encoding.UTF8.GetString(Resources.dkjson));

string mssqlModulePath = Path.Combine(moduesDirectory, "mssql.lua");
if (!File.Exists(mssqlModulePath))
File.WriteAllText(mssqlModulePath, Encoding.UTF8.GetString(Resources.mssql));

string hashModulePath = Path.Combine(moduesDirectory, "hash.lua");
if (!File.Exists(hashModulePath))
File.WriteAllText(hashModulePath, Encoding.UTF8.GetString(Resources.hash));
}

internal static void Log(string message, bool newLine = true)
=> logger.Log(message, newLine);
Expand Down
63 changes: 18 additions & 45 deletions Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,13 @@
&lt;/html&gt;</value>
</data>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="dkjson" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\dkjson.lua;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="mssql" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\mssql.lua;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
<value>..\Resources\mssql.lua;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
<data name="dkjson" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\dkjson.lua;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
<data name="hash" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\hash.lua;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>
</root>
1 change: 0 additions & 1 deletion README.FA.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@
- اطمینان حاصل کنید که فایل‌های صفحه در پوشه `wwwapp` قرار دارند:

7. **قرار دادن ماژول‌های مورد نیاز**:
- برای نصب ماژول های پیشفرض از دستور ```mahi -i``` بعد از ساخت پروژه استفاده کنید
- می‌توانید ماژول‌ها را دانلود کرده و در پوشه `modules` قرار دهید

## اعتباردهی
Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ Before you can run this project, you need to have the following installed:
- Ensure that the page files are placed in the `wwwapp` folder:

7. **Place Required Modules**:
- To install default modules use ```mahi -i``` command after build
- You can download modules and palce it in `modules` folder

## Credits
Expand Down
Loading

0 comments on commit 38580ef

Please sign in to comment.