File size: 17,471 Bytes
5bbfb59 | 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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | /*
* Copyright (C) 2014-2020 Arpit Khurana <arpitkh96@gmail.com>, Vishal Nehra <vishalmeham2@gmail.com>,
* Emmanuel Messulam<emmanuelbendavid@gmail.com>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.filesystem.ssh
import android.os.Build
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.os.Build.VERSION_CODES.P
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SSHClientFactory
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.SSH_URI_PREFIX
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.getConnection
import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.shutdown
import com.amaze.filemanager.filesystem.ftp.NetCopyClientUtils.encryptFtpPathAsNecessary
import com.amaze.filemanager.filesystem.ssh.test.TestUtils
import com.amaze.filemanager.shadows.ShadowMultiDex
import com.amaze.filemanager.test.ShadowPasswordUtil
import com.amaze.filemanager.utils.PasswordUtil
import com.amaze.filemanager.utils.Utils
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.common.KeyType
import net.schmizz.sshj.common.SecurityUtils
import net.schmizz.sshj.userauth.UserAuthException
import net.schmizz.sshj.userauth.keyprovider.KeyProvider
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.AdditionalMatchers.not
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.doNothing
import org.mockito.kotlin.doThrow
import org.mockito.kotlin.eq
import org.mockito.kotlin.never
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowSQLiteConnection
import java.io.IOException
import java.net.URLEncoder.encode
import java.security.KeyPair
import java.security.PrivateKey
import kotlin.text.Charsets.UTF_8
/**
* Tests for [NetCopyClientConnectionPool] with SSH connections.
*/
@Suppress("LargeClass", "StringLiteralDuplication")
@RunWith(AndroidJUnit4::class)
@Config(
shadows = [ShadowMultiDex::class, ShadowPasswordUtil::class],
sdk = [LOLLIPOP, P, Build.VERSION_CODES.R],
)
class NetCopyClientConnectionPoolSshTest {
/**
* Post test cleanup.
*/
@After
fun tearDown() {
shutdown()
ShadowSQLiteConnection.reset()
}
/**
* Test getting connections with username and password.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUsernameAndPassword() {
val mock = createSshServer("testuser", "testpassword")
assertNotNull(
getConnection(
SSH_URI_PREFIX,
HOST,
PORT,
SecurityUtils.getFingerprint(hostKeyPair.public),
"testuser",
PasswordUtil.encryptPassword(
AppConfig.getInstance(),
"testpassword",
),
null,
),
)
assertNull(
getConnection(
SSH_URI_PREFIX,
HOST,
PORT,
SecurityUtils.getFingerprint(hostKeyPair.public),
"invaliduser",
PasswordUtil.encryptPassword(
AppConfig.getInstance(),
"invalidpassword",
),
null,
),
)
verify(mock, times(2))
.addHostKeyVerifier(
SecurityUtils.getFingerprint(
hostKeyPair.public,
),
)
verify(mock, times(2)).connect(HOST, PORT)
verify(mock).authPassword("testuser", "testpassword")
verify(mock).authPassword("invaliduser", "invalidpassword")
}
/**
* Test getting connections with username and key authentication.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUsernameAndKey() {
val mock = createSshServer("testuser", null)
assertNotNull(
getConnection(
SSH_URI_PREFIX,
HOST,
PORT,
SecurityUtils.getFingerprint(hostKeyPair.public),
"testuser",
null,
userKeyPair,
),
)
shutdown()
assertNull(
getConnection(
SSH_URI_PREFIX,
HOST,
PORT,
SecurityUtils.getFingerprint(hostKeyPair.public),
"invaliduser",
null,
userKeyPair,
),
)
verify(mock, times(2))
.addHostKeyVerifier(
SecurityUtils.getFingerprint(
hostKeyPair.public,
),
)
verify(mock, times(2)).connect(HOST, PORT)
verify(mock).authPublickey("testuser", sshKeyProvider)
verify(mock).authPublickey("invaliduser", sshKeyProvider)
}
/**
* Test getting connection with an URL/URI.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrl() {
val validUsername = "testuser"
val validPassword = "testpassword"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL(URI) having path to directory. It should return the same
* connection without path to directory.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingSubpath() {
val validUsername = "testuser"
val validPassword = "testpassword"
doRunTest(validUsername, validPassword, "/home/testuser")
}
/**
* Test getting connection with URL/URI using key authentication.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlAndKeyAuth() {
doRunTest(validUsername = "testuser", validPrivateKey = userKeyPair.private)
}
/**
* Test getting connection with URL/URI using key authentication having complex username.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlAndKeyAuthHavingComplexUsername() {
doRunTest(validUsername = "test@example.com", validPrivateKey = userKeyPair.private)
}
/**
* Test getting connection with URL(URI) having path to directory using key authentication.
* It should return the same connection without path to directory.
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlAndKeyAuthHavingSubpath() {
doRunTest("testuser", userKeyPair.private, "/home/testuser")
}
/**
* Test getting connection with URL/URI having complex password (case 1)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingComplexPassword1() {
val validUsername = "testuser"
val validPassword = "testP@ssw0rd"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having complex passwords (case 2)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingComplexPassword2() {
val validUsername = "testuser"
val validPassword = "testP@##word"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having complex credentials (case 1)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingComplexCredential1() {
val validUsername = "test@example.com"
val validPassword = "testP@ssw0rd"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having complex credentials (case 2)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingComplexCredential2() {
val validUsername = "test@example.com"
val validPassword = "testP@ssw0##$"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having minus sign in password (case 1)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingMinusSignInPassword1() {
val validUsername = "test@example.com"
val validPassword = "abcd-efgh"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having minus sign in password (case 2)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingMinusSignInPassword2() {
val validUsername = "test@example.com"
val validPassword = "---------------"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having minus sign in password (case 3)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingMinusSignInPassword3() {
val validUsername = "test@example.com"
val validPassword = "--agdiuhdpost15"
doRunTest(validUsername, validPassword)
}
/**
* Test getting connection with URL/URI having minus sign in password (case 4)
*/
@Test
@Throws(IOException::class)
fun testGetConnectionWithUrlHavingMinusSignInPassword4() {
val validUsername = "test@example.com"
val validPassword = "t-h-i-s-i-s-p-a-s-s-w-o-r-d-"
doRunTest(validUsername, validPassword)
}
private fun doRunTest(
validUsername: String,
validPassword: String,
subPath: String? = null,
) {
val encodedUsername = encode(validUsername, UTF_8.name())
val encodedPassword = encode(validPassword, UTF_8.name())
val encryptedPassword =
PasswordUtil.encryptPassword(
AppConfig.getInstance(),
encodedPassword,
)?.replace("\n", "")
val mock = createSshServer(validUsername, validPassword)
TestUtils.saveSshConnectionSettings(
hostKeyPair,
encodedUsername,
encryptedPassword,
null,
subPath,
)
assertNotNull(
getConnection<SSHClient>(
if (subPath.isNullOrEmpty()) {
"ssh://$encodedUsername:$encryptedPassword@$HOST:$PORT"
} else {
"ssh://$encodedUsername:$encryptedPassword@$HOST:$PORT$subPath"
},
),
)
assertNull(
getConnection<SSHClient>(
encryptFtpPathAsNecessary(
if (subPath.isNullOrEmpty()) {
"ssh://$encodedInvalidUsername:$encodedInvalidPassword@$HOST:$PORT"
} else {
"ssh://$encodedInvalidUsername:$encodedInvalidPassword@$HOST:$PORT$subPath"
},
),
),
)
verify(mock, atLeastOnce())
.addHostKeyVerifier(
SecurityUtils.getFingerprint(
hostKeyPair.public,
),
)
verify(mock, atLeastOnce()).connectTimeout =
NetCopyClientConnectionPool.CONNECT_TIMEOUT
verify(mock, atLeastOnce()).connect(HOST, PORT)
verify(mock).authPassword(validUsername, validPassword)
// invalid username won't give host key. Should never called this
verify(mock, never()).authPassword(invalidUsername, invalidPassword)
}
private fun doRunTest(
validUsername: String,
validPrivateKey: PrivateKey = userKeyPair.private,
subPath: String? = null,
) {
val encodedUsername = encode(validUsername, UTF_8.name())
val mock = createSshServer(validUsername, null)
TestUtils.saveSshConnectionSettings(
hostKeyPair,
encodedUsername,
null,
validPrivateKey,
subPath,
)
assertNotNull(
getConnection<SSHClient>(
if (subPath.isNullOrEmpty()) {
"ssh://$encodedUsername@$HOST:$PORT"
} else {
"ssh://$encodedUsername@$HOST:$PORT$subPath"
},
),
)
assertNull(
getConnection<SSHClient>(
if (subPath.isNullOrEmpty()) {
"ssh://$encodedInvalidUsername@$HOST:$PORT"
} else {
"ssh://$encodedInvalidUsername@$HOST:$PORT$subPath"
},
),
)
verify(mock, atLeastOnce())
.addHostKeyVerifier(
SecurityUtils.getFingerprint(
hostKeyPair.public,
),
)
verify(mock, atLeastOnce()).connectTimeout =
NetCopyClientConnectionPool.CONNECT_TIMEOUT
verify(mock, atLeastOnce()).connect(HOST, PORT)
verify(mock).authPublickey(validUsername, sshKeyProvider)
// invalid username won't give host key. Should never called this
verify(mock, never()).authPublickey(invalidPassword, sshKeyProvider)
}
@Throws(IOException::class)
private fun createSshServer(
validUsername: String,
validPassword: String?,
): SSHClient {
val mock = Mockito.mock(SSHClient::class.java)
doNothing().`when`(mock).connect(HOST, PORT)
doNothing()
.`when`(mock)
.addHostKeyVerifier(
SecurityUtils.getFingerprint(
hostKeyPair.public,
),
)
doNothing().`when`(mock).disconnect()
if (!Utils.isNullOrEmpty(validPassword)) {
doNothing().`when`(mock).authPassword(validUsername, validPassword)
doThrow(UserAuthException("Invalid login/password"))
.`when`(mock)
.authPassword(
not(eq(validUsername)),
not(eq(validPassword)),
)
} else {
doNothing().`when`(mock).authPublickey(validUsername, sshKeyProvider)
doThrow(UserAuthException("Invalid key"))
.`when`(mock)
.authPublickey(
not(eq(validUsername)),
eq(sshKeyProvider),
)
}
`when`(mock.isConnected).thenReturn(true)
`when`(mock.isAuthenticated).thenReturn(true)
NetCopyClientConnectionPool.sshClientFactory =
object : SSHClientFactory {
override fun create(config: net.schmizz.sshj.Config): SSHClient {
return mock
}
}
return mock
}
companion object {
const val HOST = "127.0.0.1"
const val PORT = 22222
private const val invalidUsername = "invaliduser"
private const val invalidPassword = "invalidpassword"
private val encodedInvalidUsername = encode(invalidUsername, UTF_8.name())
private val encodedInvalidPassword = encode(invalidPassword, UTF_8.name())
lateinit var hostKeyPair: KeyPair
lateinit var userKeyPair: KeyPair
lateinit var sshKeyProvider: KeyProvider
/**
* Bootstrap the unit test
*/
@BeforeClass
@JvmStatic
fun bootstrap() {
hostKeyPair = TestUtils.createKeyPair()
userKeyPair = TestUtils.createKeyPair()
sshKeyProvider =
object : KeyProvider {
override fun getPrivate() = userKeyPair.private
override fun getPublic() = userKeyPair.public
override fun getType() = KeyType.RSA
override fun equals(other: Any?): Boolean {
return if (other !is KeyProvider) {
false
} else {
other.private == private && other.public == public
}
}
}
RxJavaPlugins.reset()
RxJavaPlugins.setIoSchedulerHandler {
Schedulers.trampoline()
}
RxAndroidPlugins.reset()
RxAndroidPlugins.setInitMainThreadSchedulerHandler {
Schedulers.trampoline()
}
}
}
}
|