Hello world!

Hello world

Django テンプレートで変数代入

Djangoのテンプレートで変数代入に躓いたので

変数代入の方法をまとめておく

 

Djangoのドキュメントによると変数代入を許容していないそうです。

Django の設計思想 — Django 1.4 documentation

 

・カスタムテンプレートタグで回避することができる

テンプレートタグやフィルタを自作する — Django 1.4 documentation

 

・/templatetags/common.pyを作成し

from django import template
register = template.Library()


class SetVarNode(template.Node):

    def __init__(self, var_name, var_value):
        self.var_name = var_name
        self.var_value = var_value

    def render(self, context):
        try:
            value = template.Variable(self.var_value).resolve(context)
        except template.VariableDoesNotExist:
            value = ""
        context[self.var_name] = value

        return u""


@register.tag(name='set')
def set_var(parser, token):
    """
    {% set some_var = '123' %}
    """
    parts = token.split_contents()
    if len(parts) < 4:
        raise template.TemplateSyntaxError("'set' tag must be of the form: {% set <var_name> = <var_value> %}")

    return SetVarNode(parts[1], parts[3])

 

・template内のhtmlで作成したcommon.pyをロードすると

 setタグが使用できるようになる

{% load common %}

{% if xx == aaa %}
    {% set color = '#ffffff' %}
{% else %}
    {% set color = '#c0c0c0' %}
{% endif %}

07_Anti-Debugging

  • Title

Anti-Debugging
Reverse it.
bin
http://files.quals.seccon.jp/bin

may some AV will alert,but no problem.

  • writeup
  • binファイルの確認
$ file bin 
bin: PE32 executable for MS Windows (console) Intel 80386 32-bit

f:id:taku_sid:20161212225308p:plain
左下のように分岐しているので怪しいところを調べる


f:id:taku_sid:20161212225406p:plain
メッセージボックスを出してる


f:id:taku_sid:20161212225433p:plain
直前の処理も見てみる

  • 一番最初のjump先アドレスをメッセージボックス出力直前の処理に飛ばしてみる

f:id:taku_sid:20161212225526p:plain

  • OllyDbgを使ってバイナリを書き換え

f:id:taku_sid:20161212225610p:plain

  • 実行してみる

f:id:taku_sid:20161212225710p:plain

01_Vigenere

  • Title

Vigenere
k: ????????????
p: SECCON{???????????????????????????????????}
c: LMIG}RPEDOEEWKJIQIWKJWMNDTSR}TFVUFWYOCBAJBQ

k=key, p=plain, c=cipher, md5(p)=f528a6ab914c1ecf856a1d93103948fe

|ABCDEFGHIJKLMNOPQRSTUVWXYZ{}

                                                          • -

A|ABCDEFGHIJKLMNOPQRSTUVWXYZ{}
B|BCDEFGHIJKLMNOPQRSTUVWXYZ{}A
C|CDEFGHIJKLMNOPQRSTUVWXYZ{}AB
D|DEFGHIJKLMNOPQRSTUVWXYZ{}ABC
E|EFGHIJKLMNOPQRSTUVWXYZ{}ABCD
F|FGHIJKLMNOPQRSTUVWXYZ{}ABCDE
G|GHIJKLMNOPQRSTUVWXYZ{}ABCDEF
H|HIJKLMNOPQRSTUVWXYZ{}ABCDEFG
I|IJKLMNOPQRSTUVWXYZ{}ABCDEFGH
J|JKLMNOPQRSTUVWXYZ{}ABCDEFGHI
K|KLMNOPQRSTUVWXYZ{}ABCDEFGHIJ
L|LMNOPQRSTUVWXYZ{}ABCDEFGHIJK
M|MNOPQRSTUVWXYZ{}ABCDEFGHIJKL
N|NOPQRSTUVWXYZ{}ABCDEFGHIJKLM
O|OPQRSTUVWXYZ{}ABCDEFGHIJKLMN
P|PQRSTUVWXYZ{}ABCDEFGHIJKLMNO
Q|QRSTUVWXYZ{}ABCDEFGHIJKLMNOP
R|RSTUVWXYZ{}ABCDEFGHIJKLMNOPQ
S|STUVWXYZ{}ABCDEFGHIJKLMNOPQR
T|TUVWXYZ{}ABCDEFGHIJKLMNOPQRS
U|UVWXYZ{}ABCDEFGHIJKLMNOPQRST
V|VWXYZ{}ABCDEFGHIJKLMNOPQRSTU
W|WXYZ{}ABCDEFGHIJKLMNOPQRSTUV
X|XYZ{}ABCDEFGHIJKLMNOPQRSTUVW
Y|YZ{}ABCDEFGHIJKLMNOPQRSTUVWX
Z|Z{}ABCDEFGHIJKLMNOPQRSTUVWXY
{|{}ABCDEFGHIJKLMNOPQRSTUVWXYZ
}|}ABCDEFGHIJKLMNOPQRSTUVWXYZ{
Vigenere cipher
Vigenère cipher - Wikipedia

  • writeup
  • pyhtonで計算してみる
k = '????????????'
p = 'SECCON{???????????????????????????????????}'
c = 'LMIG}RPEDOEEWKJIQIWKJWMNDTSR}TFVUFWYOCBAJBQ'

num={'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3, 'G': 6, 'F': 5, 'I': 8, 'H': 7, 'K': 10, 'J': 9, 'M': 12, 'L': 11, 'O': 14, 'N': 13, 'Q': 16, 'P': 15, 'S': 18, 'R': 17, 'U': 20, 'T': 19, 'W': 22, 'V': 21, 'Y': 24, 'X': 23, 'Z': 25, '{': 26, '}': 27}

def printk(p,c):
    ci = num[c]
    pi = num[p]

    for ki in range(28):
        if ci == (pi + ki) % 28:
            print num.keys()[num.values().index(ki)]

def printp(c,k):
    ki = num[k]
    ci = num[c]

    pi = (ci - ki) % 28
    print num.keys()[num.values().index(pi)]

#kの前半を求める
for i in range(7):
    printk(p[i],c[i]),

#k="VIGENER?????"
  • ん〜総当りか?あれ?

md5(p)=f528a6ab914c1ecf856a1d93103948fe

  • md5逆変換してみる

f:id:taku_sid:20161211213822p:plain

fin

03_Memory Analysis

  • Title

Memory Analysis
Find the website that the fake svchost is accessing.
You can get the flag if you access the website!!

memoryanalysis.zip

The challenge files are huge, please download it first.
Hint1: http://www.volatilityfoundation.org/
Hint2: Check the hosts file

password: fjliejflsjiejlsiejee33cnc

  • write up

参考サイト:
http://downloads.volatilityfoundation.org/releases/2.4/CheatSheet_v2.4.pdf


1.OS調査

$ vol.py -f forensic_100.raw imageinfo
Volatility Foundation Volatility Framework 2.5
INFO    : volatility.debug    : Determining profile based on KDBG search...
          Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)
                     AS Layer1 : IA32PagedMemoryPae (Kernel AS)
                     AS Layer2 : FileAddressSpace (/Users/Tk/Hack/SECCON2016/03_Memory Analysis/forensic_100.raw)
                      PAE type : PAE
                           DTB : 0x34c000L
                          KDBG : 0x80545ce0L
          Number of Processors : 1
     Image Type (Service Pack) : 3
                KPCR for CPU 0 : 0xffdff000L
             KUSER_SHARED_DATA : 0xffdf0000L
           Image date and time : 2016-12-06 05:28:47 UTC+0000
     Image local date and time : 2016-12-06 14:28:47 +0900


2.通信内容確認

$ vol.py -f forensic_100.raw --profile=WinXPSP2x86 connections
Volatility Foundation Volatility Framework 2.5
Offset(V)  Local Address             Remote Address            Pid
---------- ------------------------- ------------------------- ---
0x8213bbe8 192.168.88.131:1034       153.127.200.178:80        1080

3.hostsファイル取得

$ vol.py -f forensic_100.raw --profile=WinXPSP2x86 filescan | grep hosts
Volatility Foundation Volatility Framework 2.5
0x000000000217b748      1      0 R--rw- \Device\HarddiskVolume1\WINDOWS\system32\drivers\etc\hosts

$ vol.py -f forensic_100.raw --profile=WinXPSP2x86 dumpfiles -Q 0x000000000217b748 --name -D ./
Volatility Foundation Volatility Framework 2.5
DataSectionObject 0x0217b748   None   \Device\HarddiskVolume1\WINDOWS\system32\drivers\etc\hosts

4.hostsファイル確認

$ cat file.None.0x819a3008.hosts.dat
# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

127.0.0.1       localhost
153.127.200.178    crattack.tistory.com

5.接続サイト調査

$ vol.py -f forensic_100.raw --profile=WinXPSP2x86 iehistory -p 1080 --output=csv
Volatility Foundation Volatility Framework 2.5
URL ,2016-12-06 05:22:04 UTC+0000,2016-12-06 05:22:38 UTC+0000,Cookie:system@tiara.daum.net/
URL ,2016-12-06 05:21:55 UTC+0000,2016-12-06 05:22:04 UTC+0000,Cookie:system@daum.net/
URL ,2016-12-06 05:22:04 UTC+0000,2016-12-06 05:22:04 UTC+0000,Cookie:system@daum.net/
URL ,2016-12-01 05:53:52 UTC+0000,2016-12-06 05:22:04 UTC+0000,http://s1.daumcdn.net/cfs.tistory/blog/skin/tis_tickTalk/images/bg_counter.gif
URL ,2016-12-01 05:53:52 UTC+0000,2016-12-06 05:22:04 UTC+0000,http://s1.daumcdn.net/cfs.tistory/blog/skin/tis_tickTalk/images/txt_total.gif
URL ,2016-12-01 05:53:52 UTC+0000,2016-12-06 05:22:04 UTC+0000,http://s1.daumcdn.net/cfs.tistory/blog/skin/tis_tickTalk/images/txt_today.gif
URL ,2016-12-01 05:53:52 UTC+0000,2016-12-06 05:22:04 UTC+0000,http://s1.daumcdn.net/cfs.tistory/blog/skin/tis_tickTalk/images/txt_yesterday.gif
URL ,2016-12-01 05:53:52 UTC+0000,2016-12-06 05:22:04 UTC+0000,http://s1.daumcdn.net/cfs.tistory/blog/skin/tis_tickTalk/images/tistory.gif
URL ,2016-12-01 05:53:52 UTC+0000,2016-12-06 05:22:04 UTC+0000,http://s1.daumcdn.net/cfs.tistory/resource/d7d52300d7e0e43711a4493fa749b587f1ee6971/blog/script/copyTrackback.swf
URL ,2014-06-30 07:24:47 UTC+0000,2016-12-06 05:15:02 UTC+0000,http://i1.daumcdn.net/cfs.tistory/static/top/favicon_0630.ico
URL ,2016-12-06 03:39:11 UTC+0000,2016-12-06 05:28:40 UTC+0000,http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd
URL ,2016-12-06 05:22:04 UTC+0000,2016-12-06 05:22:04 UTC+0000,Visited: SYSTEM@http://crattack.tistory.com/rss
URL ,2016-12-06 05:28:40 UTC+0000,2016-12-06 05:28:40 UTC+0000,Visited: SYSTEM@http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd
URL ,2016-12-06 05:28:40 UTC+0000,2016-12-06 05:28:40 UTC+0000,Visited: SYSTEM@http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd
URL ,2016-12-06 14:28:40 UTC+0000,2016-12-06 05:28:40 UTC+0000,:2016120620161207: SYSTEM@http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd
URL ,2016-12-06 14:15:02 UTC+0000,2016-12-06 05:15:02 UTC+0000,:2016120620161207: SYSTEM@:Host: crattack.tistory.com
URL ,2016-12-06 14:28:05 UTC+0000,2016-12-06 05:28:05 UTC+0000,:2016120620161207: SYSTEM@http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd

6.サイトに接続してみる

$ curl http://153.127.200.178/entry/Data-Science-import-pandas-as-pd
SECCON{_h3110_w3_h4ve_fun_w4rg4m3_}

Volatility Analysis

Volatilityによるメモリフォレンジック

セキュリティコンテストで
初メモリフォレンジックの問題に挑戦したが
惨敗です。。。

メモリフォレンジックといえば
Volatility Framework を使うらしいので
調べた使い方をまとめとく

  • インストール方法(mac
$ brew install volatility
  • とりあえずヘルプを見てみる
$ vol.py -h
Volatility Foundation Volatility Framework 2.5
Usage: Volatility - A memory forensics analysis platform.

Options:
  -h, --help            list all available options and their default values.
                        Default values may be set in the configuration file
                        (/etc/volatilityrc)
  --conf-file=/Users/Tk/.volatilityrc
                        User based configuration file
  -d, --debug           Debug volatility
  --plugins=PLUGINS     Additional plugin directories to use (colon separated)
  --info                Print information about all registered objects
  --cache-directory=/Users/Tk/.cache/volatility
                        Directory where cache files are stored
  --cache               Use caching
  --tz=TZ               Sets the (Olson) timezone for displaying timestamps
                        using pytz (if installed) or tzset
  -f FILENAME, --filename=FILENAME
                        Filename to use when opening an image
  --profile=WinXPSP2x86
                        Name of the profile to load (use --info to see a list
                        of supported profiles)
  -l LOCATION, --location=LOCATION
                        A URN location from which to load an address space
  -w, --write           Enable write support
  --dtb=DTB             DTB Address
  --shift=SHIFT         Mac KASLR shift address
  --output=text         Output in this format (support is module specific, see
                        the Module Output Options below)
  --output-file=OUTPUT_FILE
                        Write output in this file
  -v, --verbose         Verbose information
  -g KDBG, --kdbg=KDBG  Specify a KDBG virtual address (Note: for 64-bit
                        Windows 8 and above this is the address of
                        KdCopyDataBlock)
  --force               Force utilization of suspect profile
  --cookie=COOKIE       Specify the address of nt!ObHeaderCookie (valid for
                        Windows 10 only)
  -k KPCR, --kpcr=KPCR  Specify a specific KPCR address

	Supported Plugin Commands:

		amcache        	Print AmCache information
		apihooks       	Detect API hooks in process and kernel memory
		atoms          	Print session and window station atom tables
		atomscan       	Pool scanner for atom tables
		auditpol       	Prints out the Audit Policies from HKLM\SECURITY\Policy\PolAdtEv
		bigpools       	Dump the big page pools using BigPagePoolScanner
		bioskbd        	Reads the keyboard buffer from Real Mode memory
		cachedump      	Dumps cached domain hashes from memory
		callbacks      	Print system-wide notification routines
		clipboard      	Extract the contents of the windows clipboard
		cmdline        	Display process command-line arguments
		cmdscan        	Extract command history by scanning for _COMMAND_HISTORY
		connections    	Print list of open connections [Windows XP and 2003 Only]
		connscan       	Pool scanner for tcp connections
		consoles       	Extract command history by scanning for _CONSOLE_INFORMATION
		crashinfo      	Dump crash-dump information
		deskscan       	Poolscaner for tagDESKTOP (desktops)
		devicetree     	Show device tree
		dlldump        	Dump DLLs from a process address space
		dlllist        	Print list of loaded dlls for each process
		driverirp      	Driver IRP hook detection
		drivermodule   	Associate driver objects to kernel modules
		driverscan     	Pool scanner for driver objects
		dumpcerts      	Dump RSA private and public SSL keys
		dumpfiles      	Extract memory mapped and cached files
		dumpregistry   	Dumps registry files out to disk 
		editbox        	Dumps various data from ComCtl Edit controls (experimental: ListBox, ComboBox)
		envars         	Display process environment variables
		eventhooks     	Print details on windows event hooks
		evtlogs        	Extract Windows Event Logs (XP/2003 only)
		filescan       	Pool scanner for file objects
		gahti          	Dump the USER handle type information
		gditimers      	Print installed GDI timers and callbacks
		gdt            	Display Global Descriptor Table
		getservicesids 	Get the names of services in the Registry and return Calculated SID
		getsids        	Print the SIDs owning each process
		handles        	Print list of open handles for each process
		hashdump       	Dumps passwords hashes (LM/NTLM) from memory
		hibinfo        	Dump hibernation file information
		hivedump       	Prints out a hive
		hivelist       	Print list of registry hives.
		hivescan       	Pool scanner for registry hives
		hpakextract    	Extract physical memory from an HPAK file
		hpakinfo       	Info on an HPAK file
		idt            	Display Interrupt Descriptor Table
		iehistory      	Reconstruct Internet Explorer cache / history
		imagecopy      	Copies a physical address space out as a raw DD image
		imageinfo      	Identify information for the image 
		impscan        	Scan for calls to imported functions
		joblinks       	Print process job link information
		kdbgscan       	Search for and dump potential KDBG values
		kpcrscan       	Search for and dump potential KPCR values
		ldrmodules     	Detect unlinked DLLs
		lsadump        	Dump (decrypted) LSA secrets from the registry
		machoinfo      	Dump Mach-O file format information
		malfind        	Find hidden and injected code
		mbrparser      	Scans for and parses potential Master Boot Records (MBRs) 
		memdump        	Dump the addressable memory for a process
		memmap         	Print the memory map
		messagehooks   	List desktop and thread window message hooks
		mftparser      	Scans for and parses potential MFT entries 
		moddump        	Dump a kernel driver to an executable file sample
		modscan        	Pool scanner for kernel modules
		modules        	Print list of loaded modules
		multiscan      	Scan for various objects at once
		mutantscan     	Pool scanner for mutex objects
		notepad        	List currently displayed notepad text
		objtypescan    	Scan for Windows object type objects
		patcher        	Patches memory based on page scans
		poolpeek       	Configurable pool scanner plugin
		printkey       	Print a registry key, and its subkeys and values
		privs          	Display process privileges
		procdump       	Dump a process to an executable file sample
		pslist         	Print all running processes by following the EPROCESS lists 
		psscan         	Pool scanner for process objects
		pstree         	Print process list as a tree
		psxview        	Find hidden processes with various process listings
		qemuinfo       	Dump Qemu information
		raw2dmp        	Converts a physical memory sample to a windbg crash dump
		screenshot     	Save a pseudo-screenshot based on GDI windows
		servicediff    	List Windows services (ala Plugx)
		sessions       	List details on _MM_SESSION_SPACE (user logon sessions)
		shellbags      	Prints ShellBags info
		shimcache      	Parses the Application Compatibility Shim Cache registry key
		shutdowntime   	Print ShutdownTime of machine from registry
		sockets        	Print list of open sockets
		sockscan       	Pool scanner for tcp socket objects
		ssdt           	Display SSDT entries
		strings        	Match physical offsets to virtual addresses (may take a while, VERY verbose)
		svcscan        	Scan for Windows services
		symlinkscan    	Pool scanner for symlink objects
		thrdscan       	Pool scanner for thread objects
		threads        	Investigate _ETHREAD and _KTHREADs
		timeliner      	Creates a timeline from various artifacts in memory 
		timers         	Print kernel timers and associated module DPCs
		truecryptmaster	Recover TrueCrypt 7.1a Master Keys
		truecryptpassphrase	TrueCrypt Cached Passphrase Finder
		truecryptsummary	TrueCrypt Summary
		unloadedmodules	Print list of unloaded modules
		userassist     	Print userassist registry keys and information
		userhandles    	Dump the USER handle tables
		vaddump        	Dumps out the vad sections to a file
		vadinfo        	Dump the VAD info
		vadtree        	Walk the VAD tree and display in tree format
		vadwalk        	Walk the VAD tree
		vboxinfo       	Dump virtualbox information
		verinfo        	Prints out the version information from PE images
		vmwareinfo     	Dump VMware VMSS/VMSN information
		volshell       	Shell in the memory image
		windows        	Print Desktop Windows (verbose details)
		wintree        	Print Z-Order Desktop Windows Tree
		wndscan        	Pool scanner for window stations
		yarascan       	Scan process or kernel memory with Yara signatures

コマンド数多すぎ、、、


  • よく使うコマンド
  • imageinfo(OS判定)
$  vol.py -f [memfile] imageinfo
  • pstree(プロセス一覧)
$  vol.py -f [memfile Profile] --profile=[OS] pstree
  • imageinfo(OS判定)
$  vol.py -f [memfile] imageinfo
  • connections(メモリダンプ時の通信)
$  vol.py -f [memfile Profile] --profile=[OS] connections
  • connscan(クローズしたソケット)
$  vol.py -f [memfile Profile] --profile=[OS] connscan
  • filescan(ファイル一覧)
$  vol.py -f [memfile Profile] --profile=[OS] filescan
  • dumpfiles(ファイルダンプ)
$  vol.py -f [memfile Profile] --profile=[OS] dumpfiles -Q [file addr] --name -D ./