English 中文(简体)
Android Kotlin SSH NY
原标题:Android Kotlin SSH VPN

Hey Guys I tried to make simple android ssh vpn i m new to android programming and made simple logic to just work and everything in that code seems ok but somehow when i run the code i have Invalid Argument Error and idk what s the problem heres s the code

2. 服役逻辑


import android.content.Intent
import android.net.VpnService
import android.os.ParcelFileDescriptor
import android.util.Log
import com.jcraft.jsch.ChannelDirectTCPIP
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.FileInputStream
import java.io.FileOutputStream
import java.net.Inet4Address
import java.net.InetSocketAddress
import java.net.Socket
import java.nio.ByteBuffer
import java.nio.channels.DatagramChannel

class ServiceAction: VpnService() {
    private val tag = "serviceAction"

    private var vpnInterface: ParcelFileDescriptor? = null
    private var sshClient: SshLogic? = null
    private var directTcpIpChannel: ChannelDirectTCPIP? = null
    private var isConnected: Boolean? = false

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent?.getStringExtra("COMMAND") == "STOP"){
            stopVPN()
        }
        Log.d(tag, "Activity Extras -> ${intent?.extras.toString()}")
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        stopSelf()
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(tag, "Creating Service Action")
        //Initialize The VPN Interface
        setupVPN()
        //Setup the ssh Client
        initializeSSHClient()
        //start The VPN
        startVPN()

    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun startVPN(){
        GlobalScope.launch(Dispatchers.IO) {
            runVpn()
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun initializeSSHClient(){
        GlobalScope.launch(Dispatchers.IO) {
            sshClient = SshLogic("server hostname", port, "username", "password")
            isConnected = sshClient?.connect()
            directTcpIpChannel = sshClient!!.openChannel()
        }
    }

    private fun stopVPN(){
        sshClient?.disconnect()
        vpnInterface?.close()
        stopSelf()
        Log.d(tag, "Stop Vpn!")
    }

    private fun setupVPN(){
        val packageName = applicationContext.packageName
        val builder = Builder()
            .addAddress("79.76.0.1", 24)
            .addDnsServer("9.9.9.9")
            .addRoute("0.0.0.0", 0)
            .setSession(tag)
            .addDisallowedApplication(packageName)
            .setMtu(1500)
        vpnInterface = builder.establish()
        Log.d(tag, "VPN Interface Established")
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun runVpn() {

        Thread.sleep(3000L)
        Log.d(tag, "Running VPN Loop...")
        val vpnInterfaceChannelIn = FileInputStream(vpnInterface?.fileDescriptor).channel
        val vpnInterfaceChannelOut = FileOutputStream(vpnInterface?.fileDescriptor).channel
        Log.d(tag, "Vpn Interface state ${vpnInterface?.fileDescriptor?.valid()}")

        //Log.d(tag, "VPN  Interface File -> ${vpnInterface?.fileDescriptor}")

        directTcpIpChannel?.let {
            val channelInput = it.inputStream
            val channelOutput = it.outputStream
            it.connect()
            Log.d(tag, "VPN Loop Started with channel id of ${it.id}")
            if (it.isConnected){

                GlobalScope.launch(Dispatchers.IO) {

                    loop@ while (true){
                        val buffer = ByteBuffer.allocate(1500)
                        buffer.clear()
                        val readBytes = vpnInterfaceChannelIn.read(buffer)
                        if (readBytes <= 0){
                            continue@loop
                        }
                        Log.d(tag, "Incoming Traffic w/ Length $readBytes")
                        buffer.flip()
                        channelOutput.write(buffer.array())
                        channelOutput.flush()

                        buffer.clear()
                        val channelReadBytes = channelInput.read(buffer.array())
                        if (channelReadBytes <= 0){
                            continue@loop
                        }
                        Log.d(tag, "Length From Server $channelReadBytes")
                        //There is a Bug here `out of the band index` fix it
                        try {
                            Log.d(tag, "Length of prepared data to write in to interface ${buffer.get()}")
                            vpnInterfaceChannelOut.write(buffer)
                        } catch (e: Exception){
                            e.printStackTrace()
                            //stopVPN()
                        }

                    }
                }

            }else{
                Log.d(tag, "Channel is not Connected!")
                stopVPN()
            }
        }

        //channelIn.close()
        //channelOut.close()
        //stopVPN()
    }
}

2. 密切关联逻辑


import android.util.Log
import com.jcraft.jsch.ChannelDirectTCPIP
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session

class SshLogic(
    private val hostname : String,
    private val port : Int,
    private val username : String,
    private val password : String
) {
    private lateinit var session: Session
    private val tag = "sshLogic"
    fun connect() : Boolean {
        Log.d(tag, "Trying To Connect")
        val jsch = JSch()
        session = jsch.getSession(username, hostname, port)
        session.setPassword(password)
        session.setConfig("StrictHostKeyChecking", "no")

        try {
            session.connect()
            Log.d(tag, "Connected to ssh server")
            Log.d(tag, "User Info -> ${session.userInfo} - Status : ${session.isConnected}")
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Log.d(tag, "Failed To Connect")
        return false
    }

    fun disconnect() {
        Log.d(tag, "Disconnecting")
        session.disconnect()
    }

    fun openChannel(): ChannelDirectTCPIP? {
        Log.d(tag, "Trying To Open Channel")
        var channel: ChannelDirectTCPIP? = null
        try {
            channel = session.openChannel("direct-tcpip") as ChannelDirectTCPIP
            Log.d(tag, "Channel Opened Successfully -> ${channel.id}")
        } catch (e: JSchException){
            Log.d(tag, "Error Opening Channel")
            e.printStackTrace()
        }
        channel?.setHost(hostname)
        channel?.setPort(port)
        return channel
    }
}

i) 期望捕捉所有交通工具,将其拖到sh服务器

问题回答

There are some minor things I guess that you need to checkup. However this doesn t seem to have any syntax or logic trouble.

因此,我认为这需要再次检查全部项目档案。 如果有可能,请用上载服务或星号向我递交一份复印件。

  1. Incorrect Channel Usage:

在你经营的Vpn(Vpn)职能中,有一部分是,你重新利用ByteBuffer.get()获得准备数据的时间,以写入接口。 这种做法是不正确的,造成“没有班级指数”问题。 你们应使用缓冲。

改为:

Log.d(tag, "Length of prepared data to write in to interface ${buffer.get()}")

加入:

Log.d(tag, "Length of prepared data to write in to interface ${buffer.remaining()}")
  1. Invalid VpnInterfaceChannelOut Usage:

在你经营的Vpn()职能中,你正在使用vpn InterfaceChannelOut.write(buffer.array())来撰写缓冲数据,以便检索ChannelOut。 这可能造成问题,因为阵列包含整个缓冲能力,而不仅仅是实际数据。 相反,在撰写本报告之前,你应使用缓冲flip()确保只写有效数据。

改为:

channelOutput.write(buffer.array())

With these lines:

buffer.flip()
val bufferData = ByteArray(buffer.remaining())
buffer.get(bufferData)
channelOutput.write(ByteBuffer.wrap(bufferData))
  1. Non-Blocking Looping:

在你经营的Vpn()职能中,你似乎有一只 lo子处理非锁定行为,可能导致使用CPU。 为了解决这一问题,考虑在休息室内引入睡眠期,以让《公约》有一部分内容。 您也不妨采用一种更加复杂的非锁定做法。

  1. Ensure Buffer Synchronization:

When using buffers across different threads, you need to ensure proper synchronization to avoid data corruption. Consider using thread-safe mechanisms like ByteBuffer.allocateDirect() and wrapping it in a ByteBuffer instance, which can be safely passed between threads.

请铭记,像这种分散的复杂的网络编码可能具有挑战性,可能需要测试和反复确定和确定问题。 此外,轨道隧道的质量可能取决于诸如SSH服务器的稳定、网络条件等各种因素。

Hope you ll fix this cause I was also looking for some samples about ssh connection to be used as a vpn.

did you fixed it? if yes i need to know how you did it





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签