2011年12月29日 星期四

jQuery 與 XPath 的比較

資料來源:
http://www.ibm.com/developerworks/xml/library/x-xpathjquery/index.html?ca=drs-
or
http://www.smartwei.com/xpath-vs-jquery.html
(是同一篇)


大致上, 就是只能在 jQuery 裡用到很簡單的 xPath, 太複雜的 xpath 語法就沒辦法,
簡單來說, 就是把 xpath 的 / 換成 空格, 就可以在 jQuery 裡執行,
遇到要選擇第幾個 element 時, 就用 : 或用 contains()
參考看看:
http://www.w3school.com.cn/jquery/jquery_ref_selectors.asp

jQuery 的 [] 中括號, 好像只能用來處理屬性的樣子.

jQuery 教程 + jQuery 参考手册

jQuery 教程 + jQuery 参考手册
URL: http://www.w3school.com.cn/jquery/index.asp

自從我看了這個站, 對 jQuery 更加的了解到, 要怎麼去使用,
像是

$('#test').val('2')
這行的功能, 是把 id='test' 的 value 設成 '2'

$('#test').val()
這行的功能, 是取得 id='test' 的 value.


.html() 用用法同 .val()

FileZilla是最好用的 ftp client 和 ftp server

ftp server download:
http://filezilla-project.org/download.php?type=server

* 說明, 在 user account 的設定上很直覺, 也有良好的管理者設定介面.


-----------------------------
ftp client download:
http://filezilla-project.org/download.php?type=client

* 說明: 穩定性高, 還會自動升級(更新) 既有的設定也不會因為升級就不見.

資料庫的內容繁轉簡(Big5 to GB)

要怎麼把 table 裡的 data, 轉成簡體(或繁體),
step 1: 開出 table 的欄位資訊.
step 2: 用loop 取得每一筆要被更新的 record.
step 3: 透過元件取出欄位內容, 繁轉簡之後, 放回去欄位裡, 再透過 recoredset.update 更新回 table 裡.


程式的說明:



程式碼:


* 說明1: open recordset, 記得不要開成 readonly, 醬子才可以用 recordset.update 更新資料.




* 說明2: 針對 table 的 TYPE_NAME 有 text 或 char 型別的, 才需要做內容的轉換.



執行結果:


==================================
相關說明:
----------------
Set RsObject = Server.CreateObject(”ADODB.Recordset:”)
RsObject.Open 資料來源,資料連結,指標型態,鎖定方式
資料來源:指定資料表名稱
資料連結:指定一個已Connection的物件


指標型態:
----------------
0:只能向前移動的指標,此為預設值
1:無法讀取其他使用著新增之資料,更新之資料會立即反應
2:可以及時反應其他使用著操作資料庫之狀況
3:無法及時反映其他使用著操作相同資料庫的狀況用於搜尋或新增記錄時使用


鎖定方式:
----------------
1:將Recordset 開啟為唯讀狀態,此為預設值
2:當使用著對Recordset 中的某筆資料作編輯時店鎖定記錄
3:當使用著呼叫Update方法對Recordset做更新時才鎖定記錄
4:使用著做批次更新時才鎖定記錄


===================================

原理是 call windows kernel32.dll 裡的 LCMapString  function, 理論上只要是可以 call dll 的 programming language 都可以做到offline 的簡/繁互轉.


如果您的需求和我一樣, 只是想把文字內容的簡繁部分轉換, 並不是想轉成 big5 或 gb, 整個輸出入都是 unicode, 而且也不想破壞其他非簡繁文字部分的話, 那麼結論就是照著本篇文章的一開始的 d1, d2 範例呼叫 VB 的 Strings.StrConv 帶上 0x0009 或是其他 SingleByte 字集的 localeID 當成第三個參數就可以啦!!!
如果不想引入 Microsoft.VisualBasic.dll (別問為什麼, 純屬個人偏好) 又想要做到相同的效果, 做法也很簡單, 請參考以下的範例程式碼!!!

public static class ChineseStringUtility
{
    internal const int LOCALE_SYSTEM_DEFAULT = 0x0800;
    internal const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
    internal const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;

    [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    internal static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int cchSrc, [Out] string lpDestStr, int cchDest);

    public static string ToSimplified(string source)
    {
        String target = new String(' ', source.Length);
        int ret = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_SIMPLIFIED_CHINESE, source, source.Length, target, source.Length);
        return target;
    }

    public static string ToTraditional(string source)
    {
        String target = new String(' ', source.Length);
        int ret = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_TRADITIONAL_CHINESE, source, source.Length, target, source.Length);
        return target;
    }
}




2011年12月28日 星期三

[IIS].AspScriptFileCacheSize 在記憶體裡快取asp檔案

IIS 裡有一個設定, 透過增加快取的 asp, 讓程式在執行時, 可以快一點被執行完.

透過 GUI 設定方式如下:
-------------------------
1. Open the IIS MMC.
2. Right-click Web Sites, then click Properties.
3. On the Home Directory tab, click Configuration.
4. On the Cache Options tab, select Cache all requested ASP files.
5. Type a new value for ASP files cached in memory and click OK.
6. Click the Cache Options tab. Note that the value in the ASP files cached in memory text box is 999999.




透過指令的設定方式如下:
-------------------------
1. Open a command prompt.
2. Type cd inetpub\adminscripts.
3. Type adsutil set w3svc/AspScriptFileCacheSize "1-999999".


理論上, asp 程式碼的個數小於500支的話, 就用預設值就ok了, 預設好像是快取500支程式檔案.




資料來源:
-------------------------
BUG: Cannot Modify the Maximum Number of ASP Files Cached in Memory with the IIS MMC
http://support.microsoft.com/kb/308182/en-us

AspScriptFileCacheSize
http://msdn.microsoft.com/en-us/library/ms525870(v=vs.90).aspx

AspScriptFileCacheSize Metabase Property (IIS 6.0)
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0596baf9-41c7-4459-bbc0-0c5d5d9fbd8b.mspx?mfr=true

jQuery 教學 - 基礎篇

資料來源:
----------------------------------------------
http://jsgears.com/thread-63-1-1.html



簡介:
----------------------------------------------
jQuery 是一套 JavaScript 的 Library,因此,你必須稍具 JavaScript 的基礎,jQuery 主要是用在 DOM 文件的操作,包含「快速選取元素(Element)」並且「做一些事情」,快速選取元素可以讓你一次選取單一或多個的元素,然後你可以將這些被選取的元素做一些改變,例如隱藏、顯示等等。此外 jQuery 的核心程式還加強了非同步傳輸(AJAX)以及事件(Event)的功能。



快速選取元素:
----------------------------------------------
jQuery 怎麼用來「快速選取元素」並且「做一些事情」呢?請看看程式碼:
$("div").addClass("special");

錢記號 $ 是 jQuery 的物件,使用 $("div") 就是用 jQuery 來選取元素,這個範例可以選取文件內所有的 <div> 元素。後面接著的 .addClass("special") 就是用來做一些事情,這個範例是將先前所選取到的所有元素都加上一個名為 "special" 的 class。也就是透過 $("div").addClass("special") 的語法,可以讓你一次幫文件上有的 <div> 元素都加入 special 的 class。



做一些事情:
----------------------------------------------
使用 jQuery 來選取元素之後,接下來當然就是要來對這些選取到的元素做些改變囉。透過 jQuery 內建的函數,你可以:

1.對 DOM 進行操作,例如對文件節點的新增或修改
2.添加事件處理
3.做一些基本的視覺效果,例如隱藏、顯示、下拉顯示、淡出淡入等等
4.使用 AJAX 傳送表單內容或取得遠端文件



[範例] 選取所有有 target 屬性的 <a>,並且在其節點下加入一段文字。
$("a[target]").append(" (Opens in New Window)");
這是一段原始的 HTML :
<a href="http://jsgears.com">jsGears</a>
<a href="http://google.com" target="_blank">Google</a>
<a href="http://amazon.com" target="_blank">Amazon</a>
選取有 target 屬性並加入文字後的結果:
<a href="http://jsgears.com">jsGears</a>
<a href="http://google.com" target="_blank">Google (Opens in New Window)</a>
<a href="http://amazon.com" target="_blank">Amazon (Opens in New Window)</a>



連續地使用函數(Chaining):
----------------------------------------------
jQuery 很重要的一個特性是可以連續地使用函數(Chaining),當你選取了一個或一組的元素後,可以連續對這些元素進行多個處理。以下範例會將所有的 <div> 隱藏,修改文字顏色為藍色,再將 <div> 以下拉布幕的效果顯示出來:
$("div").hide();
$("div").css("color", "blue");
$("div").slideDown();
這樣的三行程式碼可以用以下一行的程式碼取代,結果會是完全相同的:
$("div").hide().css("color", "blue").slideDown();




相關的教學文章:
----------------------------------------------
jQuery 學習筆記
網址:http://blog.ericsk.org/archives/tag/jquery-tut
作者:ericsk
部落格:國二學生認真打雜

自製 jQuery Plugin
網址:http://www.jaceju.net/blog/?p=336 (Part 1)
http://www.jaceju.net/blog/?p=337 (Part 2)
作者:jace ju
部落格:網站製作學習誌

jQuery 手冊- 選擇器(Selectors 1.2)
網址:http://jquery.shian.tw/selectors.php
作者:遨遊飛翔
部落格:遨遊飛翔

邊做邊學 jQuery 系列 (有圖有文有影片、適合 ASP.NET 的開發者)
網址:http://msdn.microsoft.com/zh-tw/asp.net/dd446623.aspx
作者:Jeffrey
部落格:黑暗執行緒



相關的範例下載:
----------------------------------------------
http://jsgears.com/tag.php?name=jQuery


官方網站:
----------------------------------------------
http://jquery.com/

2011年12月22日 星期四

IIS Logs 分析工具 - indihiang

官方網站:
http://indihiang.codeplex.com/

How to use(使用方法):
http://wiki.indihiang.com/default.aspx?AspxAutoDetectCookieSupport=1

執行畫面:


source code 下載:
http://indihiang.codeplex.com/SourceControl/list/changesets


建議開啟下列的3個欄位, 以便可以分析到更多的資訊:



相關文章:
------------------------------------------------
介紹好用工具:Visual Log Parser ( 視覺化操作 LP 語法 )
http://blog.miniasp.com/post/2009/02/Useful-tool-Visual-Log-Parser.aspx

visuallogparser:
http://visuallogparser.codeplex.com/

Log Parser-記錄檔分析器:
http://www.weithenn.org/cgi-bin/wiki.pl?Log_Parser-%E8%A8%98%E9%8C%84%E6%AA%94%E5%88%86%E6%9E%90%E5%99%A8

Log Parser 2.2:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=24659

2011年12月20日 星期二

[Asp].Randomize 對亂數產生器做初始化的動作

當使用者上傳檔案到主機上時,通常會依亂數重新命名, 但為了避免同一個時間點(同一分同一秒)有人同時傳檔案, 程式同時被呼叫, 產生出一樣的檔案, 所以會使用 rnd() 取亂數指令,
但...如果沒有Randomize做初始化亂數產生器,每次更新後產生的數字都會一樣.


沒有下的話, 如下圖, 最後幾碼都一樣, 因為 rnd() 進亂數表的進入點是相同的.



多下一行 Randomize
就有立竿見影的功效, 檔名的後幾碼就不再固定是 02867.



道理很簡單, 奇怪的是大家滿容易乎略, 覺得電腦預設應該就要是 randomized 過.

[SQL].stored procedure 拒絕 EXECUTE 權限

重新安裝系統, db user 只開放 data_reader + data_writer 權限, 所以一執行 stored procedure 就掛掉, 錯誤訊息如下:
--------------------------
結構描述 'dbo',資料庫 'myDatabase',物件 'sp_myStoredProcedure' 拒絕 EXECUTE 權限。


(方案1) 懶人解決辦法:
--------------------------
1. 建立新的 Role. (例如: myDbUserRole)
2. 設定 myDbUserRole 是某一個 database 的 dbo.
3. 設定登入的 userid 屬於該 role.


(方案2) 比較花時間的建議的解決辦法:
--------------------------
1. 建立新的 Role. (例如: myDbUserRole)
2. 設定 myDbUserRole 是某一個 database 的 dbreader + dbwriter.
3. 針對要允許的 物件 開放應該給予的權限, 可能需要設定的物件分別有:
3.1 stored procedure
3.2 function
3.3 view

權限給太多 = 出事時資料會被偷走, 或系統會有被hack 風險.
權限給太少 = 程式三不五十會出錯, 因為權限不夠...


結論:
--------------------------
如果您的系統略重要, 或會被外部的複雜的 internet access, 請使用方案2.
應急(或偷懶)的話請使用方案1.



相關文章:
--------------------------
google search: GRANT EXECUTE ON sp_columns

create role:
http://65.55.20.225/zh-tw/library/ms187936.aspx

資料庫層級角色:
http://65.55.20.225/zh-tw/library/ms189121.aspx

認識 資料庫層級角色(Database Role)
http://maxtellyou.blogspot.com/2011/12/database-role.html

2011年12月19日 星期一

程式可以存取使用實體檔案時,應避免使用http去取得檔案

程式可以存取使用實體檔案時,應避免使用http去取得檔案,
因為透過http 需要花費更多的記憶體 + CPU時間 + 工作項目 + IIS log.

例如某一行指令:
LoadXMLurl = myHttpURL & "/configFolder/Settings.xml"


建議修改成:
LoadXMLurl = server.mappath("/configFolder") & "\Settings.xml"

[Asp].queryString 阻擋單引號比較好的解法

假設您有2道關卡, 來阻擋 hacker 的 sql injection,
第1道關卡: 寫在所有的 include 檔的第1行裡, 固定會執行.
第2道關卡: 寫在,每一個 request 指令之後, 用來判斷接收到的變數內容的正確及合法性.

* 附註: 聽說攻擊的方式, 不只有用單引號, 所以其實第1道關卡不是必須的, 但一定要在每一程式寫好第2道關卡進行檢查.


由於在 querystring 裡, %27 與 ' (單引號) 是不同的, 但直接擋掉 %27 感覺又怪怪的, 不知道會不會擋到不知名的中文字. 所以之前寫:
if instr(request.querystring(),"%27") > 0 then
...
end if


置換成:
if isQueryStringContainQuota() then
...
end if



'// purpose: check is querystring Contains quota.
'// ex: ret = isQueryStringContantQuota()
'// return:
' True: Found!
' False: not Found.
function isQueryStringContainQuota()
dim returnValue
returnValue = not True '// default: not found.

dim strSingleQuota
strSingleQuota = "'"

dim qItem
for each qItem in request.querystring
if instr(trim("" & request.querystring(qItem)),strSingleQuota) > 0 then
returnValue = True
exit for
end if
next

isQueryStringContainQuota = returnValue
end function

robots.txt 攔截所有的機器人的設定值

資料來源: http://zh.wikipedia.org/wiki/Robots.txt

直接設成下面這2行, 禁止所有 spider 或 crawl 來存取您的網站,
通常管理介面, 不希望他們來 趴, 免得程式沒寫好被發理:
--------------------
User-agent: *
Disallow: /




* 附註: 通常管理用的後台, 不需要進 search engine 裡...

2011年12月15日 星期四

違反_PRIMARY_KEY_條件約束_'PK_iCount'。無法在物件_'dbo.iCount'_中插入重複的索引鍵。

在 IIS 的 log 裡看到, 500 Error,
出錯的程式碼片斷, 是在處理 "點閱率",
點閱率 (iCount) table 的定義是: (docID, date, counter)

三不五十會有人重覆插入, 造成 Error, trace source code, 發現, 同一時間, 2個人去 select database 的確可能都還沒有被 insert data 進去, 但2個人一起去 insert 就會出錯.

由於不是很重要的資料, 所以, 加一個 on error resume next 的指令, 到 insert command 前, 讓程式不要產生 500 error 就先交差了. 之後再找時間來想其他辦法.

避免在排程(tasks)的地方使用管理者帳號執行

排程很方便, 有時候可以解化掉程式的流程, 我猜應該避免在排程的地方使用管理者帳號執行, 假設有心人者知道伺服器主機固定會執行某一支的 .vbs (或 .bat 或 .exe) 檔案, 並透過漏洞(http 或 ftp 之類) 上傳檔案到該目錄下, 伺服器主機可能會有被提升權限的風險.


排程設定的畫面:

* 附註: 這個 "執行身分" 用的帳號, 最好權限設定的超小, 最好是在 Guests group 而不是 User group 裡.


排程被執行後, 在系統的日誌裡, 可以看到該帳號通過驗證做登入.



相關文章: [IIS].關於 IUSER 帳號的相關設定
http://maxtellyou.blogspot.com/2011/12/iis-iuser.html

2011年12月14日 星期三

認識 資料庫層級角色(Database Role)

理論上, 一般的操作(select/insert/update/delete),似乎開 reader + writer 就ok了, 需要開到 db_owner, 可以避免萬一被 SQL Inject 後, 最糟的情況是 data 的部份被刪除和被偷走...



資料庫層級角色名稱+說明:
-----------------------------
db_owner 固定資料庫角色的成員可以在資料庫上執行所有的組態和維護活動,也可以卸除資料庫。
db_securityadmin 固定資料庫角色的成員可以修改角色成員資格及管理權限。將主體加入這個角色可能會產生不必要的權限擴大。
db_accessadmin 固定資料庫角色的成員可以針對 Windows 登入、Windows 群組及 SQL Server 登入加入或移除資料庫的存取權。
db_backupoperator 固定資料庫角色的成員可以備份資料庫。
db_ddladmin 固定資料庫角色的成員可在資料庫中執行任何「資料定義語言」(DDL) 的命令。
db_datawriter 固定資料庫角色的成員可以加入、刪除或變更所有使用者資料表中的資料。
db_datareader 固定資料庫角色的成員可以從所有使用者資料表讀取所有資料。


資料來源: 資料庫層級角色
http://msdn.microsoft.com/zh-tw/library/ms189121.aspx

認識 .NET Framework 4.0 Client Profile

今天在發佈寫的 exe 檔時, 發現有
(1).NET Framework 4.0 Client Profile 和
(2).NET Framework 4.0

這2個可以選, 原來 Client Profile, 指的是比較小包的版本,
不包含下列4個完整版才提供的功能:

(1) ASP.NET
(2) 進階 Windows Communication Foundation (WCF) 功能
(3) NET Framework Data Provider for Oracle
(4) 編譯用 MSBuild


附註: 沒有用到 3.0 , 3.5, 或 4.0之後的新功能, 似乎用 .NET Framework 2.0 來發佈, 相容性應該會比較好.




The .NET Framework 4 Client Profile 包含下列功能:
Common Language Runtime (CLR)
ClickOnce
Windows Forms
Windows Presentation Foundation (WPF)
Windows Communication Foundation (WCF)
Entity Framework
Windows Workflow Foundation
語音
XSLT 支援
LINQ to SQL
Entity Framework 與 WCF Data Services 執行期設計函式庫。
Managed Extensibility Framework (MEF)
動態型別。
並列程式設計功能,例如 Task Parallel Library (TPL), Parallel LINQ (PLINQ), and Coordination Data Structures (CDS)
除錯用戶端應用程式。


資料來源:
http://www.dotblogs.com.tw/regionbbs/archive/2010/03/25/vs2010.net.4.client.profile.aspx

[IIS].關於 IUSER 帳號的相關設定


如果您的案子, 不是使用 IUSER 而是自行定義的 USER account,
請記得把這個 User 做以下的設定:

1. user 的群組, 請移掉 User group, 加入 guests group.
2. 不允許 遠端登入.
3. 不允許 登入伺服器.


設好帳號之後, 有4個地方可能會需對這個帳號做設定:
1.資料夾(實體檔案)的 "安全性" 設定.
2.IIS 站台.
3.IIS application pool.
4.元件. (參考下圖).


2011年12月13日 星期二

[c#].透過 Get Http Header 執行 web app 的排程

公司同事建議不要使用 wget(或 tinyGet) 來執行某一個 URL 來排程, 我發現, 只需要觸發 HEAD, 該 URL 的程式就會被執行, 所以不需要使用到 wget.


用 c# 寫, 程式碼居然, 只有短短 2行就寫完, 呵呵呵, 真方便:
-----------------------------------------
WebRequest request = WebRequest.Create("http://www.yourdomain.com/");
request.GetResponse();


source code download:
-----------------------------------------
http://max-free-app.googlecode.com/files/MaxGetHttpHeader.zip


檔案說明:
-----------------------------------------
MaxGetHttpHeader.exe 取得 http URL header.

* PS: 執行時需要安裝 .net 2.0



相關文章:
-----------------------------------------
資料來源1: 如何使用 WebRequest 類別傳送資料
http://msdn.microsoft.com/zh-tw/library/debx8sh9(v=vs.80).aspx#Y3000

資料來源2: Get HTTP header
http://www.jonasjohn.de/snippets/csharp/get-http-header.htm

資料來源3: HTTPGet.cs | C# .NET 2.0 HTTP GET Class
http://www.goldb.org/httpgetcsharp.html

資料來源4: 如何:使用 C# .NET 進行 GET 要求
http://support.microsoft.com/kb/307023

資料來源5: TechEd 2008 補充: 使用 Tinyget + Logparser 進行網站程式自動測試
http://blogs.msdn.com/b/roberthu/archive/2008/09/30/teched-2008-tinyget-logparser.aspx


* 附註: 我個人是覺得 tinyGet 應該沒問題, 只是自己寫的 GetHttpHeader 可能會更好, 呵呵呵~

2011年12月12日 星期一

button tag 與 input tag 的 type=button

今天在看 IIS 發現很多的 500 Error, 怕系統被滲透, 所以緊張地按照 log 裡 user 操作的方式, 看看怎麼操作會發生 Error, 結果是因為 chrome browser 在處理完 button tag 後, 會比照 submit tag 一樣, 做 submit, 如果被 submit 的那支程式有寫沒好, 沒有檢查欄位內容, 就會出錯.


之前與別的同事共同開發系統, 從來沒用過 button tag, 建議避免使用 button tag:
<button onclick="javascript:document.getElementById('fieldid').value='';">清除</button>

改用 input tag:
<input type="button" onclick="javascript:document.getElementById('fieldid').value='';" value="清除" />

研究 URLRewriter

之前寫過利用 404 status 實作 URLRewriter(短路徑) 的文章:
http://maxtellyou.blogspot.com/2010/05/aspvirtual-directory.html

google 了一下, 似乎有其他不錯的解決辦法,

研究中的文章1: URL rewrite with asp.net 4.0 and IIS7
http://www.jphellemons.nl/post/URL-rewrite-with-aspnet-40-and-IIS7.aspx

研究中的文章2: URL Rewriting in ASP.NET
http://msdn.microsoft.com/en-us/library/ms972974.aspx

2011年12月9日 星期五

每一個 request 都要檢查後, 再放進去 database 裡做操作

建議程式裡的每一個 request 都要檢查後, 再放進去 database 裡做操作,

舉例, case 是畫面上有很多筆資料, 要整批做更新,
假設有一段 SQL command 要執行, 有人是直接醬子寫.

一般正常的操作流程下, 程式不會出問題, 但如果有人亂輸入內容, 程式就會發生 500 Error, 例如 user 輸入 &dir, 由於 Num 欄位和 Seq 欄位都是 int 型別, 所以輸竹了文字的資料, 就會發生錯誤:
將_nvarchar_值_'&dir'_轉換成資料類型_int_時,轉換失敗。


針對這個 case 要降低 500 Error 發生的機率, 請先把 request 到的資料, 放到變數裡, 先經過簡單的前置檢查後, 再把變數的內容放到 sql command 裡來執行, 建議的寫法如下:



我猜 input FORM 裡會輸入的資料, 大致上分成: 數字 和 文字2種,
數字的話, 使用 isNumeric() 應該就可以解決掉大部份的變數內容檢查,
文字的話, 建議先從 database 裡的 column 來限制收到的變數的長度, 最好可以再針對欄位內容做過濾, 像是不允許內容出現 SQL 指令, 和部份 stored procedure 指令.

單引號' 在 querystring() 裡與 %27 是不同的

有用防火牆不一定安全, 因為有些攻擊的方法, 一樣是走 80 port 進來您的系統後, 再做滲透.
使用外部的 filter 來擋 SQL Injection 的單引號, 也不一定安全, 因為 filter 可能沒寫好, 如果寫好, 可能會安全一點點.

最近在看 IIS Log, 有一支 demo-1.asp 程式裡的 id 欄位, 忘了增加前置檢查, 直接去 access databae, 結果..., 現在發現的2個小問題:
1. Site 1 傳回給 user 的 status, 居然是 302, 而不是 200.
2. Site 1 的 filter 功能沒擋成功, 把單引號丟給實際 Access Database 的程式.




架構說明:
-----------------
Site 1 的 demo-1.asp 是在與 User 的 browser 的互動, 裡面沒有寫程式, 單純的做單引號的過濾, 就去呼叫 Site 2 的 demo-2.asp



Site 1 (與User browser 互連的程式) 的 IIS log
---------------------------------
201X-XX-XX 17:03:14 GET /demo-1.asp id=-1%27%20or%20%273%27%3d%273 80 - xxx.xxx.xxx.xxx Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+6.0) 302 0 0


Site 2 (實際程式) 的 IIS log
---------------------------------
201X-XX-XX 17:03:14 GET /demo-2.asp id=-1%27%20or%20%273%27%3d%273&|316|80040e07|將_nvarchar_值_'-1'_or_'3'='3'_轉換成資料類型_int_時,轉換失敗。 80 - 127.0.0.1 Mozilla/4.0+(compatible;+MSIE+5.00;+Windows+98) 500 0 0



手動地開啟 chrome 在 Site 1 上做測試,
輸入單引號, 有被程式判斷到, 並導回首頁. status=200
---------------------------------
2011-12-09 02:59:41 GET /demo-1.asp id=-1'%20or%20'3'='3 80 - 10.10.x.x Chrome/17.0.963.0 200 0 0


輸入單引號 (%27), 有被程式判斷到, 並導回首頁. status=200
---------------------------------
2011-12-09 03:10:24 GET /demo-1.asp id=1%27%20or%20%273%27 80 - 10.10.x.x Chrome/17.0.963.0 200 0 0


* 附註: 有問題的地方在, 為什麼之前的 IIS 的 log , status=302 而不是 200.


接下來, 我發現 request.querystring() 裡 %27 並不等於 ' (單引號),
測試的程式如下:
if instr(request.querystring(),"'") > 0 then
response.write "querystring found ' sign!"
else
response.write "pass ' sign query string check."
end if

if instr(request.querystring(),"%27") > 0 then
response.write "querystring found %27 sign!"
else
response.write "pass %27 query string check."
end if

URL 裡輸入 id=', 可以被第1個 if 判斷到, 但無法通過第2個 if 判斷.
URL 裡輸入 id=%27, 可以被第2個 if 判斷到, 但無法通過第1個 if 判斷.

* 附註: 如果您是使用 request("id") 的話, 會取得的是 ' 而不是 %27. (合乎常理).


結論1: 關於 querystring 的部份, 建議增加一個 %27 的判斷.

結論2: 如果要在第1關的 filter 裡擋單引號的話, 用 for each 來一個個的把 form 的資料 request 出來後, 再做判斷, 可能會擋的比較確實.

結論3: 每一支程式, 的每一個 request 應該都要詳細檢查要放進去 database 處理的變數是否為乾淨的(沒有被Hacker修改).

2011年12月8日 星期四

[Asp].isNumeric()函數測試

如果您有一個變數, 確定 URL 輸入時, 必需是數字, 可以使用 isNumeric 來做數字的驗證, 降低被 SQL Injection 滲透的機率.

asp code
--------------------------
id = "123"
response.write "(" & id & "): " & isNumeric(id)



執行完的結果如下:
--------------------------
(123): True
(+123): True
(-123): True
(1+23): False
(12-3): False
(1*23): False
(12/3): False
(12\3): False
(&123): True
(&dir): False
($123): False
(0x123): False
(1=23): False
(1=1): False
--------------------------



結論:
確定是數字的變數, 可以多增加一個 isNumeric() 來做前置檢查.
確定是 text 的欄位, 可以多增加一個檢查輸入的句字中, 是不有包含不允許使用的 SQL command.

[IIS].Log 裡的200 0 64(sc-win32-status)

看到 IIS Log 裡大部份都是 200 0 0 , 但有幾筆卻是顯示:
200 0 64, google 了一下, 答案可能是:

sc-status = 200
sc-substatus = 0
sc-win32-status = 64
The error for status 64 is: "The specified network name is no longer available."


sc-win32-status of 64 means "The specified network name is no longer available". It usually occurs when the client reset the connection after getting the last packet rather than doing a graceful close of the connection. In client server architecture after IIS has sent final response to client typically it waits for ACK message form client. Now certain clients instead of sending final ACK back to server, resets the connections which are not and graceful connection close and hence IIS logs “64” in IIS logs. Many clients will reset the connection when they are done with it, to free up the socket instead of leaving it in TIME_WAIT/CLOSE_WAIT. Proxies tend to do it more than others do, hence win 32 status code of 64 should be reviewed only if necessary.


資料來源:
http://column.iresearch.cn/u/lesishu/archives/2008/39752.shtml

Notepad++ RegExp 處理 IIS log

正規表示法(regular expression, RegExp)是一個很方便的工具, 這比較像是 Linux 世界的人在使用的工具, 因為都沒有 GUI. 這次要用 NotePad++ 所附的 RegExp 解決的是, 只看 IIS "確定有" 異常的 log 的部份.


使用步驟:
----------------------
step 1: 用 Notepad++ 開啟 IIS log 檔, 並用 save as... 另存新檔.

step 2: 使用 replace ,
Find: ^201(.*) 200 0 0
Replace as: (不要填)
按下 Replace ALL


附註: 理論上, status = 302 的也可以刪掉, 302 是指「Object Moved」
Find: ^201(.*) 320 0 0


step 3: 全選, 再用 TextFX 裡的 TextFX Edit 裡的 Delete Blank Lines.

OK, 大功告成.



附註:
----------------------
status=200, 並不是不重要, 也不代表程式沒問題,
status=500 指的就是程式確定出問題!



進階應用:
----------------------
假設您的 IIS log 多開了3個欄位(sc-bytes cs-bytes time-taken), 可以試試看下列這幾組:

^20(.*) 200 ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)
^20(.*) 302 ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)
^20(.*) 404 ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)


相關文章:
----------------------
Notepad++ RegExp sample, 幫 request("xxx") 加副程式
http://maxtellyou.blogspot.com/2011/12/notepad-regexp-sample-requestxxx.html


第十二章、正規表示法與文件格式化處理
http://linux.vbird.org/linux_basic/0330regularex.php

Notepad++ RegExp sample, 幫 request("xxx") 加副程式

修改前:
str=request("item")


Notepad++ 裡設定
Fine what: request\("([A-Z0-9_]+)"\)
Replace as: htmlEncode(request("\1"))


Replace 結果:
str=htmlEncode(request("item"))


Notepad++官方說明文章如下:

Notepad++ RegExp List
Note: In case you have the plugins installed, try CONTROL+R or in the Menu Plugins � TextFX Quick - Find/Replace to get a sophisticated dialogue including a drop down for regular expressions and multi line search/replace.
In a regular expression, special characters interpreted are:
.Matches any character
(This marks the start of a region for tagging a match; so what's inside ( ) you can use in "replace with" using \1, \2 etc.
)This marks the end of a tagged region.
\nWhere n is 1 through 9 refers to the first through ninth tagged region when replacing. For example, if the search string was Fred([1-9])XXX and the replace string was Sam\1YYY , when applied to Fred2XXX this would generate Sam2YYY .
\<This matches the start of a word using Scintilla's definitions of words.
\>This matches the end of a word using Scintilla's definition of words.
\xThis allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...]This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...]The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^This matches the start of a line (unless used inside a set, see above).
$This matches the end of a line.
*This matches 0 or more times. For example, Sa*m matches Sm , Sam , Saam , Saaam and so on.
+This matches 1 or more times. For example, Sa+m matches Sam , Saam , Saaam and so on.

Source of this information is the Scintilla edit component help, but it was adapted to Notepad++ behaviour.
Notepad++ RegExp Examples
Important
  • You have to check the box "regular expression" in search & replace dialog
  • When copying the strings out of here, pay close attention not to have additional spaces in front of them! Then the RegExp will not work!
You use a MediaWiki (e.g. WikipediaWikitravel) and want to make all headings one "level higher", so a H2 becomes a H1 etc.
  1. Search ^=(=)
    Replace with \1
    Click "Replace all" to find all headings2...9 (two equal sign characters are required) which begin at line beginning (^) and to replace the two equal sign characters by only the last of the two, so eleminating one and having one remaining.
  2. Search =(=)$
    Replace with \1
    Click "Replace all" to find all headings2...9 (two equal sign characters are required) which end at line ending ($) and to replace the two equal sign characters by only the last of the two, so eleminating one and having one remaining.
  3. == title == became = title =, you're done :-)
You have a document with a lot of dates, which are in German date format (dd.mm.yy) and you'd like to transform them to sortable format (yy-mm-dd). Don't be afraid by the length of the search term – it's long, but consiting of pretty easy and short parts.
  1. Search ([^0-9])([0123][0-9])\.([01][0-9])\.([0-9][0-9])([^0-9])
    Replace with \1\4-\3-\2\5
    Click "Replace all" to fetch
    • the day, whose first number can only be 0, 1, 2 or 3
    • the month, whose first number can only be 0 or 1
    • but only if the spearator is . and not any charcter ( . versus \. )
    • but only if no numbers are sourrounding the date, as then it might be an IP address instead of a date
    and to write all of this in the opposite order, except for the surroundings. Pay attention: Whatever SEARCH matches will be deleted and only replaced by the stuff in the REPLACE field, thus it is mandtory to have the surroundings in the REPLACE field as well!
  2. 31.12.97 became 97-12-31 and 14.08.05 became 05-08-14 and the IP address 14.13.14.14 did not change, you're done :-)
You have printed in windows a file list using dir /b/s >filelist.txt to the file filelist.txt and want to make local URLs out of them.
  1. Open filelist.txt with Notepad++
  2. Search \\
    Replace with /
    Click "Replace all" to change windows path separator char \  into URL path separator char / 
  3. Search ^(.*)$
    Replace with file:///\1
    Click "Replace all" to add file:/// in the beginning of all lines
  4. Depended on your requirements, preceed to escape some characters like space to %20 etc.
  5. C:\!\aktuell.csv became file:///C:/!/aktuell.csv, you're done :-)
Another Search Replace Example
[Data]
EU AX ALA 248 �land Islands
EU AL ALB 008 Albania, People's Socialist Republic of
AF DZ DZA 012 Algeria, People's Democratic Republic of
OC AS ASM 016 American Samoa
EU AD AND 020 Andorra, Principality of
AF AO AGO 024 Angola, Republic of
NA AI AIA 660 Anguilla
AN AQ ATA 010 Antarctica (the territory South of 60 deg S)
NA AG ATG 028 Antigua and Barbuda
SA AR ARG 032 Argentina, Argentine Republic
AS AM ARM 051 Armenia
NA AW ABW 533 Aruba
OC AU AUS 036 Australia, Commonwealth of
[SearchPattern]
([A-Z]+) ([A-Z]+) ([A-Z]+) ([0-9]+) (.*)
[ReplacePattern]
\1,\2,\3,\4,\5
[FinalData]
AS,AF,AFG,004,Afghanistan
EU,AX,ALA,248,�land Islands
EU,AL,ALB,008,Albania, People's Socialist Republic of
AF,DZ,DZA,012,Algeria, People's Democratic Republic of
OC,AS,ASM,016,American Samoa
EU,AD,AND,020,Andorra, Principality of
AF,AO,AGO,024,Angola, Republic of
NA,AI,AIA,660,Anguilla
AN,AQ,ATA,010,Antarctica (the territory South of 60 deg S)
NA,AG,ATG,028,Antigua and Barbuda
SA,AR,ARG,032,Argentina, Argentine Republic
AS,AM,ARM,051,Armenia
NA,AW,ABW,533,Aruba
OC,AU,AUS,036,Australia, Commonwealth of

2011年12月7日 星期三

DB 與 Web 是同一台主機時,建議DB使用 192.168.X.X 段的 IP address

DB 與 Web 是同一台主機時,建議DB使用 192.168.X.X 段的 IP address,
因為, 萬一遇到問題, 要 trace log 時, 會比較方便, 才不會看到一大堆的 127.0.0.1

如果, 確定該台Web主機, 不會連到別台的 database,
記得用 ipsec 把連外的 1433 擋掉, 免得打掛別人的主機. @_@;

建議, 該Web主機直接把連外的 80, 443 port 直接全擋掉, 等有要做 windows update 時, 再開通, 其他建議順便一併擋掉的連外 port 有: 7, 20, 21, 23, 135, 137, 138, 139, 445.

認識 RestrictAnonymous (限制匿名檢查)

資料來源1: 安全性狀態評估檢查 - 限制匿名檢查
http://technet.microsoft.com/zh-tw/library/bb418944.aspx

資料來源2: 如何使用 Windows 2000 中的 RestrictAnonymous 登錄值
http://support.microsoft.com/kb/246261/zh-tw

登錄設定位於下列位置:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA\RestrictAnonymous

不用想太多, 直接把這個值, 設成1 即可.


RestrictAnonymous 可設為下列任一值:
0 - 無。視預設權限而定。
1 - 不允許「安全性帳戶管理員」帳戶和名稱的列舉。
2 - 無不含明確匿名權限的存取權。

2011年12月6日 星期二

[ASP].achg.asp 在 \Windows\system32\inetsrv\iisadmpwd

這個資料夾下的程式, 是 M$ 工程式貼心地幫我們寫的, 更新 Windows 登入的帳號/密碼 用的管理工具, 可是誰會用網頁來修改帳/密. @_@;

結論: 灌好 IIS 後, 記得要去刪掉, 應該有選項, 在安裝時不要安裝這類的奇怪貼心駭客小工具.

要監控主機的話, 可以試試看: Zabbix
雲端備份主機資料: Acronis Remote Agent, 資享科技旗下的資料保全銀行雲端備份軟體, Zmanda Cloud Backup, backupify.

2011年12月2日 星期五

ipseccmd 的範例

● 我的範例
 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄
需求,1433 port 和網芳只開放給 10.10.9.x 和 10.10.46.x

rem --------------------------------
rem Limit MS Sql Server
rem --------------------------------
ipseccmd -w REG -p "Block 1433 ports" -y
ipseccmd -w REG -p "Block 1433 ports" -o
ipseccmd -w REG -p "Block 1433 ports" -r "Block TCP/1433" -f *+0:1433:TCP -n BLOCK
ipseccmd -w REG -p "Block 1433 ports" -r "Limit TCP/1433" -f 10.10.9.0/255.255.255.0+0:1433:TCP -n PASS
ipseccmd -w REG -p "Block 1433 ports" -r "Limit TCP/1433" -f 10.10.46.0/255.255.255.0+0:1433:TCP -n PASS
ipseccmd -w REG -p "Block 1433 ports" -x


rem --------------------------------
rem Limit UDP port 137 (NETBIOS-NS):
rem Limit UDP port 138 (NETBIOS-DGM):
rem Limit TCP port 139 (NETBIOS-SSN)
rem Limit TCP port 445 (MICROSOFT-DS)
rem --------------------------------
ipseccmd -w REG -p "Block NETBIOS ports" -y
ipseccmd -w REG -p "Block NETBIOS ports" -o
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit UDP/137" -f 10.10.9.0/255.255.255.0+0:137:UDP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit UDP/137" -f 10.10.46.0/255.255.255.0+0:137:UDP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Block UDP/137" -f *+0:137:UDP -n BLOCK
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit UDP/138" -f 10.10.9.0/255.255.255.0+0:138:UDP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit UDP/138" -f 10.10.46.0/255.255.255.0+0:138:UDP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Block UDP/138" -f *+0:138:UDP -n BLOCK
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit TCP/139" -f 10.10.9.0/255.255.255.0+0:139:TCP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit TCP/139" -f 10.10.46.0/255.255.255.0+0:139:TCP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Block TCP/139" -f *+0:139:TCP -n BLOCK
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit TCP/445" -f 10.10.9.0/255.255.255.0+0:445:TCP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Limit TCP/445" -f 10.10.46.0/255.255.255.0+0:445:TCP -n PASS
ipseccmd -w REG -p "Block NETBIOS ports" -r "Block TCP/445" -f *+0:445:TCP -n BLOCK
ipseccmd -w REG -p "Block NETBIOS ports" -x



 ● GUI 介面設定
 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄
 step 1.從 [開始] 選單,先依序指向 [所有程式] 和 [ 系統管理工具],然後選取 [本機安全性設定值]。
 step 2.在 [本機安全性設定] 對話方塊中,按一下 [在本機電腦的 IP 安全性原則]。右邊的窗格會顯示預設的 Windows Server 2003 原則。
 step 3.在右邊的窗格上按一下滑鼠右鍵,然後按一下 [管理 IP 篩選器清單和篩選器動作]。
 step 4.於 [管理 IP 篩選器清單和篩選器動作] 對話方塊中,在 [管理 IP 篩選器清單] 索引標籤上,按一下 [新增]。
 step 5.在 [IP 篩選器清單] 對話方塊中的 [名稱] 方塊內,輸入您的篩選器清單名稱 (例如:輸入 HTTP)。若您想要的話,也可輸入相關的描述。此為套用到所有的輸入 HTTP 連線的篩選器清單。
 step 6.按一下 [新增]。出現 [IP 篩選器精靈]。建立篩選器清單...



 ● 相關文章:
 ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄
 ipsec 相關工具與指令研究
 http://maxtellyou.blogspot.com/2011/11/ipsec.html

 ipseccmd 範例
 http://forum.slime.com.tw/thread88684.html

2011年12月1日 星期四

SQL Server 的安全的建議

1.先用 ipsec 把所有的人(本機以外)的 1433 port 封包都擋掉, 針對有要 access 的, 再各別加入.
2.access 前台的 account, 請勿使用有dbowner 權限的帳號, 只要reader 即可, 再針前台的 ap 要 insert 的 table 開啟有要寫入的 table 權限.
3.sql server 上, 部分沒有在使用的系統 stored procedure 應停用或刪除...

利用gpedit 禁止目錄執行exe,bat,com

1. 執行: gpedit.msc



2. 新增, 軟體 的安全性原則:



3. 選取路徑, 並設為不允許.



4. 設好 "登出" 或重開機後, 到 Temp 下執行 notepad2.exe 就會顯示錯誤訊息.


建議: web root, 或程式上傳用的資料夾(public), 要記得設成不允許執行, 這樣子即可大大提高系統的安全性.





如何建立路徑規則:
--------------------------
1.按一下 [開始],再按一下 [執行],輸入 mmc,然後按一下 [確定]。
2.開啟 [軟體限制原則]。
3.在主控台樹狀目錄或詳細資料窗格中,用滑鼠右鍵按一下 [其他原則],然後按一下 [新增路徑規則]。
4.在 [路徑] 方塊中輸入路徑,或按一下 [瀏覽] 以尋找檔案或資料夾。
5.在 [安全性等級] 方塊中,按一下 [不允許] 或 [沒有限制]。


注意:
--------------------------
如果您尚未為這個 GPO 建立新的軟體限制原則設定,可能必須執行這項操作。
如果您為安全性等級設為 [不允許] 的程式建立路徑規則,則使用者仍然可以藉由將軟體複製到其他位置的方式執行軟體。
路徑規則支援的萬用字元為星號 (*) 和問號 (?)。
您可以在路徑規則中使用環境變數,例如 %programfiles% 或 %systemroot%。
當您不知道軟體在電腦中的儲存位置,但知道軟體的登錄機碼時,如果要為軟體建立路徑規則,您可以建立登錄路徑規則。
如果要防止使用者執行電子郵件附件,您可以為郵件程式的附件資料夾建立路徑規則,以防止使用者執行電子郵件附件。
只有列在 [指定的檔案類型] 中的檔案類型,才會受到路徑規則的影響。有一份所有規則共用的指定檔案類型清單。
如果要讓軟體限制原則生效,使用者必須先登出再登入電腦,以更新原則設定。
當有一個以上的規則套用至原則設定時,處理衝突時便有規則的優先順序。


資料來源: 如何在 Windows Server 2003 中使用軟體限制原則
http://support.microsoft.com/kb/324036/zh-tw

Facebook 留言板