기본 콘텐츠로 건너뛰기

Meteor 에서 외부 Application으로 DDP 인증 (2) : SRP 교환

DDP로 인증을 하려면 네트웍상에 평문으로 보내지 않기 위해
SRP(Secure Remote Password) 라는 프로토콜로 변환한다.

https://github.com/meteor/meteor/tree/devel/packages/srp

package.js 를 보면 biginteger 와 sha256 을 사용한다.

구현해야할 부분은 https://github.com/meteor/meteor/blob/devel/packages/accounts-password/password_client.js#L10
이 곳 참조.

password 를 가지고 다음과 같이.

    s = new srp.Client password
    request = s.startExchange()
    if typeof selector == 'string'
      selector =
        if ~selector.indexof("@")
        then username: selector
        else email: selector
    request.user = selector

beginPasswordExchange 를 시작하는 부분의 인자는 request 자체를 사용.
request 내용은 A를 키로 하는 SRP 암호문과 user를 키로하는 사용자명이 되겠다.

method 쏴준다. A에 srp로 암호화한 문자를 사용.


{ msg: 'method',
  method: 'beginPasswordExchange',
  params:
   [ { A: '439284960ce6bc7c163262b5629a467cd06bb982432615ec526a1ed204d2f76a1a254faaab6c5c9309e120d708e3e46fe58d8c5017aedb85efb9670cfcbf8a8b2dd996a6226f7be032bfedc23b1261093c0374e3e176fb374818f8a38b015517c8bfc3cc1326967760bdeaac09e154e115826022cdcea75f944d61a7e724721a',
       user: {
         username: "......."  /* 혹은  email: "...." */
       } } ],
  id: '1' }

형식으로 보내면 되겠다.
코드를 써보면

  if dataJSON.msg is 'ready'
    console.log '>> method beginPasswordExchange'
    s = new srp.Client password
    request = s.startExchange()
    if typeof selector is 'string'
      selector =
        if ~selector.indexOf("@")
        then email: selector
        else username: selector
    request.user = selector
    sendObject =
      msg: 'method',
      method: 'beginPasswordExchange',
      params: [request]
      id: (++nextid).toString()
    ws.send JSON.stringify sendObject

ready 이후에 이런식으로 써주면 되겠다. id는 1 넣으니 Malformed method invocation 오류가 나니 sequence 값을 계속 사용하고 있다.

돌려보니

>> method beginPasswordExchange
{ msg: 'updated', methods: [ '2' ] }
{ msg: 'result',
  id: '2',
  result:
   { identity: 'YzHuNjbsWJm5KvDce',
     salt: 'sre6wg5ENP2FFNc42',
     B: '6bd07e3539b211ad523e38509501becba435618e25d6bd3f55852311a4c8d5a49cc0b29ffa8ccc28d3122a12b6ee20fefa01fd313fbe92c4200156e7faa7c21e3a43b3949fc7feaba9843c858f3144d92994261e7a86f9154593ec795c7725bf73e8e4fa2febda2a4fcb8bb84aa248a2ad2bb1c31d13bdc1bf025e3deec813aa' } }

하지만 이게 전부는 아니다.
서버에 갔다와서 해쉬를 받아오는 부분이라 유저명만 체크한다고 봐도 된다. 암호는 결과 값을 기준으로 확인해야함.

login method를 쏴보자.

{
  "msg":"method",
  "method":"login",
  "params":[
    {
      "srp":{
        "M":"e3e18d009a23a2f560e8eb157b6eca9d686dc4f95e2f0381ba9a8fb8dd4fa9de"
      }
    }
  ],
  "id":"2"
}

분석해보니 이런 내용이 websocket 나왔었다.
일단 여기까지 별 어려움 없이 잘 왔다.

어짜피 한 password 방식일때인 경우만 분석해봤는데
다른 경우도 크게 다르지 않을 거라고 생각한다.

전체 소스는 gist(https://gist.github.com/acidsound/6330360)에 올려놓겠다.

nextid = 0
connected = false;
ws = require 'ws'
## srp library from https://github.com/meteor/meteor/tree/devel/packages/srp
srp = require './lib/srp.js'
isLogin = false

## id/pass
selector = '<ID>'
password = '<PASS>'
s = new srp.Client password

ws = new ws 'ws://localhost:3000/websocket'
ws.on 'open', ->
  console.log "open socket"
  ws.send JSON.stringify
    msg: 'connect'
    version: 'pre1'
    support: ['pre1']
ws.on 'message', (data, flags)->
  dataJSON = JSON.parse data
  console.log dataJSON
  if dataJSON.msg is 'connected'
    connected = true
    ws.send JSON.stringify
      msg: 'sub'
      id: (++nextid).toString()
      name: 'meteor.loginServiceConfiguration'
  if dataJSON.msg is 'ready'
    if not isLogin
      console.log '>> method beginPasswordExchange'
      request = s.startExchange()
      if typeof selector is 'string'
        selector =
          if ~selector.indexOf("@")
          then email: selector
          else username: selector
      request.user = selector
      sendObject =
        msg: 'method'
        method: 'beginPasswordExchange'
        params: [request]
        id: (++nextid).toString()
      ws.send JSON.stringify sendObject
  if dataJSON.msg is 'result'
    if not isLogin
      console.log ">> checked username"
      if !!dataJSON.error
        console.log ">> username fail"
      else
        response = s.respondToChallenge dataJSON.result
        sendObject =
          msg: 'method'
          method: 'login'
          params: [
            srp: response
          ]
          id: (++nextid).toString()
        console.log JSON.stringify sendObject
        ws.send JSON.stringify sendObject
        isLogin = true
    else
      ## after login
      if !!dataJSON.error
        console.log ">>>> incorrect password"
      else
        if s.verifyConfirmation(HAMK:dataJSON.result.HAMK)
          console.log ">>>> login success"
        else
          console.log ">>>> server is cheating!"




댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.org 를

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.