Merge cherrypicks of [3116469, 3116470, 3116074, 3116075, 3116498, 3116499, 3117095, 3115988, 3116845, 3116471, 3116500, 3116573, 3115989, 3116501, 3116076, 3116472] into oc-mr1-release

Change-Id: Ie28eb9ae8fab72c17f0e55bcd15f6a404ce0ad6a
diff --git a/keystore/auth_token_table.cpp b/keystore/auth_token_table.cpp
index 8b81e47..46b644d 100644
--- a/keystore/auth_token_table.cpp
+++ b/keystore/auth_token_table.cpp
@@ -244,7 +244,7 @@
     return (token_->userId == entry.token_->userId &&
             token_->authenticatorType == entry.token_->authenticatorType &&
             token_->authenticatorId == entry.token_->authenticatorId &&
-            timestamp_host_order() > entry.timestamp_host_order());
+            is_newer_than(&entry));
 }
 
 }  // namespace keymaster
diff --git a/keystore/auth_token_table.h b/keystore/auth_token_table.h
index 422c710..0056b26 100644
--- a/keystore/auth_token_table.h
+++ b/keystore/auth_token_table.h
@@ -114,9 +114,15 @@
         bool Supersedes(const Entry& entry) const;
         bool SatisfiesAuth(const std::vector<uint64_t>& sids, HardwareAuthenticatorType auth_type);
 
-        bool is_newer_than(const Entry* entry) {
+        bool is_newer_than(const Entry* entry) const {
             if (!entry) return true;
-            return timestamp_host_order() > entry->timestamp_host_order();
+            uint64_t ts = timestamp_host_order();
+            uint64_t other_ts = entry->timestamp_host_order();
+            // Normally comparing timestamp_host_order alone is sufficient, but here is an
+            // additional hack to compare time_received value for some devices where their auth
+            // tokens contain fixed timestamp (due to the a stuck secure RTC on them)
+            return (ts > other_ts) ||
+                   ((ts == other_ts) && (time_received_ > entry->time_received_));
         }
 
         void mark_completed() { operation_completed_ = true; }