有恶意请求,增加恶意请求的拦截

如题
This commit is contained in:
tianshuanbao
2025-12-19 16:58:44 +08:00
parent fe9a71d896
commit 7963156155
13 changed files with 637 additions and 446 deletions

View File

@@ -81,7 +81,18 @@ namespace WebSite.Controllers
/// <returns></returns>
private Host CheckRoomNumber(string code, string creatDate, ref string msg, ref int hotelID, string roomNumber = "")
{
SysHotel sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
string Key = "GetHotelInfo_" + code + "_" + creatDate;
var Obj = MemoryCacheHelper.Get(Key);
SysHotel sysHotel = null;
if (Obj == null)
{
sysHotel = SysHotelManager.GetByCode(code, Convert.ToDateTime(creatDate));
MemoryCacheHelper.SlideSet(Key, sysHotel, new TimeSpan(0, 5, 0));
}
else
{
sysHotel = Obj as SysHotel;
}
if (sysHotel == null)
{
msg = "酒店未知";
@@ -91,7 +102,19 @@ namespace WebSite.Controllers
hotelID = sysHotel.ID;
if (!string.IsNullOrEmpty(roomNumber))
{
Host host = HostManager.GetByRoomNumber(roomNumber, sysHotel.ID);
Host host = null;
string Key1 = "QueryHostInfo_" + roomNumber + "_" + sysHotel.ID;
var ooo = MemoryCacheHelper.Get(Key1);
if (ooo != null)
{
host = ooo as Host;
}
else
{
host = HostManager.GetByRoomNumber(roomNumber, sysHotel.ID);
MemoryCacheHelper.SlideSet(Key1, host, new TimeSpan(0, 5, 0));
}
if (host == null)
{
msg = "房号[" + roomNumber + "]不存在";
@@ -3411,117 +3434,118 @@ namespace WebSite.Controllers
[HttpPost()]
public ActionResult GetAirDetectListPost()
{
Task.Factory.StartNew(() =>
//Task.Factory.StartNew(() =>
// {
// });
try
{
List<KongQi> listdata = GetPrepareData();
var QQQ = listdata.GroupBy(A => new { A.HotelID, A.HotelCode, A.RoomNumber, A.CreatDate });
foreach (var itemKey in QQQ)
{
try
var item = itemKey.Key;
string roomNumber = item.RoomNumber;
string code = item.HotelCode;
string createDate = item.CreatDate;
DateTime dts = DateTime.Parse(createDate);
string cd = dts.ToString("yyyy-MM-dd");
Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
if (host == null)
{
List<KongQi> listdata = GetPrepareData();
logger.Error("host not exists hotelcode: " + code + " createDate: " + cd + " roomnumber: " + roomNumber);
continue;
//return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
}
if (host != null)
{
var hostModals = HostModalManager.Load(host.ID, DeviceType.AirDetect).Where(r => r.Modal.WXActiveIndicator);
var QQQ = listdata.GroupBy(A => new { A.HotelID, A.HotelCode, A.RoomNumber, A.CreatDate });
TimeSpan ts = DateTime.Now.ToLocalTime() - new DateTime(1970, 1, 1, 8, 0, 0, 0, DateTimeKind.Utc);
string current_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
foreach (var itemKey in QQQ)
KongQiReport re = new KongQiReport();
re.hotel_code = code;
re.room_no = roomNumber;
re.time = current_timestamp;
string md5key = Tools.MD5Encrypt(baojing_airreport_key);
//hotel_code=酒店编码&time=时间戳&key=密钥
string sss = string.Format("hotel_code={0}&time={1}&key={2}", code, current_timestamp, md5key);
//logger.Error("sss is: " + sss);
string sign = Tools.MD5Encrypt(sss).ToLower();
re.sign = sign;
foreach (HostModal modal in hostModals)
{
var item = itemKey.Key;
string roomNumber = item.RoomNumber;
string code = item.HotelCode;
string createDate = item.CreatDate;
DateTime dts = DateTime.Parse(createDate);
string cd = dts.ToString("yyyy-MM-dd");
//string Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName);
string ModalAddress = modal.Modal.ModalAddress;
Host host = CheckRoomNumber(code, cd, ref msg, ref hotelID, roomNumber);
if (host == null)
string status = modal.Brightness.ToString();
string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + ModalAddress;
var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
if (obj != null)
{
logger.Error("host not exists hotelcode: " + code + " createDate: " + cd + " roomnumber: " + roomNumber);
continue;
//return Json(new { IsSuccess = false, Result = msg }, JsonRequestBehavior.AllowGet);
HostModal_Cache hhh = obj as HostModal_Cache;
status = hhh.Brightness.ToString();
}
if (host != null)
switch (ModalAddress)
{
var hostModals = HostModalManager.Load(host.ID, DeviceType.AirDetect).Where(r => r.Modal.WXActiveIndicator);
case "009000001"://CO2浓度 ppm
re.co2 = status;
break;
case "009000002"://甲醛浓度 ug/m3 实际显示单位为mg/M3
re.methanal = status;
break;
case "009000003"://TVOC浓度 ug/m3 实际显示单位为mg/M3
re.tvoc = status;
break;
case "009000004"://PM2.5浓度 ug/m3
re.pm25 = status;
break;
case "009000005"://PM10浓度 ug/m3
re.pm10 = status;
break;
case "009000006"://温度 度
re.temperature = status;
break;
case "009000007"://湿度 %RH
re.humidness = status;
break;
TimeSpan ts = DateTime.Now.ToLocalTime() - new DateTime(1970, 1, 1, 8, 0, 0, 0, DateTimeKind.Utc);
string current_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
KongQiReport re = new KongQiReport();
re.hotel_code = code;
re.room_no = roomNumber;
re.time = current_timestamp;
string md5key = Tools.MD5Encrypt(baojing_airreport_key);
//hotel_code=酒店编码&time=时间戳&key=密钥
string sss = string.Format("hotel_code={0}&time={1}&key={2}", code, current_timestamp, md5key);
//logger.Error("sss is: " + sss);
string sign = Tools.MD5Encrypt(sss).ToLower();
re.sign = sign;
foreach (HostModal modal in hostModals)
{
//string Name = ReturnNameByLanguage(modal.Modal.Name, modal.Modal.EnglishName, modal.Modal.TWName);
string ModalAddress = modal.Modal.ModalAddress;
string status = modal.Brightness.ToString();
string KKey = CacheKey.HostModalStatus_Prefix + "_" + host.ID + "_" + ModalAddress;
var obj = CSRedisCacheHelper.Get_Partition<HostModal_Cache>(KKey);
if (obj != null)
{
HostModal_Cache hhh = obj as HostModal_Cache;
status = hhh.Brightness.ToString();
}
switch (ModalAddress)
{
case "009000001"://CO2浓度 ppm
re.co2 = status;
break;
case "009000002"://甲醛浓度 ug/m3 实际显示单位为mg/M3
re.methanal = status;
break;
case "009000003"://TVOC浓度 ug/m3 实际显示单位为mg/M3
re.tvoc = status;
break;
case "009000004"://PM2.5浓度 ug/m3
re.pm25 = status;
break;
case "009000005"://PM10浓度 ug/m3
re.pm10 = status;
break;
case "009000006"://温度 度
re.temperature = status;
break;
case "009000007"://湿度 %RH
re.humidness = status;
break;
default:
break;
}
}
//list{Name名称)ModalAddress回路 地址Brightness, Status对应值}
var client1 = new RestClient(AirReport_Address);
var request1 = new RestRequest("/rcu/v1/air", Method.POST);
request1.RequestFormat = DataFormat.Json;
//string json = Newtonsoft.Json.JsonConvert.SerializeObject(re);
//logger.Error("空气质量送了数据:" + AirReport_Address+" data: "+json);
request1.AddJsonBody(re);
client1.ExecuteAsync(request1, (response) =>
{
string result = response.Content;
//logger.Error("空气质量返回了:"+result);
});
default:
break;
}
}
//list{Name名称)ModalAddress回路 地址Brightness, Status对应值}
var client1 = new RestClient(AirReport_Address);
var request1 = new RestRequest("/rcu/v1/air", Method.POST);
request1.RequestFormat = DataFormat.Json;
//string json = Newtonsoft.Json.JsonConvert.SerializeObject(re);
//logger.Error("空气质量送了数据:" + AirReport_Address+" data: "+json);
request1.AddJsonBody(re);
client1.ExecuteAsync(request1, (response) =>
{
string result = response.Content;
//logger.Error("空气质量返回了:"+result);
});
}
catch (Exception ex)
{
logger.Error(ex.Message + ex.StackTrace);
//return Json(new { IsSuccess = false, Result = ex.Message }, JsonRequestBehavior.AllowGet);
}
});
}
}
catch (Exception ex)
{
logger.Error(ex.Message + ex.StackTrace);
//return Json(new { IsSuccess = false, Result = ex.Message }, JsonRequestBehavior.AllowGet);
}
return Json(new { IsSuccess = true, Result = "sucess" }, JsonRequestBehavior.AllowGet);
}
@@ -3754,7 +3778,7 @@ namespace WebSite.Controllers
});
}
var QQQ = result.ToList();
QQQ.Sort();
//QQQ.Sort();
return Json(new { total = result.Count, rows = QQQ });
//var statusList = HostUpdateStatusManager.LoadAll().Where(r => r.HostUpdate.ID == hostUpdateID).Select(r => new { id = r.ID, hostID = r.Host.ID, status = r.Status });
@@ -4137,18 +4161,24 @@ namespace WebSite.Controllers
var QQQ = client1.Execute(request1);
string ddd = QQQ.Content;
var FFFA = Newtonsoft.Json.JsonConvert.DeserializeObject<QueryOrderResponse>(ddd);
var D1 = FFFA.data.FirstOrDefault(A => A["item_uuid"].Equals(CleanUUID));
if (D1 != null)
if (!string.IsNullOrEmpty(CleanUUID))
{
string V = "";
D1.TryGetValue("job_status", out V);
if (V.Equals("cancelled"))
if (FFFA != null && FFFA.data != null && FFFA.data.Count > 0)
{
Host host = new Host();
host.HostNumber = HostNUMBER;
HostModal s = new HostModal();
s.Modal = new RoomTypeModal() { ModalAddress = "004000003", Type = DeviceType.ServiceInfo };
HostModalManager.SetDevice(host, s, 0, 0);
var D1 = FFFA.data.FirstOrDefault(A => A["item_uuid"].Equals(CleanUUID));
if (D1 != null)
{
string V = "";
D1.TryGetValue("job_status", out V);
if (V.Equals("cancelled"))
{
Host host = new Host();
host.HostNumber = HostNUMBER;
HostModal s = new HostModal();
s.Modal = new RoomTypeModal() { ModalAddress = "004000003", Type = DeviceType.ServiceInfo };
HostModalManager.SetDevice(host, s, 0, 0);
}
}
}
}
}
@@ -5118,6 +5148,7 @@ namespace WebSite.Controllers
long jishu_error = Interlocked.Read(ref MvcApplication.UDPServerErrorCount);
if (jishu_error >= 3)
{
logger.Error("重启了UDP服务器");
Interlocked.Exchange(ref MvcApplication.UDPServerErrorCount, 0);
var hostServer = (IHostServer)MvcApplication.cxt.GetObject("RCUHost.HostServer");
hostServer.Start();

View File

@@ -117,11 +117,12 @@ namespace WebSite.Controllers
public ActionResult LogOn()
{
string result = "";
if (!Common.MyDes.Validate(ref result))
{
ViewData["Msg"] = result;
return View("License");
}
//这个是公网没有必要再验证证书了
//if (!Common.MyDes.Validate(ref result))
//{
// ViewData["Msg"] = result;
// return View("License");
//}
if (Request.Cookies["Account"] != null)
{
ViewData["Account"] = HttpUtility.UrlDecode(Request.Cookies["Account"].Value);

View File

@@ -1541,7 +1541,7 @@ namespace WebSite.Controllers
bool bsa = hostModal.Modal.Type == DeviceType.AirConditioner;
string KKKey = System.Guid.NewGuid().ToString("N");
bool wendu1 = KongTiaoControlName.Equals("IncrementTemperatureRequest") || KongTiaoControlName.Equals("IncrementTemperatureRequest")||KongTiaoControlName.Equals("SetTemperatureRequest");
bool wendu1 = KongTiaoControlName.Equals("IncrementTemperatureRequest") || KongTiaoControlName.Equals("IncrementTemperatureRequest") || KongTiaoControlName.Equals("SetTemperatureRequest");
bool fengsu1 = KongTiaoControlName.Equals("SetFanSpeedRequest") || KongTiaoControlName.Equals("IncrementFanSpeedRequest") || KongTiaoControlName.Equals("DecrementFanSpeedRequest");
bool moshi1 = KongTiaoControlName.Equals("SetModeRequest");
//特殊酒店
@@ -6291,7 +6291,9 @@ namespace WebSite.Controllers
resp.status = 1;
string nnn = Newtonsoft.Json.JsonConvert.SerializeObject(resp);
logger.Error("投诉信息给宝镜推送: " + nnn);
XuanZhuOperation.ReportService(ttt.Item3, resp);
//XuanZhuOperation.ReportService(ttt.Item3, resp);
MyHttp.SendHttpData(ttt.Item3, resp);
}, tup);
}

View File

@@ -94,6 +94,7 @@ namespace WebSite
}
protected override void Application_Start(object sender, EventArgs e)
{
logger.Error("Web重启了");
// 在应用程序启动时调用
PreHot();
log4net.Config.XmlConfigurator.Configure();//初始化log4net
@@ -279,16 +280,17 @@ namespace WebSite
{
try
{
hostServer.Close();
System.Threading.Thread.Sleep(5000);
System.Net.WebRequest request = System.Net.WebRequest.Create(currentUrl);
System.Net.WebResponse response = request.GetResponse();
logger.Error("系统重启Web服务");
response.Close();
//hostServer.Close();
//System.Threading.Thread.Sleep(5000);
//System.Net.WebRequest request = System.Net.WebRequest.Create(currentUrl);
//System.Net.WebResponse response = request.GetResponse();
//logger.Error("系统重启Web服务");
//response.Close();
}
catch (Exception)
catch (Exception ex)
{
logger.Error("重启原因为:" + ex.Message);
logger.Error(ex.StackTrace);
}
}
@@ -696,10 +698,10 @@ namespace WebSite
_client.UpdateCheckInOrOutRecord(dr["Code"].ToString(), Convert.ToInt64(dr["ID"]), flag);//更新已同步状态
string RoomNUM = dr["RoomNumber"].ToString();
var T = new Tuple<int, string,RoomStatus>(hotelID,RoomNUM,roomStatus);
var T = new Tuple<int, string, RoomStatus>(hotelID, RoomNUM, roomStatus);
Task.Factory.StartNew((state) =>
{
var T1 = state as Tuple<int, string,RoomStatus>;
var T1 = state as Tuple<int, string, RoomStatus>;
Host host = HostManager.GetByRoomNumber(T1.Item2, T1.Item1);
if (host != null)
{
@@ -711,7 +713,7 @@ namespace WebSite
ddd.Status = T1.Item3;
CSRedisCacheHelper.Set_PartitionWithForever<RoomStatusRequest>(Key, ddd);
}
},T);
}, T);
}
/// <summary>
/// 定时上报主机异常记录
@@ -737,13 +739,119 @@ namespace WebSite
resp.status = 2;
resp.faultType = 1;
resp.faultData = 1;
XuanZhuOperation.ReportService(hotel.FaultPushURL, resp);
//XuanZhuOperation.ReportService(hotel.FaultPushURL, resp);
MyHttp.SendHttpData(hotel.FaultPushURL, resp);
}
}
logger.Error(string.Format("定时上报酒店({0})主机异常记录", hotel.Code));
}
}, System.Threading.CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
protected void Application_Error(object sender, EventArgs e)
{
try
{
Exception ex = Server.GetLastError();
logger.Error("IIS:" + ex.Message);
logger.Error(ex.StackTrace);
}
catch (Exception ex)
{
logger.Error("IIS Exception:" + ex.Message);
}
}
// 存储恶意IP和请求频率
private static ConcurrentDictionary<string, RequestInfo> _ipRequests = new ConcurrentDictionary<string, RequestInfo>();
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
var ip = Request.UserHostAddress;
var url = Request.Url.AbsolutePath.ToLower();
// 定义要拦截的路径模式
var maliciousPatterns = new[]
{
@".*\.git/*",
@"^/sdk",
@"^/HNAP1",
@"^/evox",
@"^/nmaplowercheck",
@"^/phpmyadmin",
@"^/admin",
@"^/wp-login",
@"^/shell",
@"^/cmd",
@".*\.php$",
@".*\.asp$",
@".*\.git/credentials"
//@".*\.aspx$"
};
// 检查是否为恶意路径
if (maliciousPatterns.Any(pattern => System.Text.RegularExpressions.Regex.IsMatch(url, pattern)))
{
LogMaliciousRequest(ip, url);
Response.StatusCode = 403;
//Response.End();
Context.ApplicationInstance.CompleteRequest();
return;
}
// 频率限制(可选)
if (IsMaliciousRequestRate(ip))
{
Response.StatusCode = 429; // Too Many Requests
Context.ApplicationInstance.CompleteRequest();
//Response.End();
return;
}
}
catch (Exception ex)
{
logger.Error("恶意请求出错了:" + ex.Message);
}
}
private void LogMaliciousRequest(string ip, string url)
{
logger.Error("恶意IP:" + ip + " URL:" + url);
}
private bool IsMaliciousRequestRate(string ip)
{
// 简单的频率检查逻辑
var now = DateTime.UtcNow;
var info = _ipRequests.GetOrAdd(ip, _ => new RequestInfo());
lock (info)
{
info.RequestCount++;
info.LastRequest = now;
// 如果1分钟内超过100次请求认为是恶意请求
if (info.RequestCount > 100 && (now - info.FirstRequest).TotalMinutes < 1)
{
return true;
}
}
return false;
}
private class RequestInfo
{
public RequestInfo()
{
this.FirstRequest = DateTime.UtcNow;
}
public int RequestCount { get; set; }
public DateTime FirstRequest { get; set; }
public DateTime LastRequest { get; set; }
}
/// <summary>
/// 获取当前登录帐号
/// </summary>