aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/dev/msfjarvis/aps/ui/autofill/AutofillDecryptActivity.kt
blob: bd3141a8b05cc9fcab2c830006ca585d8d218f8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
 * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved.
 * SPDX-License-Identifier: GPL-3.0-only
 */
package dev.msfjarvis.aps.ui.autofill

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import android.os.Build
import android.os.Bundle
import android.view.autofill.AutofillManager
import android.widget.Toast
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts.StartIntentSenderForResult
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.github.androidpasswordstore.autofillparser.AutofillAction
import com.github.androidpasswordstore.autofillparser.Credentials
import com.github.michaelbull.result.getOrElse
import com.github.michaelbull.result.onFailure
import com.github.michaelbull.result.onSuccess
import com.github.michaelbull.result.runCatching
import dagger.hilt.android.AndroidEntryPoint
import dev.msfjarvis.aps.data.passfile.PasswordEntry
import dev.msfjarvis.aps.util.autofill.AutofillPreferences
import dev.msfjarvis.aps.util.autofill.AutofillResponseBuilder
import dev.msfjarvis.aps.util.autofill.DirectoryStructure
import dev.msfjarvis.aps.util.extensions.OPENPGP_PROVIDER
import dev.msfjarvis.aps.util.extensions.asLog
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.io.OutputStream
import javax.inject.Inject
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import logcat.LogPriority.ERROR
import logcat.logcat
import me.msfjarvis.openpgpktx.util.OpenPgpApi
import me.msfjarvis.openpgpktx.util.OpenPgpServiceConnection
import org.openintents.openpgp.IOpenPgpService2
import org.openintents.openpgp.OpenPgpError

@RequiresApi(Build.VERSION_CODES.O)
@AndroidEntryPoint
class AutofillDecryptActivity : AppCompatActivity() {

  companion object {

    private const val EXTRA_FILE_PATH = "dev.msfjarvis.aps.autofill.oreo.EXTRA_FILE_PATH"
    private const val EXTRA_SEARCH_ACTION = "dev.msfjarvis.aps.autofill.oreo.EXTRA_SEARCH_ACTION"

    private var decryptFileRequestCode = 1

    fun makeDecryptFileIntent(file: File, forwardedExtras: Bundle, context: Context): Intent {
      return Intent(context, AutofillDecryptActivity::class.java).apply {
        putExtras(forwardedExtras)
        putExtra(EXTRA_SEARCH_ACTION, true)
        putExtra(EXTRA_FILE_PATH, file.absolutePath)
      }
    }

    fun makeDecryptFileIntentSender(file: File, context: Context): IntentSender {
      val intent =
        Intent(context, AutofillDecryptActivity::class.java).apply {
          putExtra(EXTRA_SEARCH_ACTION, false)
          putExtra(EXTRA_FILE_PATH, file.absolutePath)
        }
      return PendingIntent.getActivity(
          context,
          decryptFileRequestCode++,
          intent,
          if (Build.VERSION.SDK_INT >= 31) {
            PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE
          } else {
            PendingIntent.FLAG_CANCEL_CURRENT
          },
        )
        .intentSender
    }
  }

  @Inject lateinit var passwordEntryFactory: PasswordEntry.Factory

  private val decryptInteractionRequiredAction =
    registerForActivityResult(StartIntentSenderForResult()) { result ->
      if (continueAfterUserInteraction != null) {
        val data = result.data
        if (result.resultCode == RESULT_OK && data != null) {
          continueAfterUserInteraction?.resume(data)
        } else {
          continueAfterUserInteraction?.resumeWithException(
            Exception("OpenPgpApi ACTION_DECRYPT_VERIFY failed to continue after user interaction")
          )
        }
        continueAfterUserInteraction = null
      }
    }

  private var continueAfterUserInteraction: Continuation<Intent>? = null
  private lateinit var directoryStructure: DirectoryStructure

  override fun onStart() {
    super.onStart()
    val filePath =
      intent?.getStringExtra(EXTRA_FILE_PATH)
        ?: run {
          logcat(ERROR) { "AutofillDecryptActivity started without EXTRA_FILE_PATH" }
          finish()
          return
        }
    val clientState =
      intent?.getBundleExtra(AutofillManager.EXTRA_CLIENT_STATE)
        ?: run {
          logcat(ERROR) { "AutofillDecryptActivity started without EXTRA_CLIENT_STATE" }
          finish()
          return
        }
    val isSearchAction = intent?.getBooleanExtra(EXTRA_SEARCH_ACTION, true)!!
    val action = if (isSearchAction) AutofillAction.Search else AutofillAction.Match
    directoryStructure = AutofillPreferences.directoryStructure(this)
    logcat { action.toString() }
    lifecycleScope.launch {
      val credentials = decryptCredential(File(filePath))
      if (credentials == null) {
        setResult(RESULT_CANCELED)
      } else {
        val fillInDataset =
          AutofillResponseBuilder.makeFillInDataset(
            this@AutofillDecryptActivity,
            credentials,
            clientState,
            action
          )
        withContext(Dispatchers.Main) {
          setResult(
            RESULT_OK,
            Intent().apply { putExtra(AutofillManager.EXTRA_AUTHENTICATION_RESULT, fillInDataset) }
          )
        }
      }
      withContext(Dispatchers.Main) { finish() }
    }
  }

  private suspend fun executeOpenPgpApi(
    data: Intent,
    input: InputStream,
    output: OutputStream
  ): Intent {
    var openPgpServiceConnection: OpenPgpServiceConnection? = null
    val openPgpService =
      suspendCoroutine<IOpenPgpService2> { cont ->
        openPgpServiceConnection =
          OpenPgpServiceConnection(
              this,
              OPENPGP_PROVIDER,
              object : OpenPgpServiceConnection.OnBound {
                override fun onBound(service: IOpenPgpService2) {
                  cont.resume(service)
                }

                override fun onError(e: Exception) {
                  cont.resumeWithException(e)
                }
              }
            )
            .also { it.bindToService() }
      }
    return OpenPgpApi(this, openPgpService).executeApi(data, input, output).also {
      openPgpServiceConnection?.unbindFromService()
    }
  }

  private suspend fun decryptCredential(file: File, resumeIntent: Intent? = null): Credentials? {
    val command = resumeIntent ?: Intent().apply { action = OpenPgpApi.ACTION_DECRYPT_VERIFY }
    runCatching { file.inputStream() }
      .onFailure { e ->
        logcat(ERROR) { e.asLog("File to decrypt not found") }
        return null
      }
      .onSuccess { encryptedInput ->
        val decryptedOutput = ByteArrayOutputStream()
        runCatching { executeOpenPgpApi(command, encryptedInput, decryptedOutput) }
          .onFailure { e ->
            logcat(ERROR) { e.asLog("OpenPgpApi ACTION_DECRYPT_VERIFY failed") }
            return null
          }
          .onSuccess { result ->
            return when (val resultCode =
                result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)
            ) {
              OpenPgpApi.RESULT_CODE_SUCCESS -> {
                runCatching {
                    val entry =
                      withContext(Dispatchers.IO) {
                        @Suppress("BlockingMethodInNonBlockingContext")
                        passwordEntryFactory.create(decryptedOutput.toByteArray())
                      }
                    AutofillPreferences.credentialsFromStoreEntry(
                      this,
                      file,
                      entry,
                      directoryStructure
                    )
                  }
                  .getOrElse { e ->
                    logcat(ERROR) { e.asLog("Failed to parse password entry") }
                    return null
                  }
              }
              OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED -> {
                val pendingIntent: PendingIntent =
                  result.getParcelableExtra(OpenPgpApi.RESULT_INTENT)!!
                runCatching {
                    val intentToResume =
                      withContext(Dispatchers.Main) {
                        suspendCoroutine<Intent> { cont ->
                          continueAfterUserInteraction = cont
                          decryptInteractionRequiredAction.launch(
                            IntentSenderRequest.Builder(pendingIntent.intentSender).build()
                          )
                        }
                      }
                    decryptCredential(file, intentToResume)
                  }
                  .getOrElse { e ->
                    logcat(ERROR) {
                      e.asLog("OpenPgpApi ACTION_DECRYPT_VERIFY failed with user interaction")
                    }
                    return null
                  }
              }
              OpenPgpApi.RESULT_CODE_ERROR -> {
                val error = result.getParcelableExtra<OpenPgpError>(OpenPgpApi.RESULT_ERROR)
                if (error != null) {
                  withContext(Dispatchers.Main) {
                    Toast.makeText(
                        applicationContext,
                        "Error from OpenKeyChain: ${error.message}",
                        Toast.LENGTH_LONG
                      )
                      .show()
                  }
                  logcat(ERROR) {
                    "OpenPgpApi ACTION_DECRYPT_VERIFY failed (${error.errorId}): ${error.message}"
                  }
                }
                null
              }
              else -> {
                logcat(ERROR) { "Unrecognized OpenPgpApi result: $resultCode" }
                null
              }
            }
          }
      }
    return null
  }
}