Search results

'카톡'에 해당하는 글들

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

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