From f269bc7d28f43743648a346288749f5b7f878402 Mon Sep 17 00:00:00 2001 From: Diogenes Molinares Date: Thu, 16 Apr 2020 13:51:24 +0200 Subject: [PATCH] See file's metadata to validate SSH key (#709) * See file's metadata to validate SSH key * See file's metadata to validate SSH key * change exception to throw and refactoring * catch IOException and IllegalArgumentException as equal * run ./gradlew spotlessApply * Apply suggestions from code review * validate BEGIN, END markers and size != 0 * Apply suggestions from code review * Update app/src/main/java/com/zeapo/pwdstore/UserPreference.kt * Don't throw on SSH key import failure * Style nits * Codestyle and copy nits Co-authored-by: Fabian Henneke Co-authored-by: Harsh Shandilya --- .../java/com/zeapo/pwdstore/UserPreference.kt | 52 ++++++++++++++++--- app/src/main/res/values-ar/strings.xml | 1 - app/src/main/res/values-cs/strings.xml | 1 - app/src/main/res/values-de/strings.xml | 1 - app/src/main/res/values-es/strings.xml | 1 - app/src/main/res/values-fr/strings.xml | 1 - app/src/main/res/values-ja/strings.xml | 1 - app/src/main/res/values-ru/strings.xml | 1 - app/src/main/res/values-zh-rCN/strings.xml | 1 - app/src/main/res/values-zh-rTW/strings.xml | 1 - app/src/main/res/values/strings.xml | 3 +- 11 files changed, 46 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt b/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt index 9dd8f4187..4590e6788 100644 --- a/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt +++ b/app/src/main/java/com/zeapo/pwdstore/UserPreference.kt @@ -14,6 +14,7 @@ import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.DocumentsContract +import android.provider.OpenableColumns import android.provider.Settings import android.text.TextUtils import android.view.MenuItem @@ -519,9 +520,32 @@ class UserPreference : AppCompatActivity() { startActivityForResult(intent, SET_CUSTOM_XKPWD_DICT) } - @Throws(IOException::class) + @Throws(IllegalArgumentException::class, IOException::class) private fun copySshKey(uri: Uri) { - // TODO: Check if valid SSH Key before import + // See metadata from document to validate SSH key + contentResolver.query(uri, null, null, null, null, null)?.use { cursor -> + val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE) + // cursor returns only 1 row + cursor.moveToFirst() + // see file's metadata + val fileSize = cursor.getInt(sizeIndex) + // We assume that an SSH key's ideal size is > 0 bytes && < 100 kilobytes. + if (fileSize > 100000 || fileSize == 0) { + throw IllegalArgumentException("Wrong file type selected") + } else { + // Validate BEGIN and END markers + val lines = contentResolver.openInputStream(uri)?.bufferedReader()?.readLines() + // The file must have more than 2 lines, and the first and last line must have + // OpenSSH key markers. + if (lines != null && + lines.size > 2 && + !lines[0].contains("BEGIN OPENSSH PRIVATE KEY") && + !lines[lines.size - 1].contains("END OPENSSH PRIVATE KEY")) { + throw IllegalArgumentException("Wrong file type selected") + } + } + } + val sshKeyInputStream = contentResolver.openInputStream(uri) if (sshKeyInputStream != null) { @@ -597,12 +621,24 @@ class UserPreference : AppCompatActivity() { setResult(Activity.RESULT_OK) finish() - } catch (e: IOException) { - MaterialAlertDialogBuilder(this) - .setTitle(this.resources.getString(R.string.ssh_key_error_dialog_title)) - .setMessage(this.resources.getString(R.string.ssh_key_error_dialog_text) + e.message) - .setPositiveButton(this.resources.getString(R.string.dialog_ok), null) - .show() + } catch (e: Exception) { + when (e) { + is IOException, + is IllegalArgumentException -> { + MaterialAlertDialogBuilder(this) + .setTitle(resources.getString(R.string.ssh_key_error_dialog_title)) + .setMessage(getString(R.string.ssh_key_import_error_not_an_ssh_key_message)) + .setPositiveButton(resources.getString(R.string.dialog_ok), null) + .show() + } + else -> { + MaterialAlertDialogBuilder(this) + .setTitle(resources.getString(R.string.ssh_key_error_dialog_title)) + .setMessage(resources.getString(R.string.ssh_key_error_dialog_text) + e.message) + .setPositiveButton(resources.getString(R.string.dialog_ok), null) + .show() + } + } } } EDIT_GIT_INFO -> { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 6a337f9b7..7720784bc 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -76,7 +76,6 @@ مدة الإبقاء على كلمة السر ظاهرة نسخ كلمة السر تلقائيًا تم استيراد مفتاح الـ SSH - حدث هناك خطأ أثناء عملية إسترجاع مفتاح الـ SSH نص الرسالة : \n الملئ التلقائي تشغيل الملئ التلقائي diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 217c127dd..86985f8f9 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -119,7 +119,6 @@ Automaticky kopírovat heslo Automatické kopírování hesla do schránky po úspěšném dešifrování. SSH-key importován - Chyba při importu SSH klíče Zpráva : \n Rekurzivní filtrování Rekurzivní hledání hesel v aktuálním adresáři. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index d9ba48b5f..4960387f8 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -94,7 +94,6 @@ Kopiere Passwort automatisch Kopiert das Passwort in die Zwischenablage, wenn der Eintrag entschlüsselt wurde. SSH-Key importiert - Fehler während des Imports des SSH-Keys Nachricht : \n Suche in Unterordnern Findet Passwörter auch in Unterordnern. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 8687bac84..47ec808d0 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -120,7 +120,6 @@ Copiar contraseña automáticamente Automáticamente copia la contraseña al portapapeles si el descifrado fue exitoso. Llave SSH importada - Error al intentar importar llave SSH Mensaje: \n Búsqueda recursiva Busca contraseñas recursivamente en el directorio actual. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 9edf7d667..0f4c2025a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -128,7 +128,6 @@ Copie automatique du mot de passe Copie automatiquement le mot de passe vers le presse-papier si le déchiffrement a réussi. Clef SSH importée - Erreur lors de l\'importation du la clef ssh Message : \n Filtre récursif Cherche le mot de passe dans tous les sous-répertoires du répertoire actuel. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 0c3474806..c798f6c21 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -80,7 +80,6 @@ 自動的にパスワードをコピー 復号化が成功した後、自動的にパスワードをクリップボードにコピーします。 SSH 鍵をインポートしました - ssh 鍵のインポート時にエラー メッセージ : \n 再帰的フィルタリング 現在のディレクトリーのパスワードを再帰的に検索します。 diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index cfbcedb27..bc73c5c2b 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -134,7 +134,6 @@ Автоматически копировать пароль Автоматически копировать пароль в буфер обмена после успешного расшифрования SSH ключ импортирован - Ошибка импорта SSH ключа Сообщение: \n Рекурсивная фильтрация Рекурсивный поиск паролей в текущей директории diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 9ba374121..019f703c8 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -80,7 +80,6 @@ 自动复制密码 解密成功后自动将密码复制到剪贴板 成功导入SSH密钥 - 尝试导入SSH密钥时出错 信息: 搜索子文件夹 在当前目录的子目录中查找密码 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index b7a88eac3..bdc6f1fb0 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -77,7 +77,6 @@ 自動複製密碼 解密成功後自動將密碼複製到剪貼簿 成功匯入 SSH 金鑰 - 嘗試匯入 SSH 金鑰時出錯 訊息: 搜尋子資料夾 在目前目錄的子目錄中查詢密碼 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f0ba9048d..0b9f908e5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -149,7 +149,7 @@ Automatically copy password Automatically copy the password to the clipboard after decryption was successful. SSH-key imported - Error while trying to import the ssh-key + Key import error Message : \n Recursive filtering Recursively find passwords of the current directory. @@ -348,4 +348,5 @@ Dark Set by Battery Saver System default + Selected file does not appear to be an SSH key