How Google Chrome Stores Passwords

Skill

How Google Chrome Stores Passwords

Posted in:

Every browser released in the last decade has some sort of password management system, and Google Chrome is no different. I've been sifting through the Chrome source code, released under the open source project Chromium, and I've found out how they do it. In this tutorial, I'll post all of the source code used by Google Chrome to quickly and securely save your passwords.

Let's start at the top and work our way down. Any time a password is saved, you're first prompted with the save password bar.

Google Chrome save password prompt

In Chrome, this object is called PasswordManager. This object is responsible for a lot of stuff, but what we really care about is what happens when you click "Save Password".

Google Chrome save password buttons

When you click the save button, it calls the following function:

void PasswordManager::SavePasswordBar::OKButtonPressed() {
  form_manager_->Save();
  BeginClose();
}

form_manager is another object, PasswordFormManager, that sits between the user interface and the database. All this function does is call that object's Save method. It then instructs the save password prompt to close. Here's what the Save function looks like.

void PasswordFormManager::Save() {
  DCHECK_EQ(state_, POST_MATCHING_PHASE);
  DCHECK(!profile_->IsOffTheRecord());

  if (IsNewLogin())
    SaveAsNewLogin();
  else
    UpdateLogin();
}

Again, pretty straight forward. The first two items will log information for debugging purposes and aren't compiled in release mode. It then checks if it is adding a new password or updating an existing one. For the purposes of this tutorial, let's look at adding a new password.

void PasswordFormManager::SaveAsNewLogin() {
  DCHECK_EQ(state_, POST_MATCHING_PHASE);
  DCHECK(IsNewLogin());
  // The new_form is being used to sign in, so it is preferred.
  DCHECK(pending_credentials_.preferred);
  // new_form contains the same basic data as observed_form_ (because its the
  // same form), but with the newly added credentials.

  DCHECK(!profile_->IsOffTheRecord());

  WebDataService* web_data_service =  
      profile_->GetWebDataService(Profile::IMPLICIT_ACCESS);
  if (!web_data_service) {
    NOTREACHED();
    return;
  }
  pending_credentials_.date_created = Time::Now();
  web_data_service->AddLogin(pending_credentials_);
}

Most of this function is debug code. What we care about is the call to AddLogin. The WebDataService object is responsible for meta data associated with a web page.

void WebDataService::AddLogin(const PasswordForm& form) {
  GenericRequest<PasswordForm>* request =
      new GenericRequest<PasswordForm>(this, GetNextRequestHandle(), NULL, form);
  RegisterRequest(request);
  ScheduleTask(NewRunnableMethod(this, &WebDataService::AddLoginImpl, request));
}

Now we're getting a little more complicated. Adding a password is done asynchronously and this function handles scheduling that task. It seemed to be very important that nothing interrupt Chrome's user interface - this keeps it feeling fast and responsive. Now let's take a look at what happens when this task is run.

void WebDataService::AddLoginImpl(
  GenericRequest<PasswordForm>* request) {
  if (db_ && !request->IsCancelled()) {
    if (db_->AddLogin(request->GetArgument()))
      ScheduleCommit();
  }
  request->RequestComplete();
}

We're almost at the heart of it all. The important call here is AddLogin, so let's dive into that.

bool WebDatabase::AddLogin(const PasswordForm& form) {
  SQLStatement s;
  std::string encrypted_password;
  if (s.prepare(db_,
    "INSERT OR REPLACE INTO logins "
    "(origin_url, action_url, username_element, username_value, "
    " password_element, password_value, submit_element, "
    " signon_realm, ssl_valid, preferred, date_created, "
    " blacklisted_by_user, scheme) "
    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") != SQLITE_OK) {
    NOTREACHED() << "Statement prepare failed";
    return false;
  }

  s.bind_string(0, form.origin.spec());
  s.bind_string(1, form.action.spec());
  s.bind_wstring(2, form.username_element);
  s.bind_wstring(3, form.username_value);
  s.bind_wstring(4, form.password_element);
  Encryptor::EncryptWideString(form.password_value, &encrypted_password);
  s.bind_blob(5, encrypted_password.data(),
              static_cast<int>(encrypted_password.length()));
  s.bind_wstring(6, form.submit_element);
  s.bind_string(7, form.signon_realm);
  s.bind_int(8, form.ssl_valid);
  s.bind_int(9, form.preferred);
  s.bind_int64(10, form.date_created.ToTimeT());
  s.bind_int(11, form.blacklisted_by_user);
  s.bind_int(12, form.scheme);
  if (s.step() != SQLITE_DONE) {
    NOTREACHED();
    return false;
  }
  return true;
}

We've finally reached the end of the line. This function actually builds the SQL statement for adding a new password to Chrome's SQLite database. Of course, the password isn't stored in plain text so Chrome has an Encryptor object responsible for encrypting the password first. Let's take a look at that.

bool Encryptor::EncryptString(const std::string& plaintext,
                              std::string* ciphertext) {
  DATA_BLOB input;
  input.pbData = const_cast<BYTE*>(reinterpret_cast<const BYTE*>(plaintext.data()));
  input.cbData = static_cast<DWORD>(plaintext.length());

  DATA_BLOB output;
  BOOL result = CryptProtectData(&input, L"", NULL, NULL, NULL, 0, &output);
  if (!result)
    return false;

  // this does a copy
  ciphertext->assign(
      reinterpret_cast<std::string::value_type*>(output.pbData), output.cbData);

  LocalFree(output.pbData);
  return true;
}

The important piece here is CryptProtectData, which is a Windows API function for encrypting data. Data encrypted with this function is pretty solid. It can only be decrypted on the same machine and by the same user that encrypted it in the first place.

So what'd we learn by investigating Chrome's password management system? Well, we learned that Google uses SQLite as the storage mechanism for passwords and other web page related data. We also see that Google has done a great job extracting Windows specific code from the cross-platform stuff. The only Windows specific code here is the encryption function, which can easily be ported by creating a different Encryptor object for each OS.

That does it for this walk-through of Google Chrome's password storage mechanism. It's always neat to see how other projects get things done. And of course, a chance to see Google's code in action is never something to pass up.

Andreas
09/10/2008 - 09:49

Great idea: when I move to a new OS (say XP->Vista), all my passwords are lost?

reply

Peter Petrov
09/10/2008 - 11:12

Not only moving to Vista, but moving to another computer or reinstalling Win XP and your passwords will be lost.

reply

Zach
09/10/2008 - 11:25

You do realise that means I also can't simply copy the Chrome DB and extrate at my leasure? By saving passwords at all, your already breaking "best" security practices... Sure some browsers make you put in another password to get to your saved passwords, but its still a point of failure. The most unfortunate thing is that the passwords can be revealed so easily, and that it doesn't indicate that when you save them.

reply

Bob
09/10/2008 - 16:12

Yes, andreas, when someone steals your computer and installs a new OS in order to get to your data because they don't know your password, your encrypted data is still safe.

The entire freaking point is that a convenient utility should not let any random joe steal the password to your bank account.

reply

Anonymous
01/04/2010 - 03:38

do you mean the password for the operating system? thats not safe at all, for years you have been able to reset the admin password to blank with a boot disk. not safe at all.

reply

David
09/10/2008 - 17:19

If you move to a new OS, the old OS will be overwritten. Therefore, you will lose all your passwords.

reply

Robie
09/10/2008 - 11:04

This encryption reminds me of the secure nuclear reactor that Mr. Burns works in, with the screen-door entry in the main room.

This encryption protects your passwords from the uber-haxxors stealing data from the FBI, but does not protect your passwords from your co-workers/family members/friends who occasionally use your computer.

To steal a co-workers or family member's or friends passwords from Chrome:
1. Open Chrome
2. Open Chrome Options
3. Under the "Minor Tweaks" tab, click "Show Saved Passwords"
4. Click on Gmail or something juicy, then click "Show password"

Done. Congratulations. You have just beat the secure Encryption method. Hope Bruce Willis doesn't come after you now that you are elite.

reply

The Fattest
09/10/2008 - 11:09

Robie, very good point.

reply

Tony
09/10/2008 - 11:27

Robie, I don't think anything can adequately protect you if you walk away from your computer while it's still logged in to your account. At best, they could request re-authentication before you click "Show Saved Passwords", but a user could still navigate to all your frequently used websites and log in as you without knowing your password.

The proper solution is to set up a guest account on your computer for occasional users to use.

reply

Anonymous
01/04/2010 - 03:42

nope, as i said above. you dont even need to leave your computer on and logged in for someone to break into your admin account. as long as they have local access to your machine, and the intent to take your info, youre screwed.

as robbie says, the best encryption in the world is defeated by a simple menu press.

reply

Olli
09/10/2008 - 12:09

Being able to view your own passwords is a feature, not a problem.

If they didn't put this feature in you'd be in the situation where you couldn't access the passwords yourself but any moderately competent hacker (with access to your machine + user account) would be able to.

Firefox has this same feature for this very reason.

If you want to protect your private data you should be preventing people from accessing your user account.

reply

Bob
09/10/2008 - 16:12

Robbie, you clearly don;'t understand. it's more like how the bank vault with the secure door doesn't help much if the bank president and all the staff decide they want to take the gold and run. If you want to stop your friends and family getting your passwords, don't let them use your freaking account. You're the sort of person who throws the key to your car to a person then cries because now that you've given them the key they can take the car.

Why don't you alert us all to the amazing insecurity that lets the guy with the system administrator password get access to the system?

reply

Robie
09/10/2008 - 17:21

Bob--

You've never been left at someone's computer to fix it? I'd assume anyone who can understand this post has been commissioned to provide free tech support. Many times.

Yes, Firefox allows you to view saved passwords, as does Safari (via Keychain) and Opera. Password safes do this too.

However, all of these examples provide an extra layer of protection. *None* of these examples have no layer of extra protection, where if you have access to the account, then you have access to the passwords.

If you are asked to fix a computer w/ Firefox being the main browser, it's up to the user to secure the passwords with a Master Password. If IE is the main browser, then you have to use something like RockXP to retrieve passwords. But if they use Chrome, you can retrieve their passwords quickly, painlessly, and without a trace.

When someone asks me if Firefox is secure, I tell them to set a Master Password. If someone asked me whether they should use Chrome, I'd say disable remembering passwords until this is fixed. That's the point of my post - to the average user (the 90% of market share Google is going after), Chrome is "not secure."

The encryption they use is fine, but remember: average users (at my company) leave their computers unlocked, average users (in my family) ask me to fix computers and leave them to me, average users (of my friends) will lend me their computer to check something quick w/o thinking of the security implications. That's my point: to the average user, Firefox can be secured but Chrome cannot.

reply

Anonymous
02/23/2009 - 23:52

Robie, you are exactly right here. Not protecting saved passwords is like putting your open wallet on a ten foot chain. Except that the guy with the wallet would realize he's going to get robbed. Not implementing good security on the basis that you can never provide perfect security is madness. So you can't avoid every password grabber or brute force attack so you just give up right there without trying? The average user does not need rotating key encryption, with biometrics, stored miles below the earth's surface; the average user needs protection against someone noticing a computer that is logged on and using chrome to view a password is plain text with 3 keystrokes. Why even think about more security if you can't provide the most basic level?

reply

Null
09/10/2008 - 23:27

Once physical access is gained, all security goes out the window. There are zero foolproof methods currently for securing a PC from someone who has physical access. Trying to trick people into a false sense of security seems counterproductive if your goal is to actually build a secure browser.

reply

The Hairiest
09/11/2008 - 06:30

First off, super-awesome post Red-Man. Secondly, I think chrome is quite an awesome browser, and it did just come out like a week ago, so of course it will have a few fixes.

The whole thing really boils down to your browsing habits really. If all you do is go to Google, yahoo, and the occasional forum, chances are pretty good an attack on your computer is slim. If you delete an email that was sent by ANYONE you don't know or by a system you don't recognize, your chances are even lower. If you make sure to check every link you click, your chances again grow smaller. We are all nerds here, we know how to avoid such things. Safe browsing will always be a good defense against attacks. Of course bad things will happen, no matter how hard you try.

As far as someone who is fixing your computer.......I think if you are letting someone fix your computer, especially if it is your companies IT guy (Which I happen to be one), they should be trusted. I mean lets be truthful here, if there is something you don't want them to see, chances are it's really not suppose to be there anyway. Personally, I don't care what is on someones computer, I just fix them when things go wrong. I have access to any computer I want, but that doesn't give the right to start stealing passwords from random computers I fix.

So, if you want to be more secure, for now you will just have to disable the feature and move on. I like chrome and if I have something like my Bank Account to check up one, I use an external Password manager to handle that. With Firefox I didn't even use the profile feature. In the end, if you passwords get stolen, you have only yourself to blame.

reply

David W
09/10/2008 - 12:45

At such an early stage of public release, I'm personally satisfied they're doing enough to avoid a potentially ugly security problem (plaintext passwords on disk) using the least effort required on their part (using a robust Windows API function for doing this).

I'd like to see them moving to a model like Firefox, where your profile has an associated master password. This would permit copying between machines etc.

reply

The Fattest
09/10/2008 - 12:50

I agree that I would like to see some work done to make this portable to other machines/installs.

reply

Ton
09/10/2008 - 12:46

Strange AddLogin makes a call to Encryptor::EncryptWideString but in your analysis you cover instead Encryptor::EncryptString. So we can we can assume they are both the same functionally besides the byte widths of the strings right? Also, another thing that worries me is the call to CryptProtectData being directly in the method. Things like this should really be abstracted behind a generic interface for all OS specific APIs to reduce coupling. Otherwise, the code looks pretty clean and readable, something I don't see too much in the codebases I usually take a peek at.

reply

The Fattest
09/10/2008 - 12:50

From what I have seen poking around the source code and reading up on contributing over at http://www.chromium.org/ they seem to be using #ifdef for compiling for different OSes. http://dev.chromium.org/developers/coding-style

reply

The Reddest
09/10/2008 - 12:51

I skipped an extra call. Encryptor::EncryptWideString does very little aside from simply calling Encryptor::EncryptString.

reply

Ton
09/10/2008 - 13:24

Thanks for the replies guys. Anyway I had a brain fart and forgot that C/C++ doesn't support interfaces really but something that approximates a interface can be created with a pure virtual class in C++. I figure they could have the #ifdef in the class to tell which implementation to use. Oh well, I've been coding/studying languages like C# and Java too much I guess. Good post.

reply

The Fattest
09/10/2008 - 13:39

ton, you and me both. it hadn't even occurred to me either. I do think you are right about the #ifdef though.

reply

JIffy Wiper
09/10/2008 - 13:40

I still think FireFox 3 kicks Chrome to the curb!

Jiff
www.anonymize.us.tc

reply

Chris
09/10/2008 - 16:06

Hey, I really appreciate the write up. I am not very familiar with C/C++, I am currently trying to learn C. When you say that most of the code inside the function is debug code, what does that mean?

reply

The Fattest
09/10/2008 - 17:44

Chris, when he talks about debug code. He is talking about the code they use when developing the browser to check to make sure everything is working ok. So one function might write some variables to a log to check or output to a debug console. Does this make more sense?

reply

Chris
09/10/2008 - 19:49

Yes this makes sense, thank you. Reading source is still hard for me when it comes to C, especially since I do not know how to open the source as a project. I usually use Codeblocks, do you have any suggestions?

reply

AtoBtoB
09/11/2008 - 01:42

Those... Goddamn... Bastards...

Umm.. wait... reeeeeewind.

For all they've done for the internet... (Google) don't they deserve to know what porn sites I've visited. I think so.

Eat a Kit Kat bar and then take a walk bro. This in no way effects your day to day life... Unless your some sort of terrorist or perverted and illegal porn site view-eee. Save all the passwords you like and read all the emails you want.. Google is the future and I support them 100%. If you really give a crap then your probably doing something illegal... and you should be held accountable.

Google for Pres 2008.

reply

Max
09/11/2008 - 03:51

It had been invented when people use to work on one computer?

These guys needs to take some fresh air.

But what's about accessing from any computer any where?

Normally when you are login or filling a form is that you are connected to the internet.

Most of the traffic of registering/sending passwords take place through EMail.

Google provide a very powerfull EMail.

Whyle not storing passwords and form field value in GMail? or any Mail.

Clicking on a crypted link within the mail text display the login form page, fill all fields and press submit.

One email can store hundreds of links sufficient for most of us.

Why not do this for favorites also? To not leave trace either.

Automatic filling avoïd key loggers sniffing.

Another option is to fill a form ID with most of the encountered fields once, storing as a link in your email, have an addon that receive this link ask you the link of the form and when displayed fill it by matching form field with id field as firstname -> first.

Too simple...

I like the idea to log to my email and have a favorites email that link me to all my links, fill form field values for me and press the right Submit button.

Another standardization is the naming of form fields.

reply

Jib
09/11/2008 - 05:54

If Google created a system for storing passwords in GMail, they would immediately be condemned for invading people's privacy. Even if the system were well-documented and completely opt-in and used encryption with a master password to prevent Google knowing your passwords, the paranoid Google conspiracy theorists would still have a reasonable chance of drowning out the rational discussion about the system, and it would be likely to be bad for Google's reputation.

reply

Michael Moscheck
09/15/2008 - 12:00

As it is now, Chrome is not at all secure to save passwords, period. I have to tell my clients not to use it if they save passwords while browsing. I've only had two people install it and I shut off the "Save Passwords" option an both.

It's a simple fix. I'm sure Google will fix it soon.

There are some problems with using Firefox to store pwds. There are easy hacks for the master pwd not to mention people leave their browsers open and logged into Master Password all the time. Since it's not completely secure I advise my laptop clients to use a good password manager (Big Crocodile, Password Safe SWT, etc...). How many take that advice is another question. Unfortunately I'm an independent and can't set my clients' office security.

reply

The Fattest
09/15/2008 - 14:05

I am sorry Michael, I have to disagree here. The not secure part is letting people play around on your computer while your logged in under your user. Now the current method can be improved by adding a master password. I think you would be better to tell your clients to lock their computer when leaving it unattended than to not use a feature that is easily secure unless you're dumb enough to let someone you don't trust play around on your computer.

reply

Scott Kingsley Clark
09/19/2008 - 09:35

I'm going to have to chime in here, even if Firefox has a master password set, if anyone leaves their browser open after they've entered their master password once during their browser session -- someone can easily go to that person's favorite site, log out, then go to the log-in screen and use the Web Developer toolbar to View Password form fields, which will give you that shiny password you thought was so secure. Nothing is secure about password 'remembering' -- AT ALL. Plain and simple, we sacrifice a lot by making things easy whether it be remembering passwords using the browser or using one password for everything we use.

So I don't feel less secure with Google Chrome than I was with Firefox 3, I'm just happy to be enjoying the MANY other benefits Chrome has over other browsers to-date.

reply

Film fan
09/16/2008 - 05:41

i keep learning about more and more advantages and features with Chrome, with privacy, for example; now if only they would take care of it's cookie management glitches...

reply

Web design company
09/21/2008 - 17:36

Pretty detailed article on google chrome innards. Nice.

reply

Shripad
09/23/2008 - 07:24

Chrome is super cool, but I am not going to use it unless they implement master password.

(Why just Google don't write a few lines of code instead of arguing about why it is necessary )

If I want to let anybody use the firefox on ur PC, I close the browser and open a new one so that it asks for the master password everytime he goes to the website for which I stored the password.

Closing the browser (and opening a new one)is more easier than logging off and opening a guest account. (More than that it is not polite to say ur Boss I don't trust you )

reply

Mitch
09/16/2008 - 16:56

I'm trying to get this to work, just from a user perspective. I use chrome, go to a web site that has a password, type it in, and most of the time Chrome forgets it. I have enabled all cookies. What else do I have to do to get it to work? Thanks.

reply

Cleaver
01/09/2009 - 05:39

There is only way to secure your passwords.. keep them in mind and unckeck the flag “remember your password”

reply

Tapas Chandra
03/17/2009 - 07:13

I want to know the details of Javascript. Can any one help me?

reply

Smita
03/17/2009 - 07:16

Yes I will help you.

reply

Anonymous
04/06/2009 - 13:35

the "show password" function is backwards and undermines nearly all of the users online security. even when logged out of a user account, we all know that windows is not the most secure OS out there.
i would hate to imagine what could happen if anyone got into my system and realized that Chrome gives them a free ride to run amok with all of my PW's.

reply

VenomXII
05/04/2009 - 12:55

Alright all, this is your fix if you need to reload your OS or somthing else where you want your old passwords imported into chrome.

for instance. i upgraded from xp to vista hp 64bit. it was a clean install on a totally seperate harddrive.

I fortunatly had Firefox where all of my passwords where saved. on my xp hd.

so with the vista installed. and chrome dled and ready to go, i started thinking damit i don't remember any of my passwords firefox had everything. and this chrome had nothing saved, and the fire fox i installed on my vista machine was also clean.

so i plugged my old hd back in so i could access all of my old files. i went to docs and settings> Local settings> application data> Mozilla fire fox...and copied everything there to my Vista path C:\Users> (user name)> appdata> local> Mozilla >firefox.
I also had to copy the files from xp box C:\Docs and settings>(username)>Application Data>Mozilla. all of these get copied to vista box C:\Users>(username)appdata>Local>Mozilla>firefox

then run firefox to make sure everything is there. close Firefox.

Open Chrome. go to tools> Import bookmarks and settings> then choose firefox from the "from" dropdown. i would uncheck browsing history unless you really want that imported, then hit the import button. once its done you should be able to go back to tools>options>Minor Tweaks> click on Show passwords and all of them should be there, if you click on one and then click the button to the right, " show password" your password should show up under the button.
Volia you imported your passwords back to your new box.
feel free to post this solution anywhere. but please give me credit for it. thanks all, happy surfing.

reply

Anonymous
05/24/2009 - 02:09

credit for explaining how to backup FF settings and then during the chrome install by default click continue and all your FF data will be ported over to chromium? How big is that ego of yours, if people don't backup their data with FF built in export feature before they move CP's or reinstall that is their issue.

reply

Anonymous
08/27/2009 - 23:50

How to disable "autocomplete=off" in Chrome to force it to save passwords in all pages? In other words, something like this http://brettshaffer.com/how-to/force-firefox-to-save-password/ for Firefox.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors