最近换了份工作,开始做一些项目了;在小米的时候没怎么写代码,这猛然一写感觉还是有点陌生呢;
好了,闲扯一句之后我们进入今天的话题;
问题背景
当我们登陆一个账号,然后立即将我们的进程杀掉,然后会发现再次自动登录的时候无法登上;经过服务端查询后台代码,发现登不上是因为保存的账号与Cookie对不上导致的问题;这个就需要调查原因了;
问题分析
我们用的是公司的网络框架,但是基本原理一般应该都相同,如果需要对Cookie进行保存,最终应该都是利用默认的或者自己实现的CookieManager进行处理,主要的方法也就是getCookie和setCookie;
公司的网络框架中加了一个对于Cookie处理的拦截器;其中定义了两个CookieManager,有一个作为backup;具体涉及到内部逻辑,不能多说;但是用的其实还是AwCookManager;即webkit cookiemanager;在其中完成了Cookie的设置和读取
Cookie的保存
那么首先看下Cookie是如何保存的;如果服务器返回的header中有Set-Cookie的字段,那么我们就调用AwCookieManager的setCookie来将Cookie进行保存
/**
* Set cookie for a given url. The old cookie with same host/path/name will
* be removed. The new cookie will be added if it is not expired or it does
* not have expiration which implies it is session cookie.
* @param url The url which cookie is set for
* @param value The value for set-cookie: in http response header
*/
public void setCookie(final String url, final String value) {
nativeSetCookie(url, value);
}
从注释也可以看出;其实url就相当于是一个key;而要存的Cookie值相当于是value;当新的Cookie进来时,旧的Cookie将被覆盖;那么对于我们的账号登录来说;应该保存的是最新的登录态;这个后续可以实测验证下;下面继续分析代码;
这里会调用到CookieManager.cpp中的setCookie
static void setCookie(JNIEnv* env, jobject, jstring url, jstring value, jboolean privateBrowsing)
{
GURL gurl(jstringToStdString(env, url));
std::string line(jstringToStdString(env, value));
CookieOptions options;
options.set_include_httponly();
WebCookieJar::get(privateBrowsing)->cookieStore()->GetCookieMonster()->SetCookieWithOptions(gurl, line, options);
}
这一场长串代码最终应该会走到cookie_monster.cc中的SetCookieWithOptions
bool CookieMonster::SetCookieWithOptions(const GURL& url,
const std::string& cookie_line,
const CookieOptions& options) {
base::AutoLock autolock(lock_);
if (!HasCookieableScheme(url)) {
return false;
}
return SetCookieWithCreationTimeAndOptions(url, cookie_line, Time(), options);
}
bool CookieMonster::SetCookieWithCreationTimeAndOptions(
const GURL& url,
const std::string& cookie_line,
const Time& creation_time_or_null,
const CookieOptions& options) {
lock_.AssertAcquired();
VLOG(kVlogSetCookies) << "SetCookie() line: " << cookie_line;
Time creation_time = creation_time_or_null;
if (creation_time.is_null()) {
creation_time = CurrentTime();
last_time_seen_ = creation_time;
}
// Parse the cookie.
ParsedCookie pc(cookie_line);
if (!pc.IsValid()) {
VLOG(kVlogSetCookies) << "WARNING: Couldn't parse cookie";
return false;
}
if (options.exclude_httponly() && pc.IsHttpOnly()) {
VLOG(kVlogSetCookies) << "SetCookie() not setting httponly cookie";
return false;
}
std::string cookie_domain;
if (!GetCookieDomain(url, pc, &cookie_domain)) {
return false;
}
std::string cookie_path = CanonPath(url, pc);
std::string mac_key = pc.HasMACKey() ? pc.MACKey() : std::string();
std::string mac_algorithm = pc.HasMACAlgorithm() ?
pc.MACAlgorithm() : std::string();
scoped_ptr<CanonicalCookie> cc;
Time cookie_expires = CanonExpiration(pc, creation_time);
bool session_only = options.force_session() || cookie_expires.is_null();
cc.reset(new CanonicalCookie(url, pc.Name(), pc.Value(), cookie_domain,
cookie_path, mac_key, mac_algorithm,
creation_time, cookie_expires,
creation_time, pc.IsSecure(), pc.IsHttpOnly(),
!cookie_expires.is_null(),
!session_only));
if (!cc.get()) {
VLOG(kVlogSetCookies) << "WARNING: Failed to allocate CanonicalCookie";
return false;
}
return SetCanonicalCookie(&cc, creation_time, options);
}
bool CookieMonster::SetCanonicalCookie(scoped_ptr<CanonicalCookie>* cc,
const Time& creation_time,
const CookieOptions& options) {
const std::string key(GetKey((*cc)->Domain()));
bool already_expired = (*cc)->IsExpired(creation_time);
if (DeleteAnyEquivalentCookie(key, **cc, options.exclude_httponly(),
already_expired)) {
VLOG(kVlogSetCookies) << "SetCookie() not clobbering httponly cookie";
return false;
}
VLOG(kVlogSetCookies) << "SetCookie() key: " << key << " cc: "
<< (*cc)->DebugString();
// Realize that we might be setting an expired cookie, and the only point
// was to delete the cookie which we've already done.
if (!already_expired || keep_expired_cookies_) {
// See InitializeHistograms() for details.
if ((*cc)->DoesExpire()) {
histogram_expiration_duration_minutes_->Add(
((*cc)->ExpiryDate() - creation_time).InMinutes());
}
InternalInsertCookie(key, cc->release(), true);
}
// We assume that hopefully setting a cookie will be less common than
// querying a cookie. Since setting a cookie can put us over our limits,
// make sure that we garbage collect... We can also make the assumption that
// if a cookie was set, in the common case it will be used soon after,
// and we will purge the expired cookies in GetCookies().
GarbageCollect(creation_time, key);
return true;
}
经过上面对Cookie的处理,最终调到:
void CookieMonster::InternalInsertCookie(const std::string& key,
CanonicalCookie* cc,
bool sync_to_store) {
lock_.AssertAcquired();
if ((cc->IsPersistent() || persist_session_cookies_) &&
store_ && sync_to_store)
store_->AddCookie(*cc);
cookies_.insert(CookieMap::value_type(key, cc));
if (delegate_.get()) {
delegate_->OnCookieChanged(
*cc, false, CookieMonster::Delegate::CHANGE_COOKIE_EXPLICIT);
}
}
可以看到其实这里有两个保存的地方
cookies_.insert(CookieMap::value_type(key, cc)); 以及store_->AddCookie(*cc);
这里其实就可以想到了;一个是将Cookie的内容保存在进程的内存中,一个是将Cookie保存文件中,也就是我们常说的Cookie持久化
放到内存中的其实没什么好看的了;就是CookieMap cookies_; 这里讲我们要保存的Cookie组织成CookieMap的形式,然后保存下;重点看下持久化的部分;
大体的逻辑在
https://github.com/adobe/chromium/blob/master/chrome/browser/net/sqlite_persistent_cookie_store.cc
Cookie持久化逻辑
void SQLitePersistentCookieStore::Backend::AddCookie(
const net::CookieMonster::CanonicalCookie& cc) {
BatchOperation(PendingOperation::COOKIE_ADD, cc);
}
相当于30s才会触发commit ,也就是从setCookie到真正持久化,需要30s的时间
void SQLitePersistentCookieStore::Backend::BatchOperation(
PendingOperation::OperationType op,
const net::CookieMonster::CanonicalCookie& cc) {
// Commit every 30 seconds.
static const int kCommitIntervalMs = 30 * 1000;
// Commit right away if we have more than 512 outstanding operations.
static const size_t kCommitAfterBatchSize = 512;
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::DB));
// We do a full copy of the cookie here, and hopefully just here.
scoped_ptr<PendingOperation> po(new PendingOperation(op, cc));
PendingOperationsList::size_type num_pending;
{
base::AutoLock locked(lock_);
pending_.push_back(po.release());
num_pending = ++num_pending_;
}
if (num_pending == 1) {
// We've gotten our first entry for this batch, fire off the timer.
BrowserThread::PostDelayedTask(
BrowserThread::DB, FROM_HERE,
base::Bind(&Backend::Commit, this),
base::TimeDelta::FromMilliseconds(kCommitIntervalMs));
} else if (num_pending == kCommitAfterBatchSize) {
// We've reached a big enough batch, fire off a commit now.
BrowserThread::PostTask(
BrowserThread::DB, FROM_HERE,
base::Bind(&Backend::Commit, this));
}
}
到了这里,其实已经可以确认了;这是因为系统设计的原因造成的我们的问题;进程被杀时使用了持久化的Cookie;但是由于这个kCommitIntervalMs 时延;导致没有及时更新;
这个设计应该是为了节省IO资源吧;但是这也造成了我们这里的问题;那么很明显我们登陆之后杀掉进程,就相当于用这次账号的信息和原来保存的Cookie共同登陆,所以会产生问题
不过为了完整性,我们再确认下取Cookie的流程
Cookie的读取
也是先通过AwCookieManager 先从内存中取Cookie
std::string CookieMonster::GetCookiesWithOptions(const GURL& url,
const CookieOptions& options) {
base::AutoLock autolock(lock_);
if (!HasCookieableScheme(url))
return std::string();
TimeTicks start_time(TimeTicks::Now());
std::vector<CanonicalCookie*> cookies;
FindCookiesForHostAndDomain(url, options, true, &cookies); //
std::sort(cookies.begin(), cookies.end(), CookieSorter);
std::string cookie_line = BuildCookieLine(cookies);
histogram_time_get_->AddTime(TimeTicks::Now() - start_time);
VLOG(kVlogGetCookies) << "GetCookies() result: " << cookie_line;
return cookie_line;
}
std::string BuildCookieLine(const CanonicalCookieVector& cookies) {
std::string cookie_line;
for (CanonicalCookieVector::const_iterator it = cookies.begin();
it != cookies.end(); ++it) {
if (it != cookies.begin())
cookie_line += "; ";
// In Mozilla if you set a cookie like AAAA, it will have an empty token
// and a value of AAAA. When it sends the cookie back, it will send AAAA,
// so we need to avoid sending =AAAA for a blank token value.
if (!(*it)->Name().empty())
cookie_line += (*it)->Name() + "=";
cookie_line += (*it)->Value();
}
return cookie_line;
}
那么进程被杀之后再次启动,内存中的Cookie没了;就会取出持久化的Cookie ;其位置在
data/data/package_name/app_WebView/Cookies;
问题验证
刚刚只是通过代码分析,那么如何验证我们的分析是正确的呢?
第一次登录一个账号然后快杀,只要app_webview存了上次登录态的账号就能复现
Set_Cookie
自动登录得到的Cookie
确实是app_webview中得到的Cookie(将文件pull出来,加个后缀db;然后用sqliteStudio可以查看)
可以看出确实是持久化位置的Cookie没有及时更新造成的影响
问题结束
确认了这个之后;我前面也说道公司的网络框架还自己实现了CookieManager,通过自定义PersistentCookieStore来保存Cookie;那么是否可以利用这个来避免webkit的设计造成的漏洞呢;同事将这个需求列入计划了,后续希望能看到好的结果;哈哈