Search results

'카카오톡'에 해당하는 글들

  1. 2011/07/13  [KakaoTalk] JSON Objects (5) (6)
  2. 2011/06/26  [KakaoTalk] KakaoTalk PC Prototype (4) (10)
  3. 2011/06/23  [KakaoTalk] Session Key (3) (12)
  4. 2011/06/22  [KakaoTalk] Bypassing SSL (2) (1)
  5. 2011/06/19  [KakaoTalk] Preliminary Research / Analysis (1) (3)

에.. 이번 글에서는 카카오톡 클라이언트와 서버 사이에서 어떤 데이터가 오고가는지 짧게 적어보려 합니다.
다른 플랫폼으로 (windows phone, pc, 등등) 포팅하실분들에게 약간이나마 도움이 될지도 모르겠네요.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

일단 제 프로그램에서는 세션키 인증이 끝나면 바로 친구 리스트를 불러옵니다.
친구리스트는 다음 URL에 리퀘스트를 보내면 받을 수 있습니다:
https://ch-talk.kakao.com/iphone/chats/list.json

그러면, 다음과 같은 object에 파싱해서 넣을 수 있습니다.

view [FriendsListJSON.cs]



앞으로의 모든 JSON 객체에서 status 필드를 보실 수 있는데, 0일 경우엔 성공 음수일 경우엔 각 에러코드를 나타냅니다. 예를들어, -500 은 세션키가 http 헤더에 제공되지 않았을때 리턴되고 -998은 잘못된 (서버에 등록되어있지 않은) 세션키가 제공되었을때 리턴됩니다.


각각의 Friend 객체는 다음과 같은 구조를 가지고 있습니다.
필드설명:
- type: 현재 친구와의 관계 (1 == 이미 친구, -4 == 친구 아님)
- directChatId: 직접 채팅(방) 아이디
- userId: 유져 고유번호
- nickName: 친구 이름 (상대방이 자신의 닉네임으로 설정한 것)
- phoneNumber: 폰 번호 (폰 번호가 저장되어있다면.. 아이디로만 저장되있으면 폰 번호 없음)
- profileImageUrl: 작은 프로필 사진 주소
- statusMessage: 이름 옆에 뜨는 '오늘의 메세지'
- friendNickName: 자신이 설정한 친구의 닉네임
- UUID: 아이디 (친구 검색할때 쓰는 아이디)
- fullProfileImageUrl: 원본 프로필 사진 주소

view [Friend.cs]




이제 친구 찾기에 대해서 알아봅시다~
친구찾기는 다음 url로 리퀘스트를 보내면 됩니다:
https://fr-talk.kakao.com/iphone/friends/find_by_uuid.json?uuid=UUID
찾고 싶은 친구의 아이디 (uuid)를 파라미터로 넘기면 다음과 같은 JSON이 리턴됩니다.

필드설명:
- status: 찾기 성공 여부 (0 == 찾음, -1002 == 존재하지 않는 아이디거나 공개찾기 거부)
- member: 상대방 정보 (사실 지금보니까 그냥 Friend 클래스를 썼어도 될것 같네요, 한가지 차이점은 friendNickName 필드가 없다는것 정도..)

view [FindFriendByUUIDJSON.cs]



친구 추가를 할 때는, 다음 url에 리퀘스트를 하면 됩니다:
https://fr-talk.kakao.com/iphone/friends/add.json?id=userId
여기서 주의해야 할 점은, 위에서 말씀드린 유져 고유번호인 userId를 넣어줘야한다는점입니다. UUID (사용자 아이디)가 아닙니다.

성공적으로 리스폰스가 돌아온다면 다음과 같은 JSON이 리턴됩니다.
필드설명 (FriendJSON class):
- status: 친구 추가 성공여부 (0 or 1 == 성공 | 처음으로 추가하는거면 0, 한번 해본적 있으면 1 인듯?)
- friend: 친구 정보

친구 삭제 시에는, 다음 url에 리퀘스트를 하면 됩니다:
https://fr-talk.kakao.com/iphone/friends/remove.json
하지만, 이번 리퀘스트는 그냥 GET으로는 파라미터를 넘길 수 없고, POST를 써야합니다 (한번에 여러 아이디 삭제가 가능하므로). POST 데이터는 다음과 같습니다:
ids=[userId1,userId2,...,userIdn]
이번 역시 userId를 넣어주어야합니다.

성공적으로 리스폰스가 돌아온다면 다음과 같은 JSON이 리턴됩니다.
필드설명 (FriendIdsJSON class):
- status: 친구 삭제 성공여부 (0 == 성공)
- friendIds: 삭제된 친구 userId 리스트 (클라이언트 리스트에서 삭제할 수 있도록)

view [FriendJSON.cs]



대충 이 정도하면 친구 불러오기, 찾기, 추가, 그리고 삭제와 같은 친구관련 작업들은 다 할 수 있습니다.

이제 마지막으로 채팅에 관련된 극히 일부분을 보도록 하죠 ㅎㅎ
최근에 시간이 없어서 (제일 중요한 ^^;) 채팅쪽을 많이 못봤습니다.. 베타버전에서 이미지 전송까지 해놓으려고했는데 다음..(기약없음..ㅋㅋ)으로 미뤄야하겠네요.

일단 다음은 채팅방 리스트를 불러오는 url 입니다:
https://ch-talk.kakao.com/iphone/chats/list.json

저는 개인적으로 세션키 validation을 할때밖에 쓰지 않습니다만.. 유용한 날이 오겠죠 ㅎㅎ

view [ChatListJSON.cs]




실질적으로 채팅이 이루어지는 부분을 보도록 하죠.
사실 카카오톡에서는 '채팅'의 개념보다는 '비동기식 메세지 교환' 이라고 보는게 나을지도 모르겠네요.
한쪽에서 메세지를 보내면, 이 메세지는 카카오톡 서버에 저장되어있다가 다른쪽 유져가 '나 메세지 받은거 있니?' 라고 물어보면 서버가 받아두었던 메세지를 전달해주는 방식입니다. 물론, 그 시점에서 서버단에서 그 메세지가 삭제가 되는지 저장이 되는지는 (^^;) 저로써는 알 방법이 없지만, 카카오톡 구조상 무조건 서버에 한번은 저장되어야 합니다.

그리고 또 한가지 재밌는것은, 카카오톡은 이미 처음부터 그룹채팅을 디자인으로 개발되었던것 같습니다.
그래서, 모든것이 다수가 참여할 수 있는 '채팅방'의 구조로 되어있고 1:1대화는 그저 유져가 두 명인 채팅방에 불과합니다.

다음 url로 채팅방을 생성 또는 메세지를 적을 수 있습니다:
https://ch-talk.kakao.com/iphone/chats/create_and_write.json

사실, 보통은 create_and_write은 대화를 맨 처음 할때 한번만 전송되고 그 이후부터는 그 채팅방에 부여된 채팅방 아이디를 사용해서 메세지를 보내고 받고 하지만, 저는 따로 내부 DB를 관리하고 있지 않기때문에 그냥 그때그때 create_and_write에 리퀘스트를 합니다. 그렇다고 그때마다 채팅방이 새롭게 생기는것은 아닙니다 ㅎㅎ 고맙게도(?) 이미 존재하는 채팅이면 서버단에서 처리를 해주는것 같더군요.

위의 리퀘스트는 당연히 POST이여야하고, POST 데이터는 다음과 같습니다:
receiver_ids[]=id1,id2,...,idn   (사실 저는 지금 1:1 만 지원중이라 여러아이디에 보내는데에 쓰이는 구분자가 잘 기억이 안나네요 -_-; 콤마였던거 같은데 아닐수도있으니 그룹대화 지원하실분은 체크 먼저 하시길..)
message=msg (한글은 UTF-8 인코딩해야함)
push_alert= true (또는 false)

필드설명 (ChatRoomJSON):
- status: 성공 여부 (0 == 성공적으로 전송, -401 == 실패했음)
- chatRoom: 채팅방 정보
- chatLogs: 채팅방 로그 (아직 확인 하지 않은 메세지들)

필드설명 (ChatRoom):
- type: 그룹인지 1:1인지 판별?
- activeMemberIds: 대화 참여중인 멤버 아이디들
- lastMessage: 마지막 메세지
- pushAlert: push notification 설정 되있는지 여부
- activeMembersCount: 참여중인 멤버 수
- members: 참여중인 멤버들 정보
- watermarks: ???
- lastUpdatedAt: 마지막으로 업데이트 된 시간 (내부 카운터)
- lastLogId: 마지막으로 확인한 로그 고유번호
- newMessageCount: 새 메세지 갯수
- chatId: 현재 채팅방의 고유번호

필드설명 (ChatLog):
- type: 까먹음 (그룹 또는 1:1?)
- logId: 로그 고유번호
- message: 메세지
- sendAt: 보내진 시간 (내부 카운터)
- chatId: 로그가 속한 채팅방 고유번호

view [ChatRoomJSON.cs]



해보지는 않았지만, 요즘 화두가 되고있는 '카카오톡 서버가 메세지를 저장을 하고 있느냐 아니냐'의 질문은 아무래도 이미 (채팅방 안의 모든 멤버가) 확인한 메세지의 ChatLog를 다시 불러올 수 있느냐 없느냐로 판별 할 수도있겠네요. 정상적이라면 채팅방에 있는 멤버가 특정 메세지를 모두 확인하는 순간 (즉, 메세지 옆에 뜨는 노란 숫자가 0이 되는 순간) 서버단에서 해당 로그를 지워야하겠죠. 그런데도 그 로그 아이디로 메세지를 불러올 수 있다면, 서버에 메세지들을 계속 저장하고 있다는 뜻이겠죠.

이제 마지막으로, https://ch-talk.kakao.com/iphone/chats/chatId.json?since=lastLogId 로 리퀘스트를 보내게 되면, 역시 ChatRoomJSON이 넘어오게 됩니다. 보시다시피 chatId와 lastLogId로 새로운 메세지가 도착했는지 안했는지 fetch할 수 있습니다. 방금전에 위에서 말한 테스팅을 손쉽게 할 수 있는 리퀘스트죠 :)

제가 해보진 않았습니다만.. (별로 그쪽엔 관심이 없는지라..) 다른분들이 해보시고 알게되면 댓글 달아주세요 ^^


대충 이정도가 제가 알고있는 자료구조입니다. 사실 자료구조라고 하기에도 좀 난감한 'JSON parsing' 입니다.
리퀘스트해서 돌아오는 리스폰스를 파싱해서 그 데이터를 알맞게 잘 쓰면 카카오톡 포팅이 가능한거죠.

나중에 시간과 기회가 된다면, 그룹대화 (뭐 이번 포스팅에서도 대충 설명하긴했습니다만..)와 이미지/동영상 등 전송에 대해서 설명하도록 하겠습니다.

질문이 있으시면 댓글로 남겨주시거나 이메일 주시면 됩니다~~




2011/07/13 23:34 2011/07/13 23:34
─ tag  , , ,

카카오톡 관련 포스팅을 영어로 하는데에 대한 불만들이 많으셔서 ㅋㅋ..
이번 포스팅은 한국어로 하도록 하겠습니다~ :D

사실 이번엔 카카오톡 분석에 대한것보다는 간단한 분석 (2~3시간)으로 만들 수 있는 프로토타입에 대해서 소개하고자 합니다. 제가 1편에서도 말씀드린것처럼, 카톡 개발자들이 상당히 구조를 잘 짜놨기 때문에, 프로토콜과 자료구조만 알면 사실 에뮬레이션 (예를들어, PC버전 카카오톡)을 하기가 정말 쉽게 되어있습니다.


일단 기기가 카카오톡 서버에 등록이 되고 나면 세션키라는 인증토큰이 모든 패킷에 들어가야합니다. 하지만 전편에서 말씀드린대로, (jailbreak 없이) 정상적인 방법으로는 세션키를 추출하기가 불가능에 가깝습니다. 그렇기 때문에, 현존하는 모바일기기의 계정을 그대로 PC에서도 사용하시려면 이 세션키를 먼저 추출하셔야합니다. 또 다른 방법으로는, 새로운 계정을 인증하는 방법이 있긴합니다만.. 모바일기기의 계정과 연결하기는 거의 불가능합니다 -- PC버전용으로만 쓸 수 있는것이죠. 즉, 제가 앞으로 설명드릴 카카오톡PC는 세션키를 안다는 가정하에 진행하도록 하겠습니다.

세션키 추출 방법은 나중에 기회가 되면 다시 한번 포스팅을 하겠습니다만, jailbreak를 하신 폰이라면 SSL Bypass 편을 참고하시면 추출하실 수 있습니다. 유의하실 점은, 카카오톡의 유일한 인증 방식이 이 세션키이기 때문에 한번 유출되면 다른사람이 그 세션키 주인인척하고 모든 대화 및 프로필등을 도청 할 수 있다는것입니다.


=-=-=-=-=-=-=-=-=-=-=

그럼, 제가 날림으로 만든 카카오톡PC 프로토타입에 대해서 간략한 소개를 해드리겠습니다.
원래는 그냥 PoC (Proof of Concept: 된다는것을 증명하기 위해 최소 기능만 지원)용으로 만들기 시작한거라, 코드도 조잡하고 기능도 간단한것밖에 없었는데, 아무래도 요청하시는분이 많아서 릴리즈하기전에 조금 가다듬기 위해서 시간이 필요할것 같아, 아직은 릴리즈하지 않도록 하겠습니다.
[제 개인적으로 디자인적 감각이라던가, 윈도우 UI 개발을 해본적이 없기때문에.. 정말 기능적인요소만 추가되어있습니다....너무 실망마시길..ㅋㅋ]

처음 실행을 시키면 다음과 같은 창이 뜹니다:
사용자 삽입 이미지

세션키를 넣고 Verify 버튼을 누르면 카카오톡 서버에 등록되어있는 정상 세션키인지 검사를 합니다.
그리고 존재하는 세션키라면 다음의 메인화면으로 넘어가게 됩니다.

사용자 삽입 이미지

물론, 탭들을 이용해서 실제 카톡과 비슷하게 만들 수도 있었지만.. 그냥 한눈에 보는게 테스팅하기도 편하고 해서 일단 현재 디자인은 저렇습니다..

  • Friend Info: 이곳에는 오른쪽 자신의 친구리스트에서 선택된 친구의 정보가 보여지는곳입니다.
    사용자 삽입 이미지

      + Start Chat을 누르면 상대방과 채팅을 할 수 있도록 채팅창이 뜨고,
      + Delete을 누르면 친구를 삭제할 수 있습니다.

  • Menu: 아래쪽에 있는 메뉴에는 현재 지원하는 메뉴들이 있습니다.

      + Find Friend: 친구찾기 기능입니다. 디자인은 거의 카톡 기본 디자인과 흡사하게 만들어놨습니다.
    사용자 삽입 이미지

          - 찾을 ID를 넣고 Find를 누르면 그 아이디가 존재하고 찾기가 가능하게 되있다면,
            아래쪽 Friend Info에 사진, 닉네임, 아이디, status message등이 뜨게 됩니다.
          - Add를 누르면 현재 검색된 친구를 추가할 수 있습니다.

    사용자 삽입 이미지

            - 또한, 어디서든 프로필 사진이 있는곳 위에 클릭을 하면 원본사이즈의 프로필 사진을 보여줍니다.
               (새 창의 사진 아무데나 클릭하며 사라집니다.)

    사용자 삽입 이미지


      + My Profile 메뉴는 자신의 프로필을 볼 수 있고, 수정할 수 있습니다.
          (아직 사진수정 기능은 추가하지 않았습니다.)

    사용자 삽입 이미지

            - ID subject to Search 옵션은 서버에 저장만 해두고 현재 상태를 알려주지 않기때문에
              현재 어떤 상태인지 가져올 수 없습니다.. 수정하시고 싶다면 체크박스를 클릭하신 후
              업데이트 해주시면 됩니다.


  • Chatting: 아무래도 가장 중요한 기능 중 하나인 채팅은 현재 1:1 채팅만을 지원하고, 아이폰이나 안드로이드에서 지원해주는 Push notification 기능을 사용할 수 없기때문에, 매 3초마다 새로운 메세지가 있는지 체크해서 가져오도록 되어있습니다. 나중에 릴리즈할 버전에서는 이 interval을 조정하거나 수동으로 fetch해오도록 변경할 예정입니다. (너무 자주 fetch요청이 들어오면 카카오톡측에서 수상히 여기고 정지시킬 수 있기때문에..)

    사용자 삽입 이미지

    메세지 보내기


    사용자 삽입 이미지

    상대방에게 메세지가 잘 전달된 모습


    사용자 삽입 이미지

    상대방이 보낸 메세지가 잘 받아진 모습


    사용자 삽입 이미지

    KakaoTalk PC에서 한글로 보냈을때 잘 도착하는 모습


    사용자 삽입 이미지

    KakaoTalk PC 클라이언트에서 한글메세지를 잘 받는 모습


    사용자 삽입 이미지

    카카오톡 모바일에서도 푸쉬 알람이 뜨는 모습



대략 간단한 예제들을 보여드렸지만, 대부분 많이들 쓰시는 친구찾기/프로필수정/1:1대화 기능을 지원합니다.
바로 위의 스크린샷에서도 보실 수 있듯이 메세지를 받게 되면 KakaoTalkPC뿐만이 아니고 폰에서도 메세지를 확인할 수 있습니다.

이제는 이미지 파일 메세지 전송을 구현할 계획입니다만, 귀차니즘때문에 시작을 못하고 있네요..

아참. 제 프로그램에서도 모바일 카카오톡과 마찬가지로 모든 리퀘스트는 SSL을 통해서 하게됩니다.
그래서, 카카오톡pc를 사용하는 동안 누군가가 중간에서 packet sniffing을 해서 세션키를 훔치거나 메세지 변조등을 할 수 없습니다 :)


일단 요정도로 설명을 마치겠습니다. 필요한 기능인데 제가 잊은기능들이나 (전 카카오톡 헤비유져가 아니라..) 또는 이런게 있었으면 더 편하겠다 등.. 아이디어 있으시면 댓글로 남겨주시면 되겠습니다 -- 물론 100% 다 구현은 못할 수도있지만..저도 학교일을 해야하므로..ㅋㅋ 최대한 첫 릴리즈에서 그 기능들을 추가하도록 하겠습니다.

그리고 마지막으로, 카카오톡PC 베타유져를 모집합니다..
(윈도우 UI 이쁘게 만드는 기술 전수해주실분도 환영입니다!)
관심있으신분들은 brianairb [at] gmail [dot] com 으로 이메일주시면 되겠습니다.


좋은 하루 되시길...





2011/06/26 14:07 2011/06/26 14:07

Today, I'm going to explain one of the most critical parts in KakaoTalk: Session Key.

KakaoTalk has only one mechanism to authenticate the user. It is the session key that is generated in the process of registering yourself to the KakaoTalk server when you first install on your mobile device. This, then, is stored in the device until the user deletes KakaoTalk.

What's interesting here is that this session key acts as user identification AND user authentication on server side. Thus, this session does not act the same as the usual 'web' session keys, which expires after some time. KakaoTalk Session Key never expire or change -- well, I shouldn't say 'never' because there's a case that the key is purged. It is used throughout until the user deletes his/her account or KakaoTalk app from the phone. (BTW, deleting an app doesn't cause the account to be deleted.)


As you saw last time, the Session Key is required for every request that is sent to the server, and included in HTTP header with the field name of 'S'.

사용자 삽입 이미지



So, how is this key generated, and what does the life cycle of the key look like?

    1. Session Key Generation
    • Session Key is consisted of two parts: X-Y
    • First part (X) is generated during the SMS verification in registration step.
      • I tested on Android KakaoTalk, and the following is the steps in detail what's happening in the process of the verification.

      1. Client requests a SMS verification to KakaoTalk server (ac-talk.kakao.com)
          - This is done through /android/account/request_sms.json
          - POST data: device_uuid, phone_number, country_iso

      2. Server responds with the one-time 'token' in json format
          - Meanwhile, the server also sends actual SMS message (which contains passcode) to the number.

      3. Once the user puts in the passcode, the client submits to the server.
          - /android/account/verify_sms.json
          - POST data: token (to verify it's you), phone_number, country_iso, passcode, device_uuid, old_session_key
          - Here, old_session_key is set when you have changed your phone but still has old_session_key backed up in the system.

      4. Server responds with status code '11' and a new token is returned when successful.

      5. Finally, the client requests [/android/account/verify.json] along with the nickname that the user specified.
          - POST data: phone_number, country_iso, device_uuid, new token, nickname, old_session_key

      6. The server generates and sends 'sessionKey' in JSON data with other information as well.
          - JSON data includes: sessionKey, 'member' object (type is set to -10, which means it's myself), userid (unique number that differentiates users), nickname, etc.

      7. At this point, the session key has been given to the client, and the client saves it locally.
          - The subsequent requests must contain this session key, otherwise the request is rejected with error code -500 (session key not specified).

      8. Client then sends a query to [/android/account/update_settings.json] to sync the information on the server and the client.
          - POST data: model, simOperator, screen_resolution, os_name, os_version, etc.
          - I wonder why they need all this much information.

      • I haven't tested on iPhone, but it's just basically the same with different URL for iPhone.

    • Second part (Y) is generated based on the device id.
      • On Android:
        • This is just plain device ID, it seems. But I haven't done much reversing on this part, so I may be slightly wrong :p

      • On iPhone:
        • It uses something called 'encryptedDeiceID' which it derives from the property named 'cryptedUniqueIdentifider' (notice their typo :p)

          사용자 삽입 이미지

        • Again, as the name indicates, it does something with the device ID, but I haven't reversed this part yet.

    • The reason I didn't go deep enough to actually understand how they generate the device ID is because while it's still possible to reverse engineer and reconstruct the encrypted device ID, there's no way to reconstruct the first part of the session key since it comes directly from the server.
      • Thus, unfortunately, there doesn't seem to be a good way to regenerate the session key. Once it's generated and given to the client, both client and server just save it locally and use that to authenticate.


    2. Session Key Life Cycle
    • As I mentioned above, the usage of the session key is blatantly obvious. They use it to authenticate. Once it's set, it never changes -- unless the device is changed.

    • The session key must be included to the request header.

    • If the device ID changes (due to changing the device, etc.), KakaoTalk asks the user to re-verify the mobile device. In this process, old_session_key is set to the previous session key and the newly generated session key is returned.

      • Session Revocation
        • I was little surprised and impressed that KakaoTalk does this correctly ;)
        • When the user  verifies with the existing (same) number, KakaoTalk server revokes (deletes) old association with the account and the session key.
        • Thus, it is not possible to impersonate a user with his/her old session key.

    • Local storage of the key:
      • Android: /data/data/com.kakao.com/shared_prefs/KakaoTalk.perferences.xml
      • iPhone: /User/Applications/XXXXX...XXXX/Library/Preferences/com.iwilab.KakaoTalk.plist

        사용자 삽입 이미지

I mean, their one-factor, fixed token authentication mechanism scares me a little, but I had an impression that they actually somewhat care about security. However, they would need to come up with the better solution to this, since it's basically game-over situation if someone is able to extract the session key. (You can basically become anyone, and KakaoTalk wouldn't know shit.)

Anyways, that's what I have and know about KakaoTalk's session key system.
I don't know how they generate the first part, so I wouldn't go ahead and reverse the algorithm for the second part. If someone knows more about this, feel free to contact me! Maybe we can collaborate to do cool things :p

Thanks for reading!



2011/06/23 21:42 2011/06/23 21:42

Welcome back, readers!

As I told you last time, I'm going to talk about how KakaoTalk uses SSL to protect its outgoing/incoming packets from the packet sniffing. Again, this involves a jailbroken phone. The article will only use KakaoTalk for iPhone for the analysis, but the analogous techniques work in Android one as well.

 
It was somewhat surprising (and not really at the same time) to figure out that KakaoTalk client uses SSL sometimes and non-SSL the other times. Since SSL adds some overheads to the packets, it would not be ideal to have turned on every time because:
  1. It's going to drain the battery way faster. Crypto is not cheap, especially in embedded devices like mobile phones.
  2. Overhead++ ==> Traffic++ ==> $$$++ for non-unlimited data plan users.
To avoid this problem as much as possible, they choose to use SSL only when WiFi is on and connected to the internet through it.

사용자 삽입 이미지

It is interesting choice to think about since they might have decided to do this because of the security related reason as well. Note that it is trivial to sniff/dump the traffic of the mobile device when it is on WiFi. You can easily either set up a router to become a packet sniffer or make the phone to connect to the WiFi network through the computers (e.g. Internet Sharing feature on Mac OS X).

It didn't take much work to find where they decide whether to use SSL or not.

사용자 삽입 이미지

Call to currentReachabilityStatus


Above, you can see the code is making a call to currentReachabilityStatus function (commented) to determine which network the phone is currently using. Little lookup of Reachability library sample code tells us what it does and returns.

Remember that the return value in ARM architecture is stored at R0 register. Right after the call (_objc_msgSend), you can verify that the code is comparing the return value ofcurrentReachabilityStatus function with the constant value 2.

Here, I want to go over little bit of ARM instruction: IT
From the instruction reference for ARM, we can find the following description for this instruction.

The IT (If-Then) instruction makes up to four following instructions (the IT block) conditional. The conditions can be all the same, or some of them can be the logical inverse of the others.

Damn, If-Then instruction?! that's pretty cool :p

Anyhow, after parsing the meaning, we know that the code will move the constant value 1 into R6 register only when R0 register (return value) isn't 2. Then, based on R6's value, R10 that contains the pointer to the CFString object containing "http" is overwritten with R0 that has CFString object pointer of "https". OK, fine. Where are these used?

We can answer our question little bit down the code:
사용자 삽입 이미지

Note that the value of R10 is moved to R3. Also, remember that R3 is the first argument to the format string that's loaded in R2 before the call to make the formatted string with the arguments (pushed onto the stack). This is to build URL to query to get the JSON response.

Now, we know what controls the first argument of this string (the protocol -- https or http), we can test it ourselves! I used my jailbroken iPhone to capture the packet data. Of course, with our theory, the phone needs to be in 3G network rather than WiFi. So, how do we capture the packets?

The answer is simple. we just run tcpdump on 3G interface!

사용자 삽입 이미지

SSH into my iPhone

 
We start listening on pdp_ip0 device:
사용자 삽입 이미지사용자 삽입 이미지

 Once we do some activities in KakaoTalk, we can see the packets are dumped to the file.
사용자 삽입 이미지

Searching friend by uuid==kakao

사용자 삽입 이미지

Then, we can simply scp the dumped file to the local computer and start analyzing!
사용자 삽입 이미지


As you can see down in the screenshots, all of the packets are non-SSL packets and easily analyzable by Wireshark. At this point, we can try multiple things in KakaoTalk to monitor what they are actually sending and receiving. One of the things the clients send to the server as a part of the HTTP header is the session key. I will do a detailed write-up on the session keys, but I just want to note that the session key is the most crucial part (and the only part) of KakaoTalk's authentication.

사용자 삽입 이미지

Request for finding friend by uuid

사용자 삽입 이미지

Session key as HTTP header



I have found another way of disabling SSL such that I don't have to go through this "tcpdump-do stuff-copy over-analyze" madness steps. I can actually see the plain packets in real time so I can easily match the packets that the client is sending out and receiving when I do certain activity on KakaoTalk. This speeds up things a lot, but since I'm not quite done with making the PC version of KakaoTalk, let me hold on to this method just in case I can use the above mentioned method anymore!
(I will release this method once I'm kinda done with the KakaoTalk PC -- the method works both in Android and iOS.)


Next time, I'm going to talk about everything I know about the session key for KakaoTalk.
I still have one part that's not too clear to me, but I'll just post them anyways :p

Thank you for reading!




2011/06/22 21:35 2011/06/22 21:35

Starting with this blog post, and over the next few posts, I'm going to explain in detail what I have found out about internals for KakaoTalk -- the most popular mobile messaging service in Korea.

In this article, I'm going to briefly go over from what KakaoTalk is, and why it's interesting target to look at. (To be honest, I started this just for fun then turned into something that I wanted to blog about :p)

So, let the fun begin!

=-=-=-=-=-=-=-=-=-=-=

Preliminary research on KakaoTalk:
  • It is well-designed (in terms of the structure), well-organized (highly modular), and carefully planned application for the users. And as a plus, it is security-aware application :)
  • There are 15 million users, and the number is growing really fast.
  • Multi-lingual support. They really try hard to push this application globally. They utilize localization, so it's really easy for them to adopt any new language if they wanted to.
  • Kakao, for some reason, doesn't make a PC version of KakaoTalk.
    • Some people have tried to make PC version in the past, but many stopped once every packet is encrypted with SSL and thus packet capturing is meaningless.
    • My guess is that they are working on making KakaoTalk PC, but it may not be true after all :p (Maybe they don't want to be just like Skype, etc. and decided to stay only on mobile side.)
  • KakaoTalk supports both Android OS and iPhone OS.
    • Obviously, Android KakaoTalk is in Java and iOS KakaoTalk is in Object-C.
    • Uses the (very) similar protocol / data structure.
  • Some traces of development environments: (Minor Security Alert!)
    • They seem to use SVN to do version controlling, but failed to manage permissions properly. I didn't look closely anymore, but there might be some juicy/useful information that can be gathered with this vulnerability.
    • Webservers: http://www.kakao.com/.svn/entries , http://www.kakao.com/talk/.svn/entries, etc.

Well, that took me a good 20 minutes or so of googling and poking at their servers.
Not many interesting things.. So I decided to dig up some interesting facts about KakaoTalk!

To do preliminary analysis on applications, I needed to grab the binaries from my iPhone and my friend's Android. This was easily done by scp (secure copy) from my iPhone to my computer, since my device was already jailbroken. Now that I received two applications for KakaoTalk, one for iOS and the other for Android, I immediately started analyzing them.



Preliminary Analysis on KakaoTalk:

Well, before I actually open up the binaries and start disassembling, I started by running through a packet capture tool -- wireshark. As I mentioned above, the traffic was encrypted with SSL. Of course, there is known way of efficiently breaking SSL, so I didn't even try to decrypt the packets :)

사용자 삽입 이미지

SSL encrypted packets


I guess we only have one option now! Open up the binary and reverse engineer!

So we load up in IDA, and find these...awesome... wait.. what?
All the symbols are stripped?!

사용자 삽입 이미지

No Symbols :'(


I don't usually do Obj-C binary reversing, but when I do, I almost always found nicely annotated symbols! I'm not an expert at Mac Hacking, but because of the way Obj-C code does function calls, it's usually not trivial to strip symbols. (Or, I guess there's a tool that does it for you... haven't check it yet.)

BUT! Whatever! Reverse engineering is more fun without symbols. Right?

Again, the way Obj-C code runs is by event-driven function calls. Thus, there's no such thing as control flow as in usual C or C++ programs. Another annoying thing about analyzing mobile phone is that we have to deal with either ARM or MIPS architecture.

Note: For iPhone, the architecture is ARM. So, unless you have hexray-arm, you will have to go through awesome ARM opcodes. For Android, all the apps are java program that runs on Dalvik VM.. so it's usually possible to use decompilers to recover the source code (or at least some kind of IL).


Since two are almost exactly the same client, the program logic should also be very similar -- which means that if we understand one thing thoroughly, we will quickly understand the other one as well, even with the protections/obfuscation.

Ok, the binary for iPhone is stripped. How about Android one?

사용자 삽입 이미지

Obfuscated java!



Aww. Crap. We can successfully decompile the classes, but class names, method names, and variable names are all obfuscated. This makes reversing little bit harder since it's not trivial to follow the method or class names such as 'a' or 'b'. Also, Android KakaoTalk seems to use AESObfuscator. Of course, this can be decrypted since we know the IV (Initialization Vector) and other necessary parameters that were used to encrypt, but it's just a tad annoying. (AESObfuscator is basically just Base64 + AES)

At this point, I realized that KakaoTalk actually care about securing their application and the network traffic to some degree. This doesn't mean that it is perfectly secure, but they tried the security through obscurity -- usually this is a wrong way of doing security...


Anyhow, are we stumped then? The answer is 'not really'.

There are some tricks that we can do:
  1. Get (part of) code flow in iOS applications using debugger.
  2. Re-label the obfuscated java files to understand the program logic.
  3. Hack KakaoTalk server and get the source code...
And... using the information from above techniques + static analysis in IDA, we can actually disable SSL encryption -- such that we can view non-encrypted packet data.

In the next blog post, I will discuss and explain what exactly they do inside of the binary and show how I could bypass SSL and get a clean capture of the packets.

Also in the following series, I will talk about their protocols, data structures and design. And of course, the security measures on each of them.


Thanks for reading!




2011/06/19 23:04 2011/06/19 23:04
openclose