.netcore 堆棧調用方法小記 C#獲取當前堆棧的各調用方法列表

背景

上午臨近午餐時,公司同事反饋驗證碼被攻擊灌水。咱們匆忙查詢驗證碼明細,對已頻繁出現的IP插入黑名單,但IP仍然隔斷時間頻繁變更,不得已之下只能先封禁對應公司id的驗證碼發送功能。年初時候,專門對SSO站點的發送驗證碼升級到極驗的驗證,已經杜絕了普通的攻擊,沒想到沒升級的這個系統又遭受洗禮...css

思考辦法

防灌水通用解決辦法通常有幾種:html

  • Ip+手機號限制

頻繁變化ip和手機號時,此辦法無效windows

  • 發送驗證碼頁面端提供簡單圖形驗證碼

能解決部分攻擊。安全

  • 採起12306圖片庫或極驗等複雜手段

能解決大部分攻擊,但超過必定頻率須要收費asp.net

學到的知識點

因爲調用發送驗證碼的方法很是多,在這個方法內只能定位到IP和手機號,定位不到Web層具體的Action,在此過程當中瞭解到http://www.javashuo.com/article/p-qpilmfuu-bo.html所提到的System.Diagnostics.StackTrace和System.Diagnostics.StackFrame定位到方法上層調用堆棧。而後就順騰摸瓜把漏掉圖形驗證碼的經常使用頁面先補上,不經常使用的頁面改掉髮送接口。處理細節再也不細述,只記錄下Diagnostics的相關信息。異步

/// <summary> /// 獲取堆棧 /// </summary> /// <returns></returns> public static string GetStackTraceModelName() { //當前堆棧信息 System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame[] sfs = st.GetFrames(); //過慮的方法名稱,如下方法將不會出如今返回的方法調用列表中 string _fullName = string.Empty, _methodName = string.Empty; for (int i = 1; i < sfs.Length; ++i) { //非用戶代碼,系統方法及後面的都是系統調用,不獲取用戶代碼調用結束 if (System.Diagnostics.StackFrame.OFFSET_UNKNOWN == sfs[i].GetILOffset()) break; var methedInfo = sfs[i].GetMethod(); _methodName = methedInfo.ReflectedType.FullName + "." + methedInfo.Name;//方法名稱 //sfs[i].GetFileLineNumber();//沒有PDB文件的狀況下將始終返回0 // if (_filterdName.Contains(_methodName)) continue; _fullName = _methodName + "()\r\n->" + _fullName; } st = null; sfs = null; return _fullName.TrimEnd('-', '>'); } 

下面咱們定義一些代碼來演示效果:post

public class First { public string Start() { return new Second().Start(); } } public class Second { public string Start() { return new Third().Start(); } } public class Third { public string Start() { var msg = Utils.GetStackTraceModelName(); return msg; } } 

而後在Web層調用First.Startui

public class HomeController : Controller { public IActionResult Start() { var msg = new First().Start(); return Content(msg); } } 

訪問結果以下:url

Web.Controllers.HomeController.Start() ->Venus.Common.First.Start() ->Venus.Common.Second.Start() ->Venus.Common.Third.Start() 

這個調用信息是由Third.Start記錄,可見能追蹤到完整的調用鏈。這只是簡單的演示,如更復雜的交叉調用,異步、並行等的並未在這裏實踐。spa

擴展思考

以上方法適用於.netFramework和.netCore,可用於作日誌記錄,調用鏈等行爲。
asp.netcore裏也有Microsoft.AspNetCore.Diagnostics,https://www.cnblogs.com/linezero/p/Diagnostics.html

略做總結,本篇結束,那幫閒的蛋疼亂搞攻擊的人,折騰了我一天。雖然已經禁了他們發送驗證碼,但仍是一直在發請求,頭疼ying....留個念頭以待之後深思。

安全和防禦依然是重中之重啊!

參考連接

C#獲取當前堆棧的各調用方法列表
windows管理員利器之用Log Parser Studio分析IIS日誌
相關文章
相關標籤/搜索