[Win] Add option to reauthenticate the OS user before revealing passwords.

This CL depends on 28713002

BUG=303113

Review URL: https://codereview.chromium.org/34393007

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@238552 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/build/common.gypi b/build/common.gypi
index c34a5bcc..d6d48e5 100644
--- a/build/common.gypi
+++ b/build/common.gypi
@@ -2569,6 +2569,8 @@
               'odbc32.lib',
               'odbccp32.lib',
               'delayimp.lib',
+              'credui.lib',
+              'netapi32.lib',
             ],
           },
         },
diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd
index d470ff2..b99e32a 100644
--- a/chrome/app/chromium_strings.grd
+++ b/chrome/app/chromium_strings.grd
@@ -502,6 +502,11 @@
           Chromium is trying to show passwords.
         </message>
       </if>
+      <if expr="is_win">
+        <message name="IDS_PASSWORDS_PAGE_AUTHENTICATION_PROMPT" desc="Text for the dialog box that prompts the user for their OS account password before revealing plaintext passwords on the password page.">
+          Chromium is trying to show passwords. Type your Windows password to allow this.
+        </message>
+      </if>
       <message name="IDS_CANT_WRITE_USER_DIRECTORY_EXIT_BUTTON" desc="Text on button of dialog that closes Chrome if we can't create a directory for this user.">
         Exit Chromium
       </message>
diff --git a/chrome/app/google_chrome_strings.grd b/chrome/app/google_chrome_strings.grd
index 68e511b..0474d46 100644
--- a/chrome/app/google_chrome_strings.grd
+++ b/chrome/app/google_chrome_strings.grd
@@ -425,6 +425,11 @@
           Google Chrome is trying to show passwords.
         </message>
       </if>
+      <if expr="is_win">
+        <message name="IDS_PASSWORDS_PAGE_AUTHENTICATION_PROMPT" desc="Text for the dialog box that prompts the user for their OS account password before revealing plaintext passwords on the password page.">
+          Google Chrome is trying to show passwords. Type your Windows password to allow this.
+        </message>
+      </if>
       <message name="IDS_CANT_WRITE_USER_DIRECTORY_EXIT_BUTTON" desc="Text on button of dialog that closes Chrome if we can't create a directory for this user.">
         Exit Chrome
       </message>
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc
index d193dd70..0f7a721 100644
--- a/chrome/browser/about_flags.cc
+++ b/chrome/browser/about_flags.cc
@@ -1252,7 +1252,7 @@
     "password-manager-reauthentication",
     IDS_FLAGS_PASSWORD_MANAGER_REAUTHENTICATION_NAME,
     IDS_FLAGS_PASSWORD_MANAGER_REAUTHENTICATION_DESCRIPTION,
-    kOsMac,
+    kOsMac | kOsWin,
     SINGLE_VALUE_TYPE(switches::kDisablePasswordManagerReauthentication)
   },
   {
diff --git a/chrome/browser/password_manager/password_manager.h b/chrome/browser/password_manager/password_manager.h
index 527894a..3c199c5 100644
--- a/chrome/browser/password_manager/password_manager.h
+++ b/chrome/browser/password_manager/password_manager.h
@@ -23,6 +23,7 @@
 class PasswordManagerDelegate;
 class PasswordManagerTest;
 class PasswordFormManager;
+class PrefRegistrySimple;
 
 namespace user_prefs {
 class PrefRegistrySyncable;
@@ -37,7 +38,9 @@
                         public content::WebContentsUserData<PasswordManager> {
  public:
   static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
-
+#if defined(OS_WIN)
+  static void RegisterLocalPrefs(PrefRegistrySimple* registry);
+#endif
   static void CreateForWebContentsAndDelegate(
       content::WebContents* contents,
       PasswordManagerDelegate* delegate);
diff --git a/chrome/browser/password_manager/password_manager_util.h b/chrome/browser/password_manager/password_manager_util.h
index 4c6441d..7bdeb34 100644
--- a/chrome/browser/password_manager/password_manager_util.h
+++ b/chrome/browser/password_manager/password_manager_util.h
@@ -5,13 +5,16 @@
 #ifndef CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_MANAGER_UTIL_H_
 #define CHROME_BROWSER_PASSWORD_MANAGER_PASSWORD_MANAGER_UTIL_H_
 
+#include "base/basictypes.h"
+#include "ui/gfx/native_widget_types.h"
+
 namespace password_manager_util {
 
 // Attempts to (re-)authenticate the user of the OS account. Returns true if
 // the user was successfully authenticated, or if authentication was not
 // possible. On platforms where reauthentication is not possible or does not
 // make sense, the default implementation always returns true.
-bool AuthenticateUser();
+bool AuthenticateUser(gfx::NativeWindow window);
 
 }  // namespace password_manager_util
 
diff --git a/chrome/browser/password_manager/password_manager_util_stub.cc b/chrome/browser/password_manager/password_manager_util_linux.cc
similarity index 68%
rename from chrome/browser/password_manager/password_manager_util_stub.cc
rename to chrome/browser/password_manager/password_manager_util_linux.cc
index caf654a9..09fe36357 100644
--- a/chrome/browser/password_manager/password_manager_util_stub.cc
+++ b/chrome/browser/password_manager/password_manager_util_linux.cc
@@ -2,9 +2,11 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+#include "chrome/browser/password_manager/password_manager_util.h"
+
 namespace password_manager_util {
 
-bool AuthenticateUser() {
+bool AuthenticateUser(gfx::NativeWindow window) {
   return true;
 }
 
diff --git a/chrome/browser/password_manager/password_manager_util_mac.mm b/chrome/browser/password_manager/password_manager_util_mac.mm
index edb03a2..57e0761e 100644
--- a/chrome/browser/password_manager/password_manager_util_mac.mm
+++ b/chrome/browser/password_manager/password_manager_util_mac.mm
@@ -18,7 +18,7 @@
 
 namespace password_manager_util {
 
-bool AuthenticateUser() {
+bool AuthenticateUser(gfx::NativeWindow window) {
   AuthorizationItem right_items[] = {
     {"com.google.Chrome.show-passwords", 0, NULL, 0}
   };
diff --git a/chrome/browser/password_manager/password_manager_util_win.cc b/chrome/browser/password_manager/password_manager_util_win.cc
new file mode 100644
index 0000000..7f88c071
--- /dev/null
+++ b/chrome/browser/password_manager/password_manager_util_win.cc
@@ -0,0 +1,224 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// windows.h must be first otherwise Win8 SDK breaks.
+#include <windows.h>
+#include <wincred.h>
+#include <LM.h>
+
+// SECURITY_WIN32 must be defined in order to get
+// EXTENDED_NAME_FORMAT enumeration.
+#define SECURITY_WIN32 1
+#include <security.h>
+#undef SECURITY_WIN32
+
+#include "chrome/browser/password_manager/password_manager_util.h"
+
+#include "base/prefs/pref_registry_simple.h"
+#include "base/prefs/pref_service.h"
+#include "base/safe_numerics.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/time/time.h"
+#include "chrome/browser/browser_process.h"
+#include "chrome/browser/password_manager/password_manager.h"
+#include "chrome/common/pref_names.h"
+#include "content/public/browser/render_view_host.h"
+#include "content/public/browser/render_widget_host_view.h"
+#include "grit/chromium_strings.h"
+#include "grit/generated_resources.h"
+#include "ui/base/l10n/l10n_util.h"
+
+#if defined(USE_AURA)
+#include "ui/aura/root_window.h"
+#include "ui/aura/window.h"
+#endif
+
+// static
+void PasswordManager::RegisterLocalPrefs(PrefRegistrySimple* registry) {
+  registry->RegisterInt64Pref(prefs::kOsPasswordLastChanged, 0);
+  registry->RegisterBooleanPref(prefs::kOsPasswordBlank, false);
+}
+
+namespace password_manager_util {
+
+const unsigned kMaxPasswordRetries = 3;
+
+const unsigned kCredUiDefaultFlags =
+    CREDUI_FLAGS_GENERIC_CREDENTIALS |
+    CREDUI_FLAGS_EXCLUDE_CERTIFICATES |
+    CREDUI_FLAGS_KEEP_USERNAME |
+    CREDUI_FLAGS_ALWAYS_SHOW_UI |
+    CREDUI_FLAGS_DO_NOT_PERSIST;
+
+static int64 GetPasswordLastChanged(WCHAR* username) {
+  LPUSER_INFO_1 user_info = NULL;
+  DWORD age = 0;
+
+  NET_API_STATUS ret = NetUserGetInfo(NULL, username, 1, (LPBYTE*) &user_info);
+
+  if (ret == NERR_Success) {
+    // Returns seconds since last password change.
+    age = user_info->usri1_password_age;
+    NetApiBufferFree(user_info);
+  } else {
+    return -1;
+  }
+
+  base::Time changed = base::Time::Now() - base::TimeDelta::FromSeconds(age);
+
+  return changed.ToInternalValue();
+}
+
+static bool CheckBlankPassword(WCHAR* username) {
+  PrefService* local_state = g_browser_process->local_state();
+  int64 last_changed = GetPasswordLastChanged(username);
+  bool need_recheck = true;
+  bool blank_password = false;
+
+  // If we cannot determine when the password was last changed
+  // then assume the password is not blank
+  if (last_changed == -1)
+    return false;
+
+  blank_password = local_state->GetBoolean(prefs::kOsPasswordBlank);
+  int64 pref_last_changed =
+      local_state->GetInt64(prefs::kOsPasswordLastChanged);
+  if (pref_last_changed > 0 && last_changed <= pref_last_changed) {
+    need_recheck = false;
+  }
+
+  if (need_recheck) {
+    HANDLE handle = INVALID_HANDLE_VALUE;
+
+    // Attempt to login using blank password.
+    DWORD logon_result = LogonUser(username,
+                                   L".",
+                                   L"",
+                                   LOGON32_LOGON_NETWORK,
+                                   LOGON32_PROVIDER_DEFAULT,
+                                   &handle);
+
+    // Win XP and later return ERROR_ACCOUNT_RESTRICTION for blank password.
+    if (logon_result)
+      CloseHandle(handle);
+
+    // In the case the password is blank, then LogonUser returns a failure,
+    // handle is INVALID_HANDLE_VALUE, and GetLastError() is
+    // ERROR_ACCOUNT_RESTRICTION.
+    // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681385
+    blank_password = (logon_result ||
+                      GetLastError() == ERROR_ACCOUNT_RESTRICTION);
+  }
+
+  // Account for clock skew between pulling the password age and
+  // writing to the preferences by adding a small skew factor here.
+  last_changed += base::Time::kMicrosecondsPerSecond;
+
+  // Save the blank password status for later.
+  local_state->SetBoolean(prefs::kOsPasswordBlank, blank_password);
+  local_state->SetInt64(prefs::kOsPasswordLastChanged, last_changed);
+
+  return blank_password;
+}
+
+bool AuthenticateUser(gfx::NativeWindow window) {
+  bool retval = false;
+  CREDUI_INFO cui = {};
+  WCHAR username[CREDUI_MAX_USERNAME_LENGTH+1] = {};
+  WCHAR displayname[CREDUI_MAX_USERNAME_LENGTH+1] = {};
+  WCHAR password[CREDUI_MAX_PASSWORD_LENGTH+1] = {};
+  DWORD username_length = CREDUI_MAX_USERNAME_LENGTH;
+  std::wstring product_name =
+      UTF16ToWide(l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
+  std::wstring password_prompt =
+      UTF16ToWide(l10n_util::GetStringUTF16(
+                  IDS_PASSWORDS_PAGE_AUTHENTICATION_PROMPT));
+  HANDLE handle = INVALID_HANDLE_VALUE;
+  int tries = 0;
+  bool use_displayname = false;
+  bool use_principalname = false;
+  DWORD logon_result = 0;
+
+  // On a domain, we obtain the User Principal Name
+  // for domain authentication.
+  if (GetUserNameEx(NameUserPrincipal, username, &username_length)) {
+    use_principalname = true;
+  } else {
+    username_length = CREDUI_MAX_USERNAME_LENGTH;
+    // Otherwise, we're a workstation, use the plain local username.
+    if (!GetUserName(username, &username_length)) {
+      DLOG(ERROR) << "Unable to obtain username " << GetLastError();
+      return false;
+    } else {
+      // As we are on a workstation, it's possible the user
+      // has no password, so check here.
+      if (CheckBlankPassword(username))
+        return true;
+    }
+  }
+
+  // Try and obtain a friendly display name.
+  username_length = CREDUI_MAX_USERNAME_LENGTH;
+  if (GetUserNameEx(NameDisplay, displayname, &username_length))
+    use_displayname = true;
+
+  cui.cbSize = sizeof(CREDUI_INFO);
+  cui.hwndParent = NULL;
+#if defined(USE_AURA)
+  cui.hwndParent = window->GetDispatcher()->host()->GetAcceleratedWidget();
+#else
+  cui.hwndParent = window;
+#endif
+
+  cui.pszMessageText = password_prompt.c_str();
+  cui.pszCaptionText = product_name.c_str();
+
+  cui.hbmBanner = NULL;
+  BOOL save_password = FALSE;
+  DWORD credErr = NO_ERROR;
+
+  do {
+    tries++;
+
+    // TODO(wfh) Make sure we support smart cards here.
+    credErr = CredUIPromptForCredentials(
+        &cui,
+        product_name.c_str(),
+        NULL,
+        0,
+        use_displayname ? displayname : username,
+        CREDUI_MAX_USERNAME_LENGTH+1,
+        password,
+        CREDUI_MAX_PASSWORD_LENGTH+1,
+        &save_password,
+        kCredUiDefaultFlags |
+        (tries > 1 ? CREDUI_FLAGS_INCORRECT_PASSWORD : 0));
+
+    if (credErr == NO_ERROR) {
+      logon_result = LogonUser(username,
+                               use_principalname ? NULL : L".",
+                               password,
+                               LOGON32_LOGON_NETWORK,
+                               LOGON32_PROVIDER_DEFAULT,
+                               &handle);
+      if (logon_result) {
+        retval = true;
+        CloseHandle(handle);
+      } else {
+        if (GetLastError() == ERROR_ACCOUNT_RESTRICTION &&
+            wcslen(password) == 0) {
+          // Password is blank, so permit.
+          retval = true;
+        } else {
+          DLOG(WARNING) << "Unable to authenticate " << GetLastError();
+        }
+      }
+      SecureZeroMemory(password, sizeof(password));
+    }
+  } while (credErr == NO_ERROR &&
+           (retval == false && tries < kMaxPasswordRetries));
+  return retval;
+}
+
+}  // namespace password_manager_util
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc
index 6b09a7c..1ea5e1f8 100644
--- a/chrome/browser/prefs/browser_prefs.cc
+++ b/chrome/browser/prefs/browser_prefs.cc
@@ -310,6 +310,7 @@
 
 #if defined(OS_WIN)
   app_metro_launch::RegisterPrefs(registry);
+  PasswordManager::RegisterLocalPrefs(registry);
 #endif
 
 #if defined(TOOLKIT_VIEWS)
diff --git a/chrome/browser/ui/passwords/password_manager_presenter.cc b/chrome/browser/ui/passwords/password_manager_presenter.cc
index 5f723d74..a591343 100644
--- a/chrome/browser/ui/passwords/password_manager_presenter.cc
+++ b/chrome/browser/ui/passwords/password_manager_presenter.cc
@@ -17,6 +17,7 @@
 #include "chrome/common/url_constants.h"
 #include "components/autofill/core/common/password_form.h"
 #include "content/public/browser/user_metrics.h"
+#include "content/public/browser/web_contents.h"
 
 PasswordManagerPresenter::PasswordManagerPresenter(
     PasswordUIView* password_view)
@@ -93,15 +94,18 @@
 }
 
 void PasswordManagerPresenter::RequestShowPassword(size_t index) {
+#if !defined(OS_ANDROID) // This is never called on Android.
   DCHECK_LT(index, password_list_.size());
   if (IsAuthenticationRequired()) {
-    if (password_manager_util::AuthenticateUser())
+    if (password_manager_util::AuthenticateUser(
+        password_view_->GetNativeWindow()))
       last_authentication_time_ = base::TimeTicks::Now();
     else
       return;
   }
   // Call back the front end to reveal the password.
   password_view_->ShowPassword(index, password_list_[index]->password_value);
+#endif
 }
 
 const autofill::PasswordForm& PasswordManagerPresenter::GetPassword(
diff --git a/chrome/browser/ui/passwords/password_manager_presenter_unittest.cc b/chrome/browser/ui/passwords/password_manager_presenter_unittest.cc
index 6155909f6..eb77470 100644
--- a/chrome/browser/ui/passwords/password_manager_presenter_unittest.cc
+++ b/chrome/browser/ui/passwords/password_manager_presenter_unittest.cc
@@ -23,6 +23,9 @@
   }
   virtual ~MockPasswordUIView() {}
   virtual Profile* GetProfile() OVERRIDE;
+#if !defined(OS_ANDROID)
+  virtual gfx::NativeWindow GetNativeWindow() OVERRIDE;
+#endif
   MOCK_METHOD2(ShowPassword, void(size_t, const string16&));
   MOCK_METHOD2(SetPasswordList,
                void(const ScopedVector<autofill::PasswordForm>&, bool));
@@ -39,6 +42,9 @@
   DISALLOW_COPY_AND_ASSIGN(MockPasswordUIView);
 };
 
+#if !defined(OS_ANDROID)
+gfx::NativeWindow MockPasswordUIView::GetNativeWindow() { return NULL; }
+#endif
 Profile* MockPasswordUIView::GetProfile() { return profile_; }
 
 class PasswordManagerPresenterTest : public testing::Test {
diff --git a/chrome/browser/ui/passwords/password_ui_view.h b/chrome/browser/ui/passwords/password_ui_view.h
index be925f8..69b9dca 100644
--- a/chrome/browser/ui/passwords/password_ui_view.h
+++ b/chrome/browser/ui/passwords/password_ui_view.h
@@ -6,6 +6,7 @@
 #define CHROME_BROWSER_UI_PASSWORDS_PASSWORD_UI_VIEW_H_
 
 #include "base/memory/scoped_vector.h"
+#include "ui/gfx/native_widget_types.h"
 
 namespace autofill {
 struct PasswordForm;
@@ -39,6 +40,10 @@
   // |password_exception_list| The list of saved password exceptions.
   virtual void SetPasswordExceptionList(
       const ScopedVector<autofill::PasswordForm>& password_exception_list) = 0;
+#if !defined(OS_ANDROID)
+  // Returns the top level NativeWindow for the view.
+  virtual gfx::NativeWindow GetNativeWindow() = 0;
+#endif
 };
 
 #endif  // CHROME_BROWSER_UI_PASSWORDS_PASSWORD_UI_VIEW_H_
diff --git a/chrome/browser/ui/webui/options/password_manager_handler.cc b/chrome/browser/ui/webui/options/password_manager_handler.cc
index 9b43825..3805f1d 100644
--- a/chrome/browser/ui/webui/options/password_manager_handler.cc
+++ b/chrome/browser/ui/webui/options/password_manager_handler.cc
@@ -17,6 +17,8 @@
 #include "content/public/browser/notification_details.h"
 #include "content/public/browser/notification_source.h"
 #include "content/public/browser/user_metrics.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents_view.h"
 #include "content/public/browser/web_ui.h"
 #include "grit/chromium_strings.h"
 #include "grit/generated_resources.h"
@@ -34,6 +36,12 @@
   return Profile::FromWebUI(web_ui());
 }
 
+#if !defined(OS_ANDROID)
+gfx::NativeWindow PasswordManagerHandler::GetNativeWindow() {
+  return web_ui()->GetWebContents()->GetView()->GetTopLevelNativeWindow();
+}
+#endif
+
 void PasswordManagerHandler::GetLocalizedValues(
     DictionaryValue* localized_strings) {
   DCHECK(localized_strings);
diff --git a/chrome/browser/ui/webui/options/password_manager_handler.h b/chrome/browser/ui/webui/options/password_manager_handler.h
index 49b8abe..c25b05c 100644
--- a/chrome/browser/ui/webui/options/password_manager_handler.h
+++ b/chrome/browser/ui/webui/options/password_manager_handler.h
@@ -37,7 +37,9 @@
   virtual void SetPasswordExceptionList(
       const ScopedVector<autofill::PasswordForm>& password_exception_list)
       OVERRIDE;
-
+#if !defined(OS_ANDROID)
+  virtual gfx::NativeWindow GetNativeWindow() OVERRIDE;
+#endif
  private:
   // Clears and then populates the list of passwords and password exceptions.
   // Called when the JS PasswordManager object is initialized.
diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi
index 5555da2..721bdaa 100644
--- a/chrome/chrome_browser.gypi
+++ b/chrome/chrome_browser.gypi
@@ -1374,7 +1374,8 @@
         'browser/password_manager/password_manager_metrics_util.h',
         'browser/password_manager/password_manager_util.h',
         'browser/password_manager/password_manager_util_mac.mm',
-        'browser/password_manager/password_manager_util_stub.cc',
+        'browser/password_manager/password_manager_util_linux.cc',
+        'browser/password_manager/password_manager_util_win.cc',
         'browser/password_manager/password_store.cc',
         'browser/password_manager/password_store.h',
         'browser/password_manager/password_store_consumer.cc',
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc
index 8f449e0..1144e72 100644
--- a/chrome/common/pref_names.cc
+++ b/chrome/common/pref_names.cc
@@ -2626,4 +2626,13 @@
 const char kPartnerBookmarkMappings[] = "partnerbookmarks.mappings";
 #endif
 
+#if defined(OS_WIN)
+// Whether the password was blank, only valid if OS password was last changed
+// on or before the value contained in kOsPasswordLastChanged.
+const char kOsPasswordBlank[] = "password_manager.os_password_blank";
+
+// The number of seconds since epoch that the OS password was last changed.
+const char kOsPasswordLastChanged[] =
+    "password_manager.os_password_last_changed";
+#endif
 }  // namespace prefs
diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h
index 13f65c3..12ee71c 100644
--- a/chrome/common/pref_names.h
+++ b/chrome/common/pref_names.h
@@ -937,6 +937,11 @@
 extern const char kPartnerBookmarkMappings[];
 #endif
 
+#if defined(OS_WIN)
+extern const char kOsPasswordBlank[];
+extern const char kOsPasswordLastChanged[];
+#endif
+
 }  // namespace prefs
 
 #endif  // CHROME_COMMON_PREF_NAMES_H_