Example #1
0
        public void TestCreateSaveAndLoad_TestIdenticalFiles_kdb()
        {
            string filename = DefaultDirectory + "createsaveandload.kdb";
            IKp2aApp app = SetupAppWithDatabase(filename);
            string kdbxXml = DatabaseToXml(app);
            //save it and reload it
            Android.Util.Log.Debug("KP2A", "-- Save DB -- ");
            SaveDatabase(app);
            Android.Util.Log.Debug("KP2A", "-- Load DB -- ");

            PwDatabase pwImp = new PwDatabase();
            PwDatabase pwDatabase = app.GetDb().KpDatabase;
            pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
            pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
            pwImp.MasterKey = pwDatabase.MasterKey;

            IOConnectionInfo ioc = new IOConnectionInfo() {Path = filename};
            using (Stream s = app.GetFileStorage(ioc).OpenFileForRead(ioc))
            {
                app.GetDb().DatabaseFormat.PopulateDatabaseFromStream(pwImp, s, null);
            }
            string kdbxReloadedXml = DatabaseToXml(app);

            RemoveKdbLines(ref kdbxReloadedXml);
            RemoveKdbLines(ref kdbxXml);

            Assert.AreEqual(kdbxXml, kdbxReloadedXml);
        }
Example #2
0
        public void CreateAndSaveLocal()
        {
            IKp2aApp app = new TestKp2aApp();
            IOConnectionInfo ioc = new IOConnectionInfo {Path = DefaultFilename};

            File outputDir = new File(DefaultDirectory);
            outputDir.Mkdirs();
            File targetFile = new File(ioc.Path);
            if (targetFile.Exists())
                targetFile.Delete();

            bool createSuccesful = false;
            //create the task:
            CreateDb createDb = new CreateDb(app, Application.Context, ioc, new ActionOnFinish((success, message) =>
                { createSuccesful = success;
                    if (!success)
                        Android.Util.Log.Debug("KP2A_Test", message);
                }), false);
            //run it:

            createDb.Run();
            //check expectations:
            Assert.IsTrue(createSuccesful);
            Assert.IsNotNull(app.GetDb());
            Assert.IsNotNull(app.GetDb().KpDatabase);
            //the create task should create two groups:
            Assert.AreEqual(2, app.GetDb().KpDatabase.RootGroup.Groups.Count());

            //ensure the the database can be loaded from file:
            PwDatabase loadedDb = new PwDatabase();
            loadedDb.Open(ioc, new CompositeKey(), null, new KdbxDatabaseFormat(KdbxFormat.Default));

            //Check whether the databases are equal
            AssertDatabasesAreEqual(loadedDb, app.GetDb().KpDatabase);
        }
        public async Task<object> Invoke(dynamic args)
        {
            var argsLookup = (IDictionary<string, object>)args;
            int databaseHandle = -1;
            string name = null, path = null;


            if (argsLookup.ContainsKey("handle"))
                databaseHandle = (int)argsLookup["database"];

            if (argsLookup.ContainsKey("name"))
                name = (string)argsLookup["name"];

            if (argsLookup.ContainsKey("path"))
                path = (string)argsLookup["path"];


            var database = TypedHandleTracker.GetObject<PwDatabase>(databaseHandle);

            if(database.Name != name)
                database.Name = name;
            

            if(database.IOConnectionInfo.Path != path)
            {
                var ioc = new IOConnectionInfo() { Path = path };
                database.SaveAs(ioc, true, null);
                return new { handle = databaseHandle, path = path, name = name };
            }

            
            database.Save(null);
            return new { handle = databaseHandle, path = path, name = name };
        }
Example #4
0
		private void Construct(IOConnectionInfo iocFile, bool bThrowIfDbFile)
		{
			byte[] pbFileData = IOConnection.ReadFile(iocFile);
			if(pbFileData == null) throw new FileNotFoundException();

			if(bThrowIfDbFile && (pbFileData.Length >= 8))
			{
				uint uSig1 = MemUtil.BytesToUInt32(MemUtil.Mid(pbFileData, 0, 4));
				uint uSig2 = MemUtil.BytesToUInt32(MemUtil.Mid(pbFileData, 4, 4));

				if(((uSig1 == KdbxFile.FileSignature1) &&
					(uSig2 == KdbxFile.FileSignature2)) ||
					((uSig1 == KdbxFile.FileSignaturePreRelease1) &&
					(uSig2 == KdbxFile.FileSignaturePreRelease2)) ||
					((uSig1 == KdbxFile.FileSignatureOld1) &&
					(uSig2 == KdbxFile.FileSignatureOld2)))
#if KeePassLibSD
					throw new Exception(KLRes.KeyFileDbSel);
#else
					throw new InvalidDataException(KLRes.KeyFileDbSel);
#endif
			}

			byte[] pbKey = LoadXmlKeyFile(pbFileData);
			if(pbKey == null) pbKey = LoadKeyFile(pbFileData);

			if(pbKey == null) throw new InvalidOperationException();

			m_strPath = iocFile.Path;
			m_pbKeyData = new ProtectedBinary(true, pbKey);

			MemUtil.ZeroByteArray(pbKey);
		}
		public KeyProviderQueryContext(IOConnectionInfo ioInfo, bool bCreatingNewKey)
		{
			if(ioInfo == null) throw new ArgumentNullException("ioInfo");

			m_ioInfo = ioInfo.CloneDeep();
			m_bCreatingNewKey = bCreatingNewKey;
		}
Example #6
0
		private void Initialize(IOConnectionInfo iocBaseFile, bool bTransacted)
		{
			if(iocBaseFile == null) throw new ArgumentNullException("iocBaseFile");

			m_bTransacted = bTransacted;
			m_iocBase = iocBaseFile.CloneDeep();

			string strPath = m_iocBase.Path;

			// Prevent transactions for FTP URLs under .NET 4.0 in order to
			// avoid/workaround .NET bug 621450:
			// https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
			if(strPath.StartsWith("ftp:", StrUtil.CaseIgnoreCmp) &&
				(Environment.Version.Major >= 4) && !NativeLib.IsUnix())
				m_bTransacted = false;
			else
			{
				foreach(KeyValuePair<string, bool> kvp in g_dEnabled)
				{
					if(strPath.StartsWith(kvp.Key, StrUtil.CaseIgnoreCmp))
					{
						m_bTransacted = kvp.Value;
						break;
					}
				}
			}

			if(m_bTransacted)
			{
				m_iocTemp = m_iocBase.CloneDeep();
				m_iocTemp.Path += StrTempSuffix;
			}
			else m_iocTemp = m_iocBase;
		}
Example #7
0
 public string GetDisplayName(IOConnectionInfo ioc)
 {
     string displayName = null;
     if (TryGetDisplayName(ioc, ref displayName))
         return "content://" + displayName; //make sure we return the protocol in the display name for consistency, also expected e.g. by CreateDatabaseActivity
     return ioc.Path;
 }
Example #8
0
 public void InitEx(bool bSave, IOConnectionInfo ioc, bool bCanRememberCred,
     bool bTestConnection)
 {
     m_bSave = bSave;
     if(ioc != null) m_ioc = ioc;
     m_bCanRememberCred = bCanRememberCred;
     m_bTestConnection = bTestConnection;
 }
Example #9
0
		public void InitEx(IOConnectionInfo ioInfo, bool bCanExit,
			bool bRedirectActivation)
		{
			if(ioInfo != null) m_ioInfo = ioInfo;

			m_bCanExit = bCanExit;
			m_bRedirectActivation = bRedirectActivation;
		}
Example #10
0
 public CreateDb(IKp2aApp app, Context ctx, IOConnectionInfo ioc, OnFinish finish, bool dontSave)
     : base(finish)
 {
     _ctx = ctx;
     _ioc = ioc;
     _dontSave = dontSave;
     _app = app;
 }
		public void StartFileUsageProcess(IOConnectionInfo ioc, int requestCode, bool alwaysReturnSuccess)
		{
			Intent fileStorageSetupIntent = new Intent(_activity, typeof(FileStorageSetupActivity));
			fileStorageSetupIntent.PutExtra(FileStorageSetupDefs.ExtraProcessName, FileStorageSetupDefs.ProcessNameFileUsageSetup);
			fileStorageSetupIntent.PutExtra(FileStorageSetupDefs.ExtraAlwaysReturnSuccess, alwaysReturnSuccess);
			PasswordActivity.PutIoConnectionToIntent(ioc, fileStorageSetupIntent);

			_activity.StartActivityForResult(fileStorageSetupIntent, requestCode);
		}
Example #12
0
 public static bool CheckShutdown(Activity act, IOConnectionInfo ioc)
 {
     if ((  !App.Kp2a.DatabaseIsUnlocked )
         || (IocChanged(ioc, App.Kp2a.GetDb().Ioc))) //file was changed from ActionSend-Intent
     {
         App.Kp2a.LockDatabase();
         return true;
     }
     return false;
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _ioc = App.Kp2a.GetDb().Ioc;

            _intentReceiver = new LockingClosePreferenceActivityBroadcastReceiver(this);
            IntentFilter filter = new IntentFilter();
            filter.AddAction(Intents.DatabaseLocked);
            RegisterReceiver(_intentReceiver, filter);
        }
		public void StartSelectFileProcess(IOConnectionInfo ioc, bool isForSave, int requestCode)
		{
			Kp2aLog.Log("FSSIA: StartSelectFileProcess "+ioc.Path);
			Intent fileStorageSetupIntent = new Intent(_activity, typeof(FileStorageSetupActivity));
			fileStorageSetupIntent.PutExtra(FileStorageSetupDefs.ExtraProcessName, FileStorageSetupDefs.ProcessNameSelectfile);
			fileStorageSetupIntent.PutExtra(FileStorageSetupDefs.ExtraIsForSave, isForSave);
			PasswordActivity.PutIoConnectionToIntent(ioc, fileStorageSetupIntent);

			_activity.StartActivityForResult(fileStorageSetupIntent, requestCode);
		}
		private void Initialize(IOConnectionInfo iocBaseFile, bool bTransacted)
		{
			if(iocBaseFile == null) throw new ArgumentNullException("iocBaseFile");

			m_bTransacted = bTransacted;
			m_iocBase = iocBaseFile.CloneDeep();

			string strPath = m_iocBase.Path;

			if(m_iocBase.IsLocalFile())
			{
				try
				{
					if(File.Exists(strPath))
					{
						// Symbolic links are realized via reparse points;
						// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365503.aspx
						// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365680.aspx
						// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365006.aspx
						// Performing a file transaction on a symbolic link
						// would delete/replace the symbolic link instead of
						// writing to its target
						FileAttributes fa = File.GetAttributes(strPath);
						if((long)(fa & FileAttributes.ReparsePoint) != 0)
							m_bTransacted = false;
					}
				}
				catch(Exception) { Debug.Assert(false); }
			}

#if !KeePassUAP
			// Prevent transactions for FTP URLs under .NET 4.0 in order to
			// avoid/workaround .NET bug 621450:
			// https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
			if(strPath.StartsWith("ftp:", StrUtil.CaseIgnoreCmp) &&
				(Environment.Version.Major >= 4) && !NativeLib.IsUnix())
				m_bTransacted = false;
#endif

			foreach(KeyValuePair<string, bool> kvp in g_dEnabled)
			{
				if(strPath.StartsWith(kvp.Key, StrUtil.CaseIgnoreCmp))
				{
					m_bTransacted = kvp.Value;
					break;
				}
			}

			if(m_bTransacted)
			{
				m_iocTemp = m_iocBase.CloneDeep();
				m_iocTemp.Path += StrTempSuffix;
			}
			else m_iocTemp = m_iocBase;
		}
Example #16
0
        public LoadDb(IKp2aApp app, IOConnectionInfo ioc, Task<MemoryStream> databaseData, CompositeKey compositeKey, String keyfileOrProvider, OnFinish finish)
            : base(finish)
        {
            _app = app;
            _ioc = ioc;
            _databaseData = databaseData;
            _compositeKey = compositeKey;
            _keyfileOrProvider = keyfileOrProvider;

            _rememberKeyfile = app.GetBooleanPreference(PreferenceKey.remember_keyfile);
        }
Example #17
0
        private static WebClient CreateWebClient(IOConnectionInfo ioc)
        {
            WebClient wc = new WebClient();

            wc.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

            if((ioc.UserName.Length > 0) || (ioc.Password.Length > 0))
                wc.Credentials = new NetworkCredential(ioc.UserName, ioc.Password);

            return wc;
        }
Example #18
0
        public static bool Export(PwExportInfo pwExportInfo, string strFormatName,
            IOConnectionInfo iocOutput)
        {
            if(strFormatName == null) throw new ArgumentNullException("strFormatName");
            // iocOutput may be null

            FileFormatProvider prov = Program.FileFormatPool.Find(strFormatName);
            if(prov == null) return false;

            NullStatusLogger slLogger = new NullStatusLogger();
            return Export(pwExportInfo, prov, iocOutput, slLogger);
        }
		private void Initialize(IOConnectionInfo iocBaseFile, bool bTransacted)
		{
			if(iocBaseFile == null) throw new ArgumentNullException("iocBaseFile");

			m_bTransacted = bTransacted;
			m_iocBase = iocBaseFile.CloneDeep();

			if(m_bTransacted)
			{
				m_iocTemp = m_iocBase.CloneDeep();
				m_iocTemp.Path += StrTempSuffix;
			}
			else m_iocTemp = m_iocBase;
		}
Example #20
0
        public bool CheckForFileChangeFast(IOConnectionInfo ioc, string previousFileVersion)
        {
            return false;

            //commented because this currently might use the network which is not permitted here
            /*try
            {
                return Jfs.CheckForFileChangeFast(ioc.Path, previousFileVersion);
            }
            catch (Java.Lang.Exception e)
            {
                throw LogAndConvertJavaException(e);
            }*/
        }
Example #21
0
 public bool CheckForFileChangeFast(IOConnectionInfo ioc, string previousFileVersion)
 {
     if (!ioc.IsLocalFile())
         return false;
     if (previousFileVersion == null)
         return false;
     DateTime previousDate;
     if (!DateTime.TryParse(previousFileVersion, CultureInfo.InvariantCulture, DateTimeStyles.None, out previousDate))
         return false;
     DateTime currentModificationDate = File.GetLastWriteTimeUtc(ioc.Path);
     TimeSpan diff = currentModificationDate - previousDate;
     return diff > TimeSpan.FromSeconds(1);
     //don't use > operator because milliseconds are truncated
     //return File.GetLastWriteTimeUtc(ioc.Path) - previousDate >= TimeSpan.FromSeconds(1);
 }
Example #22
0
        public static IOConnectionInfo GetParentPath(IOConnectionInfo ioc)
        {
            var iocParent = ioc.CloneDeep();
            if (iocParent.Path.EndsWith("/"))
                iocParent.Path = iocParent.Path.Substring(0, iocParent.Path.Length - 1);

            int slashPos = iocParent.Path.LastIndexOf("/", StringComparison.Ordinal);
            if (slashPos == -1)
                iocParent.Path = "";
            else
            {
                iocParent.Path = iocParent.Path.Substring(0, slashPos);
            }
            return iocParent;
        }
Example #23
0
 public void CreateDirectory(IOConnectionInfo ioc, string newDirName)
 {
     try
     {
         Jfs.CreateFolder(IocToPath(ioc), newDirName);
     }
     catch (FileNotFoundException e)
     {
         throw new System.IO.FileNotFoundException(e.Message, e);
     }
     catch (Java.Lang.Exception e)
     {
         throw LogAndConvertJavaException(e);
     }
 }
Example #24
0
        public static IOConnectionInfo CreateConnectionInfo(string databaseFileName, string credentialSaveMode = "NoSave")
        {
            if (databaseFileName == null)
                throw new ArgumentNullException("databaseFileName");

            var ioc = new IOConnectionInfo();
            ioc.Path = databaseFileName;

            var saveMode = IOCredSaveMode.NoSave;
            if (credentialSaveMode != "NoSave")
                Enum.TryParse(credentialSaveMode, out saveMode);

            ioc.CredSaveMode = saveMode;

            return ioc;
        }
Example #25
0
        public FileLock(IOConnectionInfo iocBaseFile)
        {
            if(iocBaseFile == null) throw new ArgumentNullException("strBaseFile");

            m_iocLockFile = iocBaseFile.CloneDeep();
            m_iocLockFile.Path += LockFileExt;

            LockFileInfo lfiEx = LockFileInfo.Load(m_iocLockFile);
            if(lfiEx != null)
            {
                m_iocLockFile = null; // Otherwise Dispose deletes the existing one
                throw new FileLockException(iocBaseFile.GetDisplayName(),
                    lfiEx.GetOwner());
            }

            LockFileInfo.Create(m_iocLockFile);
        }
Example #26
0
        public static void Copy(IOConnectionInfo targetIoc, IOConnectionInfo sourceIoc, IKp2aApp app)
        {
            IFileStorage sourceStorage = app.GetFileStorage(sourceIoc, false); //don't cache source. file won't be used ever again
            IFileStorage targetStorage = app.GetFileStorage(targetIoc);

            using (
                var writeTransaction = targetStorage.OpenWriteTransaction(targetIoc,
                                                                          app.GetBooleanPreference(
                                                                              PreferenceKey.UseFileTransactions)))
            {
                using (var writeStream = writeTransaction.OpenFile())
                {
                    sourceStorage.OpenFileForRead(sourceIoc).CopyTo(writeStream);
                }
                writeTransaction.CommitWrite();
            }
        }
Example #27
0
        public static bool CreateAuxFile(OtpInfo otpInfo,
			KeyProviderQueryContext ctx, IOConnectionInfo auxFileIoc)
        {
            otpInfo.Type = ProvType;
            otpInfo.Version = ProvVersion;
            otpInfo.Generator = ProductName;

            otpInfo.EncryptSecret();

            if(!OtpInfo.Save(auxFileIoc, otpInfo))
            {
                MessageService.ShowWarning("Failed to save auxiliary OTP info file:",
                    auxFileIoc.GetDisplayName());
                return false;
            }

            return true;
        }
Example #28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyTheme();

            if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(
                GetString(Resource.String.ViewDatabaseSecure_key), true))
            {
                Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            }

            _ioc = App.Kp2a.GetDb().Ioc;

            _intentReceiver = new LockCloseListActivityBroadcastReceiver(this);
            IntentFilter filter = new IntentFilter();

            filter.AddAction(Intents.DatabaseLocked);
            filter.AddAction(Intent.ActionScreenOff);
            RegisterReceiver(_intentReceiver, filter);
        }
Example #29
0
        public static PwDatabase CreateKeePassDatabase(string databasePath, CompositeKey compositeKey)
        {
            if (!databasePath.EndsWith(".kdbx"))
                throw new FileNotFoundException("The database file must end with .kdbx");

            var directoryName = Path.GetDirectoryName(databasePath);
            var fileName = Path.GetFileName(databasePath);

            if (!Directory.Exists(directoryName))
                Directory.CreateDirectory(directoryName);

            var ioc = new IOConnectionInfo();
            ioc.Path = fileName;
            ioc.CredSaveMode = IOCredSaveMode.NoSave;

            var database = new PwDatabase();
            database.New(ioc, compositeKey);
            database.Save(null);

            return database;
        }
        protected override Stream OpenFileForReadWithConflict(IOConnectionInfo ioc, string cachedFilePath)
        {
            OtpInfo remoteOtpInfo, localOtpInfo;
            //load both files
            XmlSerializer xs = new XmlSerializer(typeof(OtpInfo));
            using (var cacheStream = File.OpenRead(cachedFilePath))
            {
                localOtpInfo = (OtpInfo) xs.Deserialize(cacheStream);
            }
            using (Stream remoteStream = _cachedStorage.OpenFileForRead(ioc))
            {
                remoteOtpInfo = (OtpInfo)xs.Deserialize(remoteStream);
            }

            //see which OtpInfo has the bigger Counter value and use this one:
            if (localOtpInfo.Counter > remoteOtpInfo.Counter)
            {
                //overwrite the remote file
                UpdateRemoteFile(File.OpenRead(cachedFilePath),
                                 ioc,
                                 App.Kp2a.GetBooleanPreference(PreferenceKey.UseFileTransactions),
                                 GetBaseVersionHash(ioc)
                    );

                _cacheSupervisor.ResolvedCacheConflictByUsingRemote(ioc);
            }
            else
            {
                //overwrite the local file:
                UpdateCacheFromRemote(ioc, cachedFilePath);
                _cacheSupervisor.ResolvedCacheConflictByUsingLocal(ioc);
            }

            //now return the local file in any way:
            return File.OpenRead(cachedFilePath);
        }
Example #31
0
 public string GetDisplayName(IOConnectionInfo ioc)
 {
     return(_cachedStorage.GetDisplayName(ioc));
 }
Example #32
0
 private void StoreFilePath(IOConnectionInfo folderPath, string filename, IOConnectionInfo res)
 {
     File.WriteAllText(CachedFilePath(GetPseudoIoc(folderPath, filename)) + ".filepath", res.Path);
 }
Example #33
0
 public bool IsPermanentLocation(IOConnectionInfo ioc)
 {
     //even though the cache would be permanent, it's not a good idea to cache a temporary file, so return false in that case:
     return(_cachedStorage.IsPermanentLocation(ioc));
 }
 public virtual IFileStorage GetFileStorage(IOConnectionInfo iocInfo)
 {
     return(FileStorage);
 }
Example #35
0
 public string GetLocalVersionHash(IOConnectionInfo ioc)
 {
     return(File.ReadAllText(VersionFilePath(ioc)));
 }
Example #36
0
        protected override void OnCreate(Bundle bundle)
        {
            _design.ApplyTheme();
            base.OnCreate(bundle);

            //use FlagSecure to make sure the last (revealed) character of the password is not visible in recent apps
            if (PreferenceManager.GetDefaultSharedPreferences(this).GetBoolean(
                    GetString(Resource.String.ViewDatabaseSecure_key), true))
            {
                Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            }

            _ioc = App.Kp2a.GetDb().Ioc;

            if (_ioc == null)
            {
                Finish();
                return;
            }

            SetContentView(Resource.Layout.QuickUnlock);

            var toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.mytoolbar);

            SetSupportActionBar(toolbar);

            var collapsingToolbar = FindViewById <CollapsingToolbarLayout>(Resource.Id.collapsing_toolbar);

            collapsingToolbar.SetTitle(GetString(Resource.String.QuickUnlock_prefs));

            if (App.Kp2a.GetDb().KpDatabase.Name != "")
            {
                FindViewById(Resource.Id.filename_label).Visibility       = ViewStates.Visible;
                ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetDb().KpDatabase.Name;
            }
            else
            {
                if (
                    PreferenceManager.GetDefaultSharedPreferences(this)
                    .GetBoolean(GetString(Resource.String.RememberRecentFiles_key),
                                Resources.GetBoolean(Resource.Boolean.RememberRecentFiles_default)))
                {
                    ((TextView)FindViewById(Resource.Id.filename_label)).Text = App.Kp2a.GetFileStorage(_ioc).GetDisplayName(_ioc);
                }
                else
                {
                    ((TextView)FindViewById(Resource.Id.filename_label)).Text = "*****";
                }
            }


            TextView txtLabel = (TextView)FindViewById(Resource.Id.QuickUnlock_label);

            _quickUnlockLength = App.Kp2a.QuickUnlockKeyLength;

            txtLabel.Text = GetString(Resource.String.QuickUnlock_label, new Java.Lang.Object[] { _quickUnlockLength });

            EditText pwd = (EditText)FindViewById(Resource.Id.QuickUnlock_password);

            pwd.SetEms(_quickUnlockLength);
            Util.MoveBottomBarButtons(Resource.Id.QuickUnlock_buttonLock, Resource.Id.QuickUnlock_button, Resource.Id.bottom_bar, this);

            Button btnUnlock = (Button)FindViewById(Resource.Id.QuickUnlock_button);

            btnUnlock.Click += (object sender, EventArgs e) =>
            {
                OnUnlock(_quickUnlockLength, pwd);
            };



            Button btnLock = (Button)FindViewById(Resource.Id.QuickUnlock_buttonLock);

            btnLock.Text   = btnLock.Text.Replace("ß", "ss");
            btnLock.Click += (object sender, EventArgs e) =>
            {
                App.Kp2a.LockDatabase(false);
                Finish();
            };
            pwd.EditorAction += (sender, args) =>
            {
                if ((args.ActionId == ImeAction.Done) || ((args.ActionId == ImeAction.ImeNull) && (args.Event.Action == KeyEventActions.Down)))
                {
                    OnUnlock(_quickUnlockLength, pwd);
                }
            };

            _intentReceiver = new QuickUnlockBroadcastReceiver(this);
            IntentFilter filter = new IntentFilter();

            filter.AddAction(Intents.DatabaseLocked);
            RegisterReceiver(_intentReceiver, filter);

            if ((int)Build.VERSION.SdkInt >= 23)
            {
                Kp2aLog.Log("requesting fingerprint permission");
                RequestPermissions(new[] { Manifest.Permission.UseFingerprint }, FingerprintPermissionRequestCode);
            }
            else
            {
            }
        }
Example #37
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == KeePass.ResultOkPasswordGenerator)
            {
                String generatedPassword = data.GetStringExtra("keepass2android.password.generated_password");
                FindViewById <TextView>(Resource.Id.entry_password).Text     = generatedPassword;
                FindViewById <TextView>(Resource.Id.entry_confpassword).Text = generatedPassword;
            }

            FileSelectHelper fileSelectHelper = new FileSelectHelper(this, true, true, RequestCodeDbFilename)
            {
                DefaultExtension = "kdbx"
            };

            fileSelectHelper.OnOpen += (sender, info) =>
            {
                _ioc = info;
                (sender as CreateDatabaseActivity ?? this).UpdateIocView();
            };

            if (fileSelectHelper.HandleActivityResult(this, requestCode, resultCode, data))
            {
                return;
            }


            if (resultCode == Result.Ok)
            {
                if (requestCode == RequestCodeKeyFile)
                {
                    if (data.Data.Scheme == "content")
                    {
                        if ((int)Build.VERSION.SdkInt >= 19)
                        {
                            //try to take persistable permissions
                            try
                            {
                                Kp2aLog.Log("TakePersistableUriPermission");
                                var takeFlags = data.Flags
                                                & (ActivityFlags.GrantReadUriPermission
                                                   | ActivityFlags.GrantWriteUriPermission);
                                this.ContentResolver.TakePersistableUriPermission(data.Data, takeFlags);
                            }
                            catch (Exception e)
                            {
                                Kp2aLog.Log(e.ToString());
                            }
                        }
                    }


                    string filename = Util.IntentToFilename(data, this);
                    if (filename == null)
                    {
                        filename = data.DataString;
                    }


                    _keyfileFilename = FileSelectHelper.ConvertFilenameToIocPath(filename);
                    FindViewById <TextView>(Resource.Id.keyfile_filename).Text = _keyfileFilename;
                    FindViewById(Resource.Id.keyfile_filename).Visibility      = ViewStates.Visible;
                }
            }
            if (resultCode == (Result)FileStorageResults.FileUsagePrepared)
            {
                _ioc = new IOConnectionInfo();
                Util.SetIoConnectionFromIntent(_ioc, data);
                UpdateIocView();
            }
            if (resultCode == (Result)FileStorageResults.FileChooserPrepared)
            {
                IOConnectionInfo ioc = new IOConnectionInfo();
                Util.SetIoConnectionFromIntent(ioc, data);

                new FileSelectHelper(this, true, true, RequestCodeDbFilename)
                {
                    DefaultExtension = "kdbx"
                }
                .StartFileChooser(ioc.Path);
            }
        }
        private static void ImportIntoCurrentDatabase(EcasAction a, EcasContext ctx)
        {
            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);

            if (string.IsNullOrEmpty(strPath))
            {
                return;
            }
            IOConnectionInfo ioc = IOConnectionInfo.FromPath(strPath);

            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

            if (string.IsNullOrEmpty(strFormat))
            {
                return;
            }
            FileFormatProvider ff = Program.FileFormatPool.Find(strFormat);

            if (ff == null)
            {
                throw new Exception(KPRes.Unknown + ": " + strFormat);
            }

            uint          uMethod = EcasUtil.GetParamUInt(a.Parameters, 2);
            Type          tMM     = Enum.GetUnderlyingType(typeof(PwMergeMethod));
            object        oMethod = Convert.ChangeType(uMethod, tMM);
            PwMergeMethod mm      = PwMergeMethod.None;

            if (Enum.IsDefined(typeof(PwMergeMethod), oMethod))
            {
                mm = (PwMergeMethod)oMethod;
            }
            else
            {
                Debug.Assert(false);
            }
            if (mm == PwMergeMethod.None)
            {
                mm = PwMergeMethod.CreateNewUuids;
            }

            CompositeKey cmpKey = KeyFromParams(a, 3, 4, 5);

            if ((cmpKey == null) && ff.RequiresKey)
            {
                KeyPromptForm kpf = new KeyPromptForm();
                kpf.InitEx(ioc, false, true);

                if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                {
                    return;
                }

                cmpKey = kpf.CompositeKey;
                UIUtil.DestroyForm(kpf);
            }

            bool?b = true;

            try { b = ImportUtil.Import(pd, ff, ioc, mm, cmpKey); }
            finally
            {
                if (b.GetValueOrDefault(false))
                {
                    Program.MainForm.UpdateUI(false, null, true, null, true, null, true);
                }
            }
        }
        private static void ExportDatabaseFile(EcasAction a, EcasContext ctx)
        {
            string strPath = EcasUtil.GetParamString(a.Parameters, 0, true);
            // if(string.IsNullOrEmpty(strPath)) return; // Allow no-file exports
            string strFormat = EcasUtil.GetParamString(a.Parameters, 1, true);

            if (string.IsNullOrEmpty(strFormat))
            {
                return;
            }
            string strGroup = EcasUtil.GetParamString(a.Parameters, 2, true);
            string strTag   = EcasUtil.GetParamString(a.Parameters, 3, true);

            PwDatabase pd = Program.MainForm.ActiveDatabase;

            if ((pd == null) || !pd.IsOpen)
            {
                return;
            }

            PwGroup pg = pd.RootGroup;

            if (!string.IsNullOrEmpty(strGroup))
            {
                char    chSep = strGroup[0];
                PwGroup pgSub = pg.FindCreateSubTree(strGroup.Substring(1),
                                                     new char[] { chSep }, false);
                pg = (pgSub ?? (new PwGroup(true, true, KPRes.Group, PwIcon.Folder)));
            }

            if (!string.IsNullOrEmpty(strTag))
            {
                // Do not use pg.Duplicate, because this method
                // creates new UUIDs
                pg = pg.CloneDeep();
                pg.TakeOwnership(true, true, true);

                GroupHandler gh = delegate(PwGroup pgSub)
                {
                    PwObjectList <PwEntry> l = pgSub.Entries;
                    long n = (long)l.UCount;
                    for (long i = n - 1; i >= 0; --i)
                    {
                        if (!l.GetAt((uint)i).HasTag(strTag))
                        {
                            l.RemoveAt((uint)i);
                        }
                    }

                    return(true);
                };

                gh(pg);
                pg.TraverseTree(TraversalMethod.PreOrder, gh, null);
            }

            PwExportInfo     pei = new PwExportInfo(pg, pd, true);
            IOConnectionInfo ioc = (!string.IsNullOrEmpty(strPath) ?
                                    IOConnectionInfo.FromPath(strPath) : null);

            ExportUtil.Export(pei, strFormat, ioc);
        }
Example #40
0
        /// <summary>
        /// Synchronizes the local database that <paramref name="host" /> has open with the database (if any) by the same name stored on the bucket that <paramref name="client" /> has access to.
        /// </summary>
        /// <param name="client">The <see cref="B2Client" /> created by <see cref="GetClient" /> with access to a bucket to synchronize with.</param>
        /// <param name="host">The <see cref="IPluginHost" /> that hosts the currently-running instance of <see cref="B2SyncExt" />.</param>
        /// <returns><see langword="true" /> if the synchronization was successful, or <see langword="false" /> otherwise.</returns>
        public static async Task <bool> SynchronizeDbAsync(B2Client client, IPluginHost host)
        {
            if (client == null)
            {
                return(false);
            }

            Synchronizing = true;

            Interface.UpdateStatus("Synchronizing database with B2...");

            //Download the remote copy
            PwDatabase sourceDb     = host.Database;
            string     remoteDbPath = await DownloadDbAsync(client, GetDbFileName(sourceDb));

            bool localMatchesRemote = true;

            //If the file exists on the remote server, synchronize it with the local copy
            if (remoteDbPath != null)
            {
                string localHash  = HashFileOnDisk(sourceDb.IOConnectionInfo.Path);
                string remoteHash = HashFileOnDisk(remoteDbPath);

                localMatchesRemote = localHash == remoteHash;

                if (!localMatchesRemote)
                {
                    IOConnectionInfo   connInfo  = IOConnectionInfo.FromPath(remoteDbPath);
                    FileFormatProvider formatter = host.FileFormatPool.Find("KeePass KDBX (2.x)");

                    bool?importResult = ImportUtil.Import(sourceDb, formatter, new[] { connInfo }, true, host.MainWindow,
                                                          false, host.MainWindow);

                    //Since the Import operation automatically adds it to the list of recent files, remove it from the list afterwards
                    host.MainWindow.FileMruList.RemoveItem(remoteDbPath);

                    //Remove the copy of the database from the temp location
                    File.Delete(remoteDbPath);

                    if (!importResult.GetValueOrDefault(false))
                    {
                        Interface.UpdateStatus("Something went wrong while synchronizing the local copy with the remote one.");
                        return(false);
                    }
                }
            }

            //Upload the local copy to the server once all synchronization is completed
            bool uploadResult = ((!localMatchesRemote || remoteDbPath == null) && await UploadDbAsync(client, sourceDb)) || localMatchesRemote;

            if (uploadResult)
            {
                if (!localMatchesRemote || remoteDbPath == null)
                {
                    Interface.UpdateStatus("Synchronized database with B2 successfully.");
                }
                else
                {
                    Interface.UpdateStatus(
                        "No synchronization was necessary. The database is in sync with the copy on B2.");
                }
            }
            else
            {
                Interface.UpdateStatus("Something went wrong while uploading to B2.");
            }

            Synchronizing = false;

            return(uploadResult);
        }
Example #41
0
 public KcpKeyFile(IOConnectionInfo iocKeyFile, bool bThrowIfDbFile)
 {
     Construct(iocKeyFile, bThrowIfDbFile);
 }
Example #42
0
        public bool HandleActivityResult(Activity activity, int requestCode, Result resultCode, Intent data)
        {
            if (requestCode != _requestCode)
            {
                return(false);
            }

            if (resultCode == KeePass.ExitFileStorageSelectionOk)
            {
                string protocolId = data.GetStringExtra("protocolId");
                if (protocolId == "content")
                {
                    Util.ShowBrowseDialog(activity, _requestCode, _isForSave, _tryGetPermanentAccess);
                }
                else
                {
                    App.Kp2a.GetFileStorage(protocolId).StartSelectFile(
                        new FileStorageSetupInitiatorActivity(activity, (i, result, arg3) => HandleActivityResult(activity, i, result, arg3), s => PerformManualFileSelect(s)),
                        _isForSave,
                        _requestCode,
                        protocolId);
                }
            }

            if (resultCode == Result.Ok)
            {
                if (data.Data.Scheme == "content")
                {
                    if ((int)Build.VERSION.SdkInt >= 19)
                    {
                        //try to take persistable permissions
                        try
                        {
                            Kp2aLog.Log("TakePersistableUriPermission");
                            var takeFlags = data.Flags
                                            & (ActivityFlags.GrantReadUriPermission
                                               | ActivityFlags.GrantWriteUriPermission);
                            activity.ContentResolver.TakePersistableUriPermission(data.Data, takeFlags);
                        }
                        catch (Exception e)
                        {
                            Kp2aLog.Log(e.ToString());
                        }
                    }
                }


                string filename = Util.IntentToFilename(data, activity);
                if (filename == null)
                {
                    filename = data.DataString;
                }

                bool fileExists = data.GetBooleanExtra("group.pals.android.lib.ui.filechooser.FileChooserActivity.result_file_exists", true);

                if (fileExists)
                {
                    var ioc = new IOConnectionInfo {
                        Path = ConvertFilenameToIocPath(filename)
                    };
                    IocSelected(activity, ioc);
                }
                else
                {
                    var task = new CreateNewFilename(activity, new ActionOnFinish(activity, (success, messageOrFilename, newActivity) =>
                    {
                        if (!success)
                        {
                            Toast.MakeText(newActivity, messageOrFilename, ToastLength.Long).Show();
                            return;
                        }
                        var ioc = new IOConnectionInfo {
                            Path = ConvertFilenameToIocPath(messageOrFilename)
                        };
                        IocSelected(newActivity, ioc);
                    }), filename);

                    new ProgressTask(App.Kp2a, activity, task).Run();
                }
            }


            if (resultCode == (Result)FileStorageResults.FileUsagePrepared)
            {
                var ioc = new IOConnectionInfo();
                Util.SetIoConnectionFromIntent(ioc, data);
                IocSelected(null, ioc);
            }
            if (resultCode == (Result)FileStorageResults.FileChooserPrepared)
            {
                IOConnectionInfo ioc = new IOConnectionInfo();
                Util.SetIoConnectionFromIntent(ioc, data);
                StartFileChooser(ioc.Path);
            }
            return(true);
        }
Example #43
0
 public KcpKeyFile(string strKeyFile, bool bThrowIfDbFile)
 {
     Construct(IOConnectionInfo.FromPath(strKeyFile), bThrowIfDbFile);
 }
Example #44
0
 private void AfterQueryCredentials(IOConnectionInfo ioc)
 {
     _ioc = ioc;
     UpdateIocView();
 }
 public void LoadDatabase(IOConnectionInfo ioConnectionInfo, MemoryStream memoryStream, CompositeKey compKey, ProgressDialogStatusLogger statusLogger, IDatabaseFormat databaseFormat)
 {
     _db.LoadData(this, ioConnectionInfo, memoryStream, compKey, statusLogger, databaseFormat);
 }
Example #46
0
 public LaunchGroupActivity(IOConnectionInfo ioc, CreateDatabaseActivity activity)
     : base(activity, null)
 {
     _activity = activity;
     _ioc      = ioc;
 }
Example #47
0
 public bool HasLocalChanges(IOConnectionInfo ioc)
 {
     return(IsCached(ioc) &&
            GetLocalVersionHash(ioc) != GetBaseVersionHash(ioc));
 }
Example #48
0
        protected override void OnCreate(Bundle bundle)
        {
            _design.ApplyTheme();
            base.OnCreate(bundle);


            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);

            SetContentView(Resource.Layout.create_database);
            _appTask = AppTask.GetTaskInOnCreate(bundle, Intent);

            SetDefaultIoc();

            FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Gone;


            var keyfileCheckbox = FindViewById <CheckBox>(Resource.Id.use_keyfile);

            if (bundle != null)
            {
                _keyfileFilename = bundle.GetString(KeyfilefilenameBundleKey, null);
                if (_keyfileFilename != null)
                {
                    FindViewById <TextView>(Resource.Id.keyfile_filename).Text = FileSelectHelper.ConvertFilenameToIocPath(_keyfileFilename);
                    FindViewById(Resource.Id.keyfile_filename).Visibility      = ViewStates.Visible;
                    keyfileCheckbox.Checked = true;
                }

                if (bundle.GetString(Util.KeyFilename, null) != null)
                {
                    _ioc = new IOConnectionInfo
                    {
                        Path         = bundle.GetString(Util.KeyFilename),
                        UserName     = bundle.GetString(Util.KeyServerusername),
                        Password     = bundle.GetString(Util.KeyServerpassword),
                        CredSaveMode = (IOCredSaveMode)bundle.GetInt(Util.KeyServercredmode),
                    };
                }
            }

            UpdateIocView();

            keyfileCheckbox.CheckedChange += (sender, args) =>
            {
                if (keyfileCheckbox.Checked)
                {
                    if (_restoringInstanceState)
                    {
                        return;
                    }

                    Util.ShowBrowseDialog(this, RequestCodeKeyFile, false, true);
                }
                else
                {
                    FindViewById(Resource.Id.keyfile_filename).Visibility = ViewStates.Gone;
                    _keyfileFilename = null;
                }
            };


            FindViewById(Resource.Id.btn_change_location).Click += (sender, args) =>
            {
                Intent intent = new Intent(this, typeof(FileStorageSelectionActivity));
                StartActivityForResult(intent, RequestCodeDbFilename);
            };

            Button generatePassword = (Button)FindViewById(Resource.Id.generate_button);

            generatePassword.Click += (sender, e) =>
            {
                GeneratePasswordActivity.LaunchWithoutLockCheck(this);
            };

            FindViewById(Resource.Id.btn_create).Click += (sender, evt) =>
            {
                CreateDatabase(Intent.GetBooleanExtra("MakeCurrent", true));
            };

            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);

            btnTogglePassword.Click += (sender, e) =>
            {
                _showPassword = !_showPassword;
                MakePasswordMaskedOrVisible();
            };
            Android.Graphics.PorterDuff.Mode mMode = Android.Graphics.PorterDuff.Mode.SrcAtop;
            Android.Graphics.Color           color = new Android.Graphics.Color(224, 224, 224);
            btnTogglePassword.SetColorFilter(color, mMode);
        }
Example #49
0
        private bool TryGetCachedFilePath(IOConnectionInfo folderPath, string filename, out IOConnectionInfo res)
        {
            res = folderPath.CloneDeep();
            string filePathCache = CachedFilePath(GetPseudoIoc(folderPath, filename)) + ".filepath";

            if (!File.Exists(filePathCache))
            {
                return(false);
            }
            res.Path = File.ReadAllText(filePathCache);
            return(true);
        }
Example #50
0
 public void InitEx(IOConnectionInfo ioInfo, bool bCanExit,
                    bool bRedirectActivation)
 {
     InitEx(ioInfo, bCanExit, bRedirectActivation, null);
 }
Example #51
0
 public bool IsReadOnly(IOConnectionInfo ioc, OptionalOut <UiStringKey> reason = null)
 {
     //even though the cache can always be written, the changes made in the cache could not be transferred to the cached file
     //so we better treat the cache as read-only as well.
     return(_cachedStorage.IsReadOnly(ioc, reason));
 }
Example #52
0
 public static bool CanEditIoc(IOConnectionInfo ioc)
 {
     return(ioc.Path.StartsWith("http") ||
            ioc.Path.StartsWith("ftp") ||
            ioc.Path.StartsWith("sftp"));
 }
Example #53
0
 public IOConnectionInfo GetParentPath(IOConnectionInfo ioc)
 {
     return(_cachedStorage.GetParentPath(ioc));
 }
Example #54
0
        private bool OnOpenButton(string filename, Dialog dialog)
        {
            IOConnectionInfo ioc = new IOConnectionInfo
            {
                Path = filename
            };

            // Make sure file name exists
            if (filename.Length == 0)
            {
                Toast.MakeText(_activity,
                               Resource.String.error_filename_required,
                               ToastLength.Long).Show();
                return(false);
            }


            int lastSlashPos = filename.LastIndexOf('/');
            int lastDotPos   = filename.LastIndexOf('.');

            if (lastSlashPos >= lastDotPos)             //no dot after last slash or == in case neither / nor .
            {
                ShowFilenameWarning(filename, () => { IocSelected(null, ioc); dialog.Dismiss(); }, () => { /* don't do anything, leave dialog open, let user try again*/ });
                //signal that the dialog should be kept open
                return(false);
            }

            IFileStorage fileStorage;

            try
            {
                fileStorage = App.Kp2a.GetFileStorage(ioc);
            }
            catch (NoFileStorageFoundException)
            {
                Toast.MakeText(_activity,
                               "Unexpected scheme in " + filename,
                               ToastLength.Long).Show();
                return(false);
            }

            if (_isForSave && ioc.IsLocalFile())
            {
                // Try to create the file
                File file = new File(filename);
                try
                {
                    File parent = file.ParentFile;

                    if (parent == null || (parent.Exists() && !parent.IsDirectory))
                    {
                        Toast.MakeText(_activity,
                                       Resource.String.error_invalid_path,
                                       ToastLength.Long).Show();
                        return(false);
                    }

                    if (!parent.Exists())
                    {
                        // Create parent dircetory
                        if (!parent.Mkdirs())
                        {
                            Toast.MakeText(_activity,
                                           Resource.String.error_could_not_create_parent,
                                           ToastLength.Long).Show();
                            return(false);
                        }
                    }
                    System.IO.File.Create(filename).Dispose();
                }
                catch (IOException ex)
                {
                    Toast.MakeText(
                        _activity,
                        _activity.GetText(Resource.String.error_file_not_create) + " "
                        + ex.LocalizedMessage,
                        ToastLength.Long).Show();
                    return(false);
                }
            }
            if (fileStorage.RequiresCredentials(ioc))
            {
                Util.QueryCredentials(ioc, iocResult => IocSelected(null, iocResult), _activity);
            }
            else
            {
                IocSelected(null, ioc);
            }

            return(true);
        }
Example #55
0
 public void PrepareFileUsage(Context ctx, IOConnectionInfo ioc)
 {
     _cachedStorage.PrepareFileUsage(ctx, ioc);
 }
 public SyncOtpAuxFile(IOConnectionInfo ioc)
     : base(null)
 {
     _ioc = ioc;
 }
Example #57
0
 public void PrepareFileUsage(IFileStorageSetupInitiatorActivity activity, IOConnectionInfo ioc, int requestCode, bool alwaysReturnSuccess)
 {
     //we try to prepare the file usage by the underlying file storage but if the ioc is cached, set the flag to ignore errors
     _cachedStorage.PrepareFileUsage(activity, ioc, requestCode, alwaysReturnSuccess || IsCached(ioc));
 }
 public void StoreOpenedFileAsRecent(IOConnectionInfo ioc, string keyfile)
 {
 }
Example #59
0
 public KcpKeyFile(IOConnectionInfo iocKeyFile)
 {
     Construct(iocKeyFile, false);
 }
Example #60
0
 public KcpKeyFile(string strKeyFile)
 {
     Construct(IOConnectionInfo.FromPath(strKeyFile), false);
 }