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 <fabian@henneke.me>
Co-authored-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Diogenes Molinares 2020-04-16 13:51:24 +02:00 committed by GitHub
parent e4aa673537
commit f269bc7d28
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 46 additions and 18 deletions

View file

@ -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 -> {

View file

@ -76,7 +76,6 @@
<string name="pref_show_time_title">مدة الإبقاء على كلمة السر ظاهرة</string>
<string name="pref_copy_title">نسخ كلمة السر تلقائيًا</string>
<string name="ssh_key_success_dialog_title">تم استيراد مفتاح الـ SSH</string>
<string name="ssh_key_error_dialog_title">حدث هناك خطأ أثناء عملية إسترجاع مفتاح الـ SSH</string>
<string name="ssh_key_error_dialog_text">نص الرسالة : \n</string>
<string name="pref_autofill_title">الملئ التلقائي</string>
<string name="pref_autofill_enable_title">تشغيل الملئ التلقائي</string>

View file

@ -119,7 +119,6 @@
<string name="pref_copy_title">Automaticky kopírovat heslo</string>
<string name="pref_copy_dialog_title">Automatické kopírování hesla do schránky po úspěšném dešifrování.</string>
<string name="ssh_key_success_dialog_title">SSH-key importován</string>
<string name="ssh_key_error_dialog_title">Chyba při importu SSH klíče</string>
<string name="ssh_key_error_dialog_text">Zpráva : \n</string>
<string name="pref_recursive_filter">Rekurzivní filtrování</string>
<string name="pref_recursive_filter_hint">Rekurzivní hledání hesel v aktuálním adresáři.</string>

View file

@ -94,7 +94,6 @@
<string name="pref_copy_title">Kopiere Passwort automatisch</string>
<string name="pref_copy_dialog_title">Kopiert das Passwort in die Zwischenablage, wenn der Eintrag entschlüsselt wurde.</string>
<string name="ssh_key_success_dialog_title">SSH-Key importiert</string>
<string name="ssh_key_error_dialog_title">Fehler während des Imports des SSH-Keys</string>
<string name="ssh_key_error_dialog_text">Nachricht : \n</string>
<string name="pref_recursive_filter">Suche in Unterordnern</string>
<string name="pref_recursive_filter_hint">Findet Passwörter auch in Unterordnern.</string>

View file

@ -120,7 +120,6 @@
<string name="pref_copy_title">Copiar contraseña automáticamente</string>
<string name="pref_copy_dialog_title">Automáticamente copia la contraseña al portapapeles si el descifrado fue exitoso.</string>
<string name="ssh_key_success_dialog_title">Llave SSH importada</string>
<string name="ssh_key_error_dialog_title">Error al intentar importar llave SSH</string>
<string name="ssh_key_error_dialog_text">Mensaje: \n</string>
<string name="pref_recursive_filter">Búsqueda recursiva</string>
<string name="pref_recursive_filter_hint">Busca contraseñas recursivamente en el directorio actual.</string>

View file

@ -128,7 +128,6 @@
<string name="pref_copy_title">Copie automatique du mot de passe</string>
<string name="pref_copy_dialog_title">Copie automatiquement le mot de passe vers le presse-papier si le déchiffrement a réussi.</string>
<string name="ssh_key_success_dialog_title">Clef SSH importée</string>
<string name="ssh_key_error_dialog_title">Erreur lors de l\'importation du la clef ssh</string>
<string name="ssh_key_error_dialog_text">Message : \n</string>
<string name="pref_recursive_filter">Filtre récursif</string>
<string name="pref_recursive_filter_hint">Cherche le mot de passe dans tous les sous-répertoires du répertoire actuel.</string>

View file

@ -80,7 +80,6 @@
<string name="pref_copy_title">自動的にパスワードをコピー</string>
<string name="pref_copy_dialog_title">復号化が成功した後、自動的にパスワードをクリップボードにコピーします。</string>
<string name="ssh_key_success_dialog_title">SSH 鍵をインポートしました</string>
<string name="ssh_key_error_dialog_title">ssh 鍵のインポート時にエラー</string>
<string name="ssh_key_error_dialog_text">メッセージ : \n</string>
<string name="pref_recursive_filter">再帰的フィルタリング</string>
<string name="pref_recursive_filter_hint">現在のディレクトリーのパスワードを再帰的に検索します。</string>

View file

@ -134,7 +134,6 @@
<string name="pref_copy_title">Автоматически копировать пароль</string>
<string name="pref_copy_dialog_title">Автоматически копировать пароль в буфер обмена после успешного расшифрования</string>
<string name="ssh_key_success_dialog_title">SSH ключ импортирован</string>
<string name="ssh_key_error_dialog_title">Ошибка импорта SSH ключа</string>
<string name="ssh_key_error_dialog_text">Сообщение: \n</string>
<string name="pref_recursive_filter">Рекурсивная фильтрация</string>
<string name="pref_recursive_filter_hint">Рекурсивный поиск паролей в текущей директории</string>

View file

@ -80,7 +80,6 @@
<string name="pref_copy_title">自动复制密码</string>
<string name="pref_copy_dialog_title">解密成功后自动将密码复制到剪贴板</string>
<string name="ssh_key_success_dialog_title">成功导入SSH密钥</string>
<string name="ssh_key_error_dialog_title">尝试导入SSH密钥时出错</string>
<string name="ssh_key_error_dialog_text">信息:</string>
<string name="pref_recursive_filter">搜索子文件夹</string>
<string name="pref_recursive_filter_hint">在当前目录的子目录中查找密码</string>

View file

@ -77,7 +77,6 @@
<string name="pref_copy_title">自動複製密碼</string>
<string name="pref_copy_dialog_title">解密成功後自動將密碼複製到剪貼簿</string>
<string name="ssh_key_success_dialog_title">成功匯入 SSH 金鑰</string>
<string name="ssh_key_error_dialog_title">嘗試匯入 SSH 金鑰時出錯</string>
<string name="ssh_key_error_dialog_text">訊息:</string>
<string name="pref_recursive_filter">搜尋子資料夾</string>
<string name="pref_recursive_filter_hint">在目前目錄的子目錄中查詢密碼</string>

View file

@ -149,7 +149,7 @@
<string name="pref_copy_title">Automatically copy password</string>
<string name="pref_copy_dialog_title">Automatically copy the password to the clipboard after decryption was successful.</string>
<string name="ssh_key_success_dialog_title">SSH-key imported</string>
<string name="ssh_key_error_dialog_title">Error while trying to import the ssh-key</string>
<string name="ssh_key_error_dialog_title">Key import error</string>
<string name="ssh_key_error_dialog_text">Message : \n</string>
<string name="pref_recursive_filter">Recursive filtering</string>
<string name="pref_recursive_filter_hint">Recursively find passwords of the current directory.</string>
@ -348,4 +348,5 @@
<string name="theme_dark">Dark</string>
<string name="theme_battery_saver">Set by Battery Saver</string>
<string name="theme_follow_system">System default</string>
<string name="ssh_key_import_error_not_an_ssh_key_message">Selected file does not appear to be an SSH key</string>
</resources>