天天看點

百度登入加密協定分析(下)

  上一篇百度登入加密協定分析(上)主要講解了codestring,gid,token,rsakey等參數的産生。好了,廢話不多說,咱們進入今天的主題,咱們接着上一篇的内容往下講解,最後還剩三個字段 callback,password,ppui_logintime。(我的新書《Python爬蟲開發與項目實戰》出版了,大家可以看一下樣章)

百度登入加密協定分析(下)

  第三部分:    

  分析第一次post已經産生,第二次post内容發生變化的字段

    callback

    password

    ppui_logintime

  

   通過之前的分析,可以了解到callback 可能沒啥用,是以放到後面再分析。

   一般來說password的是最難分析的,是以也放到後面分析。

    

  3.1  接下來分析ppui_logintime,依舊是搜尋ppui_logintime,在下面連結中找到了ppui_logintime的出處

    http://passport.bdimg.com/passApi/js/login_tangram_a829ef5.js

百度登入加密協定分析(下)
  找到了 timeSpan: 'ppui_logintime',接着搜尋timespan
百度登入加密協定分析(下)

   找到了 r.timeSpan = (new Date).getTime() - e.initTime,

   接着搜尋initTime

百度登入加密協定分析(下)
  咱們看一下_initApi什麼時候調用的,通過搜尋找到以下代碼:

_eventHandler: function() {
    var e,
        t = {
            focus: function(t) {
                var n = e.fireEvent('fieldFocus', {
                    ele: this
                });
                n && (this.addClass(e.constant.FOCUS_CLASS), this.removeClass(e.constant.ERROR_CLASS), baidu(e.getElement(t + 'Label')).addClass(e.constant.LABEL_FOCUS_CLASS))
            },
            blur: function(t) {
                var n = e.fireEvent('fieldBlur', {
                    ele: this
                });
                n && (this.removeClass(e.constant.FOCUS_CLASS), baidu(e.getElement(t + 'Label')).removeClass(e.constant.LABEL_FOCUS_CLASS))
            },
            mouseover: function() {
                var t = e.fireEvent('fieldMouseover', {
                    ele: this
                });
                t && this.addClass(e.constant.HOVER_CLASS)
            },
            mouseout: function() {
                var t = e.fireEvent('fieldMouseout', {
                    ele: this
                });
                t && this.removeClass(e.constant.HOVER_CLASS)
            },
            keyup: function() {
                e.fireEvent('fieldKeyup', {
                    ele: this
                })
            }
        },
        n = {
            focus: {
                userName: function() {
                    e.config.loginMerge && e.getElement('loginMerge') && (e.getElement('loginMerge').value = 'true', e.getElement('isPhone').value = '')
                },
                password: function() {
                    e._getRSA(function(t) {
                        e.RSA = t.RSA,
                            e.rsakey = t.rsakey
                    })
                },
                verifyCode: function() {}
            },
            blur: {
                userName: function() {},
                password: function(t) {
                    var n = this.get(0).value;
                    n.length && e.validate(t)
                },
                verifyCode: function(t) {
                    var n = this.get(0).value;
                    n.length && e.validate(t)
                }
            },
            change: {
                userName: function() {
                    var t = this.get(0).value;
                    e._loginCheck(t)
                },
                verifyCode: function() {}
            },
            click: {
                verifyCodeChange: function(t, n) {
                    e.getElement('verifyCode').value = '',
                        e._doFocus('verifyCode'),
                        e.getVerifyCode(),
                        n.preventDefault()
                }
            },
            keyup: {
                verifyCode: function() {
                    var t = e.getElement('verifyCode'),
                        n = baidu(t);
                    t.value && 4 == t.value.length ? e._asyncValidate.checkVerifycode.call(e, {
                        error: function(t) {
                            n.addClass(e.constant.ERROR_CLASS),
                                e.setGeneralError(t.msg)
                        },
                        success: function() {
                            n.removeClass(e.constant.ERROR_CLASS),
                                e.clearGeneralError()
                        }
                    }) : e.$hide('verifyCodeSuccess')
                }
            },
            submit: function(t) {
                e.submit(),
                    t.preventDefault()
            }
        };
    return {
        entrance: function(i) {
            e = this;
            var r = (baidu(i.target), i.target.name);
            if (!r && i.target.id) {
                var o = i.target.id.match(/\d+__(.*)$/);
                o && (r = o[1])
            }
            r && (t.hasOwnProperty(i.type) && t[i.type].apply(baidu(i.target), [
                r,
                i
            ]), n.hasOwnProperty(i.type) && ('function' == typeof n[i.type] && n[i.type].apply(baidu(i.target), [
                i
            ]), n[i.type].hasOwnProperty(r) && n[i.type][r].apply(baidu(i.target), [
                r,
                i
            ])), e.initialized || 'focus' != i.type || e._initApi())
        }
    }
}(),      

  通過分析上面的js代碼可以看出來,發生點選,内容改變,按鍵按下等事件可能會調用initApi()。

  通過上面的代碼我們可以知道ppui_logintime是從你輸入登入資訊,一直到你點選登入按鈕送出的這段時間,

  是以我們通過之前的抓包,直接把ppui_logintime的值儲存下來即可。

  3.2 接着咱們分析callback,看看這字段到底是幹什麼用的(最後發現沒啥用,和上一篇得出來的推斷差不多)。搜尋callback,紅色标注的地方是不是和post出去的内容有重複。

百度登入加密協定分析(下)
callback ='bd__cbs__'+Math.floor(2147483648 *Math.random()).toString(36)      

   這個時候callback的生成當時也就确定了

  3.3 最後分析password的加密方式:搜尋password,發現敏感内容。 

  http://passport.bdimg.com/passApi/js/login_tangram_a829ef5.js

百度登入加密協定分析(下)
百度登入加密協定分析(下)

  通過下斷點,動态調試可以知道password,是通過公鑰pubkey對密碼進行加密,最後輸出進行base64編碼,

上圖的xn()就是在進行base64編碼。

   如果大家對javascript的RSA加密不熟悉,可以推薦看一下                         https://github.com/travist/jsencrypt/blob/master/src/jsencrypt.js。

等你看完了這個開源項目,你會發現,百度使用的RSA加密函數和上面的連命名幾乎一樣,這也就是為什麼能這麼快分析出RSA加密的原因。

  3.4  如何使用python進行RSA加密呢

采用的是RSA加密方式:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
password = 'xxxxxxxx'
with open('pub.pem') as f:
    pubkey = f.read()
    rsakey = RSA.importKey(pubkey)
    cipher = PKCS1_v1_5.new(rsakey)
    cipher_text = base64.b64encode(cipher.encrypt(password))
    print cipher_text      

  3.5 由于之前安裝了pyv8,是以不把gid,callback等js函數翻譯成python了,翻譯過來也很簡單,如果你電腦上沒裝pyv8,就試着翻譯一下。

function callback(){
        return 'bd__cbs__'+Math.floor(2147483648 * Math.random()).toString(36)

    }
    function gid(){
        return 'xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (e) {
        var t = 16 * Math.random() | 0,
        n = 'x' == e ? t : 3 & t | 8;
        return n.toString(16)
        }).toUpperCase()

    }      

  3.6 似乎還有驗證碼沒說,其實就是兩個連結,一個是擷取驗證碼的連結,一個是檢測驗證碼是否正确的連結。驗證碼擷取很簡單,這裡就不詳細說了。下面我會把整個登入的源代碼,貼在下面有興趣的,可以去玩一下。

總結: 

  下面我用python模拟了一下登入,使用了requests和pyv8(其實想偷懶),代碼如下:

#coding:utf-8
import base64
import json
import re
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import PyV8
from urllib import quote
import requests
import time

if __name__=='__main__':
    s = requests.Session()
    s.get('http://yun.baidu.com')
    js='''
    function callback(){
        return 'bd__cbs__'+Math.floor(2147483648 * Math.random()).toString(36)

    }
    function gid(){
        return 'xxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (e) {
        var t = 16 * Math.random() | 0,
        n = 'x' == e ? t : 3 & t | 8;
        return n.toString(16)
        }).toUpperCase()

    }
    '''
    ctxt = PyV8.JSContext()
    ctxt.enter()
    ctxt.eval(js)
    ###########擷取gid#############################3
    gid = ctxt.locals.gid()
    ###########擷取callback#############################3
    callback1 = ctxt.locals.callback()
    ###########擷取token#############################3
    tokenUrl="https://passport.baidu.com/v2/api/?getapi&tpl=netdisk&subpro=netdisk_web&apiver=v3" \
             "&tt=%d&class=login&gid=%s&logintype=basicLogin&callback=%s"%(time.time()*1000,gid,callback1)

    token_response = s.get(tokenUrl)
    pattern = re.compile(r'"token"\s*:\s*"(\w+)"')
    match = pattern.search(token_response.text)
    if match:
        token = match.group(1)

    else:
        raise Exception
    ###########擷取callback#############################3
    callback2 = ctxt.locals.callback()
    ###########擷取rsakey和pubkey#############################3
    rsaUrl = "https://passport.baidu.com/v2/getpublickey?token=%s&" \
             "tpl=netdisk&subpro=netdisk_web&apiver=v3&tt=%d&gid=%s&callback=%s"%(token,time.time()*1000,gid,callback2)
    rsaResponse = s.get(rsaUrl)
    pattern = re.compile("\"key\"\s*:\s*'(\w+)'")
    match = pattern.search(rsaResponse.text)
    if match:
        key = match.group(1)
        print key

    else:
        raise Exception
    pattern = re.compile("\"pubkey\":'(.+?)'")
    match = pattern.search(rsaResponse.text)
    if match:
        pubkey = match.group(1)
        print pubkey

    else:
        raise Exception
    ################加密password########################3
    password = 'xxxxxxx'#填上自己的密碼
    pubkey = pubkey.replace('\\n','\n').replace('\\','')
    rsakey = RSA.importKey(pubkey)
    cipher = PKCS1_v1_5.new(rsakey)
    password = base64.b64encode(cipher.encrypt(password))
    print password
    ###########擷取callback#############################3
    callback3 = ctxt.locals.callback()
    data={
        'apiver':'v3',
        'charset':'utf-8',
        'countrycode':'',
        'crypttype':12,
        'detect':1,
        'foreignusername':'',
        'idc':'',
        'isPhone':'',
        'logLoginType':'pc_loginBasic',
        'loginmerge':True,
        'logintype':'basicLogin',
        'mem_pass':'on',
        'quick_user':0,
        'safeflg':0,
        'staticpage':'http://yun.baidu.com/res/static/thirdparty/pass_v3_jump.html',
        'subpro':'netdisk_web',
        'tpl':'netdisk',
        'u':'http://yun.baidu.com/',
        'username':'xxxxxxxxx',#填上自己的使用者名
        'callback':'parent.'+callback3,
        'gid':gid,'ppui_logintime':71755,
        'rsakey':key,
        'token':token,
        'password':password,
        'tt':'%d'%(time.time()*1000),


    }
    ###########第一次post#############################3
    post1_response = s.post('https://passport.baidu.com/v2/api/?login',data=data)
    pattern = re.compile("codeString=(\w+)&")
    match = pattern.search(post1_response.text)
    if match:
    ###########擷取codeString#############################3
        codeString = match.group(1)
        print codeString

    else:
        raise Exception
    data['codestring']= codeString
    #############擷取驗證碼###################################
    verifyFail = True
    while verifyFail:
        genimage_param = ''
        if len(genimage_param)==0:
            genimage_param = codeString

        verifycodeUrl="https://passport.baidu.com/cgi-bin/genimage?%s"%genimage_param
        verifycode = s.get(verifycodeUrl)
        #############下載下傳驗證碼###################################
        with open('verifycode.png','wb') as codeWriter:
            codeWriter.write(verifycode.content)
            codeWriter.close()
        #############輸入驗證碼###################################
        verifycode = raw_input("Enter your input verifycode: ");
        callback4 = ctxt.locals.callback()
        #############檢驗驗證碼###################################
        checkVerifycodeUrl='https://passport.baidu.com/v2/?' \
                        'checkvcode&token=%s' \
                        '&tpl=netdisk&subpro=netdisk_web&apiver=v3&tt=%d' \
                        '&verifycode=%s&codestring=%s' \
                        '&callback=%s'%(token,time.time()*1000,quote(verifycode),codeString,callback4)
        print checkVerifycodeUrl
        state = s.get(checkVerifycodeUrl)
        print state.text
        if state.text.find(u'驗證碼錯誤')!=-1:
            print '驗證碼輸入錯誤...已經自動更換...'
            callback5 = ctxt.locals.callback()
            changeVerifyCodeUrl = "https://passport.baidu.com/v2/?reggetcodestr" \
                                  "&token=%s" \
                                  "&tpl=netdisk&subpro=netdisk_web&apiver=v3" \
                                  "&tt=%d&fr=login&" \
                                  "vcodetype=de94eTRcVz1GvhJFsiK5G+ni2k2Z78PYRxUaRJLEmxdJO5ftPhviQ3/JiT9vezbFtwCyqdkNWSP29oeOvYE0SYPocOGL+iTafSv8pw" \
                                  "&callback=%s"%(token,time.time()*1000,callback5)
            print changeVerifyCodeUrl
            verifyString = s.get(changeVerifyCodeUrl)
            pattern = re.compile('"verifyStr"\s*:\s*"(\w+)"')
            match = pattern.search(verifyString.text)
            if match:
            ###########擷取verifyString#############################3
                verifyString = match.group(1)
                genimage_param = verifyString
                print verifyString

            else:
                verifyFail = False
                raise Exception

        else:
            verifyFail = False
    data['verifycode']= verifycode
    ###########第二次post#############################3
    data['ppui_logintime']=81755      

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

   # 特地說明,大家會發現第二次的post出去的密碼是改變的,為什麼我這裡沒有變化呢?

   #是因為RSA加密,加密密鑰和密碼原文即使不變,每次加密後的密碼都是改變的,RSA有随機因子的關系

   #是以我這裡不需要在對密碼原文進行第二次加密了,直接使用上次加密後的密碼即可,是沒有問題的。

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

post2_response = s.post('https://passport.baidu.com/v2/api/?login',data=data)
    if post2_response.text.find('err_no=0')!=-1:
        print '登入成功'

    else:
        print '登入失敗'      

  我把整個代碼上傳到git上了:https://github.com/qiyeboy/baidulogin.git,大家可以star和fork。

  今天的分享就到這裡,如果大家覺得還可以呀,記得推薦呦。


歡迎大家支援我公衆号:         
百度登入加密協定分析(下)
本文章屬于原創作品,歡迎大家轉載分享,禁止修改文章的内容。尊重原創,轉載請注明來自:七夜的故事 http://www.cnblogs.com/qiyeboy/      

本文章屬于原創作品,歡迎大家轉載分享,禁止修改文章的内容。尊重原創,轉載請注明來自:七夜的故事 http://www.cnblogs.com/qiyeboy/