Home | History | Annotate | Download | only in util
      1 // Copyright 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef SYNC_UTIL_CRYPTOGRAPHER_H_
      6 #define SYNC_UTIL_CRYPTOGRAPHER_H_
      7 
      8 #include <map>
      9 #include <string>
     10 
     11 #include "base/gtest_prod_util.h"
     12 #include "base/memory/linked_ptr.h"
     13 #include "base/memory/scoped_ptr.h"
     14 #include "sync/base/sync_export.h"
     15 #include "sync/protocol/encryption.pb.h"
     16 #include "sync/util/nigori.h"
     17 
     18 namespace sync_pb {
     19 class NigoriKeyBag;
     20 class NigoriSpecifics;
     21 }
     22 
     23 namespace syncer {
     24 
     25 class Encryptor;
     26 
     27 SYNC_EXPORT_PRIVATE extern const char kNigoriTag[];
     28 
     29 // The parameters used to initialize a Nigori instance.
     30 struct KeyParams {
     31   std::string hostname;
     32   std::string username;
     33   std::string password;
     34 };
     35 
     36 // This class manages the Nigori objects used to encrypt and decrypt sensitive
     37 // sync data (eg. passwords). Each Nigori object knows how to handle data
     38 // protected with a particular passphrase.
     39 //
     40 // Whenever an update to the Nigori sync node is received from the server,
     41 // SetPendingKeys should be called with the encrypted contents of that node.
     42 // Most likely, an updated Nigori node means that a new passphrase has been set
     43 // and that future node updates won't be decryptable. To remedy this, the user
     44 // should be prompted for the new passphrase and DecryptPendingKeys be called.
     45 //
     46 // Whenever a update to an encrypted node is received from the server,
     47 // CanDecrypt should be used to verify whether the Cryptographer can decrypt
     48 // that node. If it cannot, then the application of that update should be
     49 // delayed until after it can be decrypted.
     50 class SYNC_EXPORT Cryptographer {
     51  public:
     52   // Does not take ownership of |encryptor|.
     53   explicit Cryptographer(Encryptor* encryptor);
     54   ~Cryptographer();
     55 
     56   // |restored_bootstrap_token| can be provided via this method to bootstrap
     57   // Cryptographer instance into the ready state (is_ready will be true).
     58   // It must be a string that was previously built by the
     59   // GetSerializedBootstrapToken function.  It is possible that the token is no
     60   // longer valid (due to server key change), in which case the normal
     61   // decryption code paths will fail and the user will need to provide a new
     62   // passphrase.
     63   // It is an error to call this if is_ready() == true, though it is fair to
     64   // never call Bootstrap at all.
     65   void Bootstrap(const std::string& restored_bootstrap_token);
     66 
     67   // Returns whether we can decrypt |encrypted| using the keys we currently know
     68   // about.
     69   bool CanDecrypt(const sync_pb::EncryptedData& encrypted) const;
     70 
     71   // Returns whether |encrypted| can be decrypted using the default encryption
     72   // key.
     73   bool CanDecryptUsingDefaultKey(const sync_pb::EncryptedData& encrypted) const;
     74 
     75   // Encrypts |message| into |encrypted|. Does not overwrite |encrypted| if
     76   // |message| already matches the decrypted data within |encrypted| and
     77   // |encrypted| was encrypted with the current default key. This avoids
     78   // unnecessarily modifying |encrypted| if the change had no practical effect.
     79   // Returns true unless encryption fails or |message| isn't valid (e.g. a
     80   // required field isn't set).
     81   bool Encrypt(const ::google::protobuf::MessageLite& message,
     82                sync_pb::EncryptedData* encrypted) const;
     83 
     84   // Encrypted |serialized| into |encrypted|. Does not overwrite |encrypted| if
     85   // |message| already matches the decrypted data within |encrypted| and
     86   // |encrypted| was encrypted with the current default key. This avoids
     87   // unnecessarily modifying |encrypted| if the change had no practical effect.
     88   // Returns true unless encryption fails or |message| isn't valid (e.g. a
     89   // required field isn't set).
     90   bool EncryptString(const std::string& serialized,
     91                      sync_pb::EncryptedData* encrypted) const;
     92 
     93   // Decrypts |encrypted| into |message|. Returns true unless decryption fails,
     94   // or |message| fails to parse the decrypted data.
     95   bool Decrypt(const sync_pb::EncryptedData& encrypted,
     96                ::google::protobuf::MessageLite* message) const;
     97 
     98   // Decrypts |encrypted| and returns plaintext decrypted data. If decryption
     99   // fails, returns empty string.
    100   std::string DecryptToString(const sync_pb::EncryptedData& encrypted) const;
    101 
    102   // Encrypts the set of currently known keys into |encrypted|. Returns true if
    103   // successful.
    104   bool GetKeys(sync_pb::EncryptedData* encrypted) const;
    105 
    106   // Creates a new Nigori instance using |params|. If successful, |params| will
    107   // become the default encryption key and be used for all future calls to
    108   // Encrypt.
    109   // Will decrypt the pending keys and install them if possible (pending key
    110   // will not overwrite default).
    111   bool AddKey(const KeyParams& params);
    112 
    113   // Same as AddKey(..), but builds the new Nigori from a previously persisted
    114   // bootstrap token. This can be useful when consuming a bootstrap token
    115   // with a cryptographer that has already been initialized.
    116   // Updates the default key.
    117   // Will decrypt the pending keys and install them if possible (pending key
    118   // will not overwrite default).
    119   bool AddKeyFromBootstrapToken(const std::string restored_bootstrap_token);
    120 
    121   // Creates a new Nigori instance using |params|. If successful, |params|
    122   // will be added to the nigori keybag, but will not be the default encryption
    123   // key (default_nigori_ will remain the same).
    124   // Prereq: is_initialized() must be true.
    125   // Will decrypt the pending keys and install them if possible (pending key
    126   // will become the new default).
    127   bool AddNonDefaultKey(const KeyParams& params);
    128 
    129   // Decrypts |encrypted| and uses its contents to initialize Nigori instances.
    130   // Returns true unless decryption of |encrypted| fails. The caller is
    131   // responsible for checking that CanDecrypt(encrypted) == true.
    132   // Does not modify the default key.
    133   void InstallKeys(const sync_pb::EncryptedData& encrypted);
    134 
    135   // Makes a local copy of |encrypted| to later be decrypted by
    136   // DecryptPendingKeys. This should only be used if CanDecrypt(encrypted) ==
    137   // false.
    138   void SetPendingKeys(const sync_pb::EncryptedData& encrypted);
    139 
    140   // Makes |pending_keys_| available to callers that may want to cache its
    141   // value for later use on the UI thread. It is illegal to call this if the
    142   // cryptographer has no pending keys. Like other calls that access the
    143   // cryptographer, this method must be called from within a transaction.
    144   const sync_pb::EncryptedData& GetPendingKeys() const;
    145 
    146   // Attempts to decrypt the set of keys that was copied in the previous call to
    147   // SetPendingKeys using |params|. Returns true if the pending keys were
    148   // successfully decrypted and installed. If successful, the default key
    149   // is updated.
    150   bool DecryptPendingKeys(const KeyParams& params);
    151 
    152   // Sets the default key to the nigori with name |key_name|. |key_name| must
    153   // correspond to a nigori that has already been installed into the keybag.
    154   void SetDefaultKey(const std::string& key_name);
    155 
    156   bool is_initialized() const {
    157     return !nigoris_.empty() && !default_nigori_name_.empty();
    158   }
    159 
    160   // Returns whether this Cryptographer is ready to encrypt and decrypt data.
    161   bool is_ready() const {
    162     return is_initialized() && !has_pending_keys();
    163   }
    164 
    165   // Returns whether there is a pending set of keys that needs to be decrypted.
    166   bool has_pending_keys() const { return NULL != pending_keys_.get(); }
    167 
    168   // Obtain a token that can be provided on construction to a future
    169   // Cryptographer instance to bootstrap itself.  Returns false if such a token
    170   // can't be created (i.e. if this Cryptograhper doesn't have valid keys).
    171   bool GetBootstrapToken(std::string* token) const;
    172 
    173   Encryptor* encryptor() const { return encryptor_; }
    174 
    175   // Returns true if |keybag| is decryptable and either is a subset of nigoris_
    176   // and/or has a different default key.
    177   bool KeybagIsStale(const sync_pb::EncryptedData& keybag) const;
    178 
    179   // Returns a serialized sync_pb::NigoriKey version of current default
    180   // encryption key.
    181   std::string GetDefaultNigoriKey() const;
    182 
    183   // Generates a new Nigori from |serialized_nigori_key|, and if successful
    184   // installs the new nigori as the default key.
    185   bool ImportNigoriKey(const std::string serialized_nigori_key);
    186 
    187  private:
    188   typedef std::map<std::string, linked_ptr<const Nigori> > NigoriMap;
    189 
    190   // Helper method to instantiate Nigori instances for each set of key
    191   // parameters in |bag|.
    192   // Does not update the default nigori.
    193   void InstallKeyBag(const sync_pb::NigoriKeyBag& bag);
    194 
    195   // Helper method to add a nigori to the keybag, optionally making it the
    196   // default as well.
    197   bool AddKeyImpl(scoped_ptr<Nigori> nigori, bool set_as_default);
    198 
    199   // Helper to unencrypt a bootstrap token into a serialized sync_pb::NigoriKey.
    200   std::string UnpackBootstrapToken(const std::string& token) const;
    201 
    202   Encryptor* const encryptor_;
    203 
    204   // The Nigoris we know about, mapped by key name.
    205   NigoriMap nigoris_;
    206   // The key name associated with the default nigori. If non-empty, must
    207   // correspond to a nigori within |nigoris_|.
    208   std::string default_nigori_name_;
    209 
    210   scoped_ptr<sync_pb::EncryptedData> pending_keys_;
    211 
    212   DISALLOW_COPY_AND_ASSIGN(Cryptographer);
    213 };
    214 
    215 }  // namespace syncer
    216 
    217 #endif  // SYNC_UTIL_CRYPTOGRAPHER_H_
    218