Exemplo n.º 1
0
        public void Decapsulate(VpnChannel channel, VpnPacketBuffer encapBuffer, VpnPacketBufferList decapsulatedPackets, VpnPacketBufferList controlPacketsToSend)
        {
            var context = channel.PlugInContext as VpnContext;

            while (context.PendingPackets.TryDequeue(out byte[] originBuffer))
            {
                var buf = channel.GetVpnReceivePacketBuffer();
                if (encapBuffer.Buffer.Length > buf.Buffer.Capacity)
                {
                    LogLine("Dropped one packet", channel);
                    //Drop larger packets.
                    return;
                }
                originBuffer.CopyTo(0, buf.Buffer, 0, originBuffer.Length);
                buf.Buffer.Length = (uint)originBuffer.Length;
                LogLine("Added one packet" + buf.Buffer.Length, channel);
                decapsulatedPackets.Append(buf);
            }
            //var buf = channel.GetVpnReceivePacketBuffer();
            // LogLine("Decapsulating one packet", channel);
            //if (encapBuffer.Buffer.Length > buf.Buffer.Capacity)
            //{
            //    LogLine("Dropped one packet", channel);
            //    //Drop larger packets.
            //    return;
            //}

            //encapBuffer.Buffer.CopyTo(buf.Buffer);
            //buf.Buffer.Length = encapBuffer.Buffer.Length;
            //decapsulatedPackets.Append(buf);
            // LogLine("Decapsulated one packet", channel);
        }
Exemplo n.º 2
0
        public void Connect(VpnChannel channel)
        {
            List <HostName> hosts = new List <HostName>();

            hosts.Add(new HostName("216.58.208.46"));

            StreamSocket streamsock = new StreamSocket();



            VpnRouteAssignment vpr = new VpnRouteAssignment();

            vpr.ExcludeLocalSubnets = true;
            VpnNamespaceAssignment na = new VpnNamespaceAssignment();

            VpnInterfaceId id = new VpnInterfaceId(Encoding.ASCII.GetBytes("1"));

            channel.AssociateTransport(streamsock, null);
            //channel.TerminateConnection("FUCKU");
            try
            {
                channel.Start(null, null, id, vpr, na, 512, 512, true, streamsock, null);
                VpnPacketBuffer buf = channel.GetVpnReceivePacketBuffer();
            }
            catch (Exception e)
            {
                return;
            }
        }
Exemplo n.º 3
0
        public void Disconnect(VpnChannel channel)
        {
            channel.Stop();
            this.socket?.Dispose();

            Debug.WriteLine("VPNDEMO: Disconnected");
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Debug.WriteLine("VPNDEMO: Entering VpnBackgroundTask.Run");

            //Take a deferral
            serviceDeferral = taskInstance.GetDeferral();

            try
            {
                if (VpnBackgroundTask.vpnPlugin == null)
                {
                    Debug.WriteLine("VPNDEMO: creating vpn plugin... ");
                    VpnBackgroundTask.vpnPlugin = new SslVpnPlugin();

                    taskInstance.Canceled += OnTaskCanceled;
                }

                Debug.WriteLine("VPNDEMO: Calling ProcessEventAsync...");
                VpnChannel.ProcessEventAsync(VpnBackgroundTask.vpnPlugin, taskInstance.TriggerDetails);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"VPNDEMO: unhandled exception in VpnBackgroundTask.Run: {ex.Message} ");
            }

            // we're done complete the deferral
            serviceDeferral.Complete();

            //Debug.WriteLine($"VPNDEMO: Exiting VpnBackgroundTask.Run");
        }
 public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
 {
     while (packets.Size > 0)
     {
         encapulatedPackets.Append(packets.RemoveAtBegin());
     }
 }
Exemplo n.º 6
0
        public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
        {
            var vpnSendPacketBuffer = channel.GetVpnSendPacketBuffer();

            while (packets.Size > 0) //can't iterate over packets
            {
                var packet       = packets.RemoveAtEnd();
                var packetAppId  = packet.AppId;
                var packetBuffer = packet.Buffer;
                var fromBuffer   = DataReader.FromBuffer(packetBuffer);
                var fromBufferUnconsumedBufferLength = fromBuffer.UnconsumedBufferLength;
                var bytes = new byte[fromBufferUnconsumedBufferLength];
                fromBuffer.ReadBytes(bytes);

                var bytesRead  = 0;
                var ipv4Header = Ipv4Header.Create(bytes, ref bytesRead);

                var vpnPacketBufferStatus   = packet.Status;
                var packetTransportAffinity = packet.TransportAffinity;
                var packetTransportContext  = packet.TransportContext;

                encapulatedPackets.Append(packet);

                //parse ip datagram and inspect destination IP
                //if destIP isn't found in peer list, drop and send ICMP "no route to host"?
            }
        }
Exemplo n.º 7
0
        public void GetKeepAlivePayload(VpnChannel channel, out VpnPacketBuffer keepAlivePacket)
        {
            Debug.WriteLine("GetKeepAlivePayload++");

            keepAlivePacket = null;
            Debug.WriteLine("GetKeepAlivePayload--");
        }
Exemplo n.º 8
0
        public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
        {
            try
            {
                uint packetCount = packets.Size;
                var  tun         = context.tun;
                if (tun == null)
                {
                    return;
                }
                while (packetCount-- > 0)
                {
#if YTLOG_VERBOSE
                    LogLine("Encapsulating " + packets.Size.ToString(), channel);
#endif
                    var packet = packets.RemoveAtBegin();
                    tun.PushPacket(packet.Buffer.ToArray());
                    packets.Append(packet);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Log("Error encapsulating packets: " + ex.ToString());
            }
        }
Exemplo n.º 9
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            _toyVpnPlugin = _toyVpnPlugin ?? new ToyVpnPlugin();
            VpnChannel.ProcessEventAsync(_toyVpnPlugin, taskInstance.TriggerDetails);
            deferral.Complete();
        }
Exemplo n.º 10
0
        public void Connect(VpnChannel channel)
        {
            State = VpnPluginState.Connecting;
            LogLine("Connecting", channel);
            try
            {
                DatagramSocket transport = new DatagramSocket();
                channel.AssociateTransport(transport, null);

                VpnContext context = null;
                if (channel.PlugInContext == null)
                {
                    // create and Initialize context
                    LogLine("Initializing new context", channel);
                    channel.PlugInContext = context = new VpnContext();
                    context.InitTun2Socks(TUN_SERVICE_NAME, VPN_ADDR, VPN_NETMASK, (int)VPN_MTU, "192.168.1.107:60000", "aes-256-cfb", "SSTest");
                    context.Init();
                }
                else
                {
                    LogLine("Context exists", channel);
                    context = (VpnContext)channel.PlugInContext;
                }

                transport.ConnectAsync(new HostName("127.0.0.1"), TUN_SERVICE_NAME).AsTask().ContinueWith(t =>
                {
                    LogLine("r Connected", channel);
                }).Wait();

                var now = DateTime.Now;
                LogLine("Starting transport", channel);

                channel.StartWithMainTransport(
                    new[] { VPN_HOST },
                    null,
                    null,
                    context.routeScope,
                    null,
                    VPN_MTU,
                    VPN_MAX_FRAME,
                    false,
                    transport
                    );

                var delta = DateTime.Now - now;
                LogLine($"Finished starting transport in {delta.TotalMilliseconds} ms.", channel);
                LogLine("Connected", channel);
                State = VpnPluginState.Connected;
            }
            catch (Exception ex)
            {
                LogLine("Error connecting", channel);
                LogLine(ex.Message, channel);
                LogLine(ex.StackTrace, channel);
                State = VpnPluginState.Disconnected;
            }
        }
Exemplo n.º 11
0
 public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
 {
     // LogLine("Encapsulating", channel);
     while (packets.Size > 0)
     {
         var packet = packets.RemoveAtBegin();
         encapulatedPackets.Append(packet);
         //LogLine("Encapsulated one packet", channel);
     }
 }
Exemplo n.º 12
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral def = taskInstance.GetDeferral();



            VpnPlgin plg = new VpnPlgin();

            VpnChannel.ProcessEventAsync(plg, taskInstance.TriggerDetails);
        }
Exemplo n.º 13
0
        public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
        {
            //Debug.WriteLine("Encapsulate++");
            while (packets.Size > 0)
            {
                encapulatedPackets.Append(packets.RemoveAtBegin());
            }

            //Debug.WriteLine("Encapsulate--");
        }
Exemplo n.º 14
0
        public void Connect(VpnChannel channel)
        {
            //VpnCustomPromptTextInput i = new VpnCustomPromptTextInput();
            //i.Compulsory = true;
            //i.DisplayName = "aaaa";

            //await channel.RequestCustomPromptAsync(new IVpnCustomPromptElement[] {i});

            //channel.RequestCredentials(VpnCredentialType.UsernamePassword, false, false, null);
            channel.LogDiagnosticMessage("asdasdasd");
        }
Exemplo n.º 15
0
        public void Decapsulate(VpnChannel channel, VpnPacketBuffer encapBuffer, VpnPacketBufferList decapsulatedPackets, VpnPacketBufferList controlPacketsToSend)
        {
            if (encapBuffer.Buffer.Capacity > ushort.MaxValue)
            {
                return;
            }
            var packetBuffer = encapBuffer.Buffer.ToArray();

            packetBuffer.CopyTo(0, encapBuffer.Buffer, 0, packetBuffer.Length);
            decapsulatedPackets.Append(encapBuffer);
        }
Exemplo n.º 16
0
        public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
        {
            while (packets.Size > 0)
            {
#if YTLOG_VERBOSE
                LogLine("Encapsulating " + packets.Size.ToString(), channel);
#endif
                var packet = packets.RemoveAtBegin();
                encapulatedPackets.Append(packet);
                //LogLine("Encapsulated one packet", channel);
            }
        }
Exemplo n.º 17
0
 public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
 {
     while (packets.Size > 0)
     {
         var packet = packets.RemoveAtBegin();
         if (packet.Buffer.Capacity <= ushort.MaxValue)
         {
             var packetBuffer = packet.Buffer.ToArray();
             packetBuffer.CopyTo(0, packet.Buffer, 0, packetBuffer.Length);
             encapulatedPackets.Append(packet);
         }
     }
 }
Exemplo n.º 18
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     try
     {
         var plugin = GetPlugin() as VpnPlugin;
         VpnChannel.ProcessEventAsync(GetPlugin(), taskInstance.TriggerDetails);
     }
     catch { }
     finally
     {
         taskInstance.GetDeferral().Complete();
     }
 }
Exemplo n.º 19
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var backgroundTaskDeferral = taskInstance.GetDeferral();

            try
            {
                VpnChannel.ProcessEventAsync(GetPlugin(), taskInstance.TriggerDetails);
            }
            catch { }
            finally
            {
                backgroundTaskDeferral.Complete();
            }
        }
Exemplo n.º 20
0
        public void Encapsulate(VpnChannel channel, VpnPacketBufferList packets, VpnPacketBufferList encapulatedPackets)
        {
            var context = channel.PlugInContext as VpnContext;

            // LogLine("Encapsulating", channel);
            while (packets.Size > 0)
            {
                var packet = packets.RemoveAtBegin();
                // encapulatedPackets.Append(packet);
                context.PushPacket(packet.Buffer.ToArray());
                LogLine("Encapsulated one packet" + packet.Buffer.ToArray().Length, channel);
            }
            context.CheckPendingPacket();
        }
        public void Connect(VpnChannel channel)
        {
            string serverPort = "8000";
            string secret     = "test";
            string parameters = null;

            _datagramSocket = new DatagramSocket();
            channel.AssociateTransport(_datagramSocket, null);
            _datagramSocket.MessageReceived += (s, e) =>
            {
                DataReader dataReader = e.GetDataReader();
                if (dataReader.UnconsumedBufferLength > 0 && dataReader.ReadByte() == 0)
                {
                    parameters      = dataReader.ReadString(dataReader.UnconsumedBufferLength);
                    _handshakeState = HandshakeState.Received;
                }
            };
            var         serverHostName = channel.Configuration.ServerHostNameList[0];
            XmlDocument xmlDocument    = new XmlDocument();

            xmlDocument.LoadXml(channel.Configuration.CustomField);
            var firstChild = xmlDocument.FirstChild;

            if (firstChild.Name.Equals("ToyVpnConfig"))
            {
                foreach (XmlNode childNode in firstChild.ChildNodes)
                {
                    if (childNode.Name.Equals("ServerPort"))
                    {
                        serverPort = childNode.InnerText;
                    }
                    else if (childNode.Name.Equals("Secret"))
                    {
                        secret = childNode.InnerText;
                    }
                }
            }
            _datagramSocket.ConnectAsync(serverHostName, serverPort).AsTask().GetAwaiter().GetResult();
            _handshakeState = HandshakeState.Waiting;
            HandShake(_datagramSocket, secret).AsTask().GetAwaiter().GetResult();
            if (_handshakeState == HandshakeState.Received)
            {
                ConfigureAndConnect(channel, parameters);
            }
            else
            {
                channel.Stop();
            }
        }
Exemplo n.º 22
0
        public void Decapsulate(VpnChannel channel, VpnPacketBuffer encapBuffer, VpnPacketBufferList decapsulatedPackets,
                                VpnPacketBufferList controlPacketsToSend)
        {
            var buf = channel.GetVpnReceivePacketBuffer();

            // LogLine("Decapsulating one packet", channel);
            if (encapBuffer.Buffer.Length > buf.Buffer.Capacity)
            {
                //Drop larger packets.
                return;
            }
            encapBuffer.Buffer.CopyTo(buf.Buffer);
            buf.Buffer.Length = encapBuffer.Buffer.Length;
            decapsulatedPackets.Append(buf);
        }
Exemplo n.º 23
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var initDebugSocketNeeded = DebugLogger.InitNeeded();

            if (initDebugSocketNeeded)
            {
                try
                {
                    var _ = DebugLogger.InitDebugSocket();
                }
                catch (Exception) { }
            }
            VpnChannel.ProcessEventAsync(Plugin, taskInstance.TriggerDetails);
            DebugLogger.Log("VPN Background task finished");
        }
Exemplo n.º 24
0
        public void Connect(VpnChannel channel)
        {
            try
            {
                var b = goTestFunction(1);

                //var vpnCustomPromptTextInput = new VpnCustomPromptTextInput() { DisplayName = "Give me some input" };
                ////this call is NOT asynchronous. awaiting the result will halt the program
                //channel.RequestCustomPromptAsync(new IVpnCustomPromptElement[]
                //{
                //    new VpnCustomPromptText() {DisplayName = "This is a test", Text = "Message"},
                //    vpnCustomPromptTextInput
                //});
                //var inputWas = vpnCustomPromptTextInput.Text;


                var transport = new DatagramSocket();
                transport.MessageReceived += Transport_MessageReceived;
                //var streamSocket = new StreamSocket();
                channel.AssociateTransport(transport, null);
                //channel.LogDiagnosticMessage("this is from the wireguard plugin");// supposedly under Event Viewer, under Application and Services Logs\Microsoft\Windows\Vpn Plugin Platform. but can't find
                //transport.BindServiceNameAsync("50000").AsTask().Wait();
                //transport.BindEndpointAsync(new HostName("192.168.1.100"), "50000").AsTask().Wait();
                transport.ConnectAsync(new HostName(channel.Configuration.ServerUris[0].Scheme),
                                       channel.Configuration.ServerUris[0].LocalPath).AsTask().Wait();

                var vpnRouteAssignment = new VpnRouteAssignment {
                    ExcludeLocalSubnets = false
                };
                vpnRouteAssignment.Ipv4InclusionRoutes.Add(new VpnRoute(new HostName("10.189.129.1"), 32));

                channel.StartExistingTransports(
                    new[] { new HostName("10.189.129.2"), //this is our network interface address
                    },
                    null,
                    null,
                    vpnRouteAssignment,
                    null,
                    VPN_MTU,
                    VPN_MAX_FRAME,
                    false
                    );
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 25
0
        internal void ConfigureAndConnect(VpnChannel vpnChannel, string parameters)
        {
            parameters = parameters.TrimEnd();
            uint mtuSize = 68;
            var  assignedClientIPv4list                = new List <HostName>();
            var  dnsServerList                         = new List <HostName>();
            VpnRouteAssignment      assignedRoutes     = new VpnRouteAssignment();
            VpnDomainNameAssignment assignedDomainName = new VpnDomainNameAssignment();
            var ipv4InclusionRoutes                    = assignedRoutes.Ipv4InclusionRoutes;

            foreach (var parameter in parameters.Split(null))
            {
                var fields = parameter.Split(",");
                switch (fields[0])
                {
                case "m":
                    mtuSize = uint.Parse(fields[1]);
                    break;

                case "a":
                    assignedClientIPv4list.Add(new HostName(fields[1]));
                    break;

                case "r":
                    ipv4InclusionRoutes.Add(new VpnRoute(new HostName(fields[1]), (byte)(int.Parse(fields[2]))));
                    break;

                case "d":
                    dnsServerList.Add(new HostName(fields[1]));
                    break;

                default:
                    break;
                }
            }

            assignedRoutes.Ipv4InclusionRoutes = ipv4InclusionRoutes;
            assignedDomainName.DomainNameList.Add(new VpnDomainNameInfo(".", VpnDomainNameType.Suffix, dnsServerList, null));

            try
            {
                vpnChannel.StartExistingTransports(assignedClientIPv4list, null, null, assignedRoutes, assignedDomainName, mtuSize, ushort.MaxValue, false);
            }
            catch (Exception e)
            {
                vpnChannel.TerminateConnection(e.Message);
            }
        }
Exemplo n.º 26
0
 private void promoteGUI(VpnChannel channel)
 {
     channel.RequestCustomPrompt(new List <IVpnCustomPrompt> {
         new VpnCustomTextBox()
         {
             Label = "this is label", DisplayText = "DPT"
         },
         new VpnCustomEditBox()
         {
             Label = "AccessKey"
         },
         new VpnCustomEditBox()
         {
             Label = "AccessKey2"
         },
     });
 }
Exemplo n.º 27
0
        public void Connect(VpnChannel channel)
        {
            Debug.WriteLine("UniPacketConnect++");
            try
            {
                channel.LogDiagnosticMessage("Start");

                foreach (var shn in channel.Configuration.ServerHostNameList)
                {
                    Debug.WriteLine("serverHostName->{0}", shn);
                    remoteHost = shn.ToString();
                }
                foreach (var ssn in channel.Configuration.ServerServiceName)
                {
                    Debug.WriteLine("ServerServiceName->{0}", ssn);
                }


                tunnelSocket.ConnectAsync(new HostName(remoteHost), "2312").AsTask().Wait();
                channel.AssociateTransport(tunnelSocket, null);
                channel.Start(
                    new[] { new HostName("66.32.12.12") }, //此处可从服务端获取ip配置 或者直接通过dhcp来设置,此处需注意随机IP生成不得与本地网络中所有的网段碰撞
                    null,                                  //此处为V6地址指派,用于设置虚拟nic的v6地址,也可通过远端dhcp配置
                    null,                                  //未弄清,此处为绑定的网卡id还是创建的虚拟nic id
                    new VpnRouteAssignment
                {
                    ExcludeLocalSubnets = true,
                    Ipv4InclusionRoutes = new[] { new VpnRoute(new HostName("66.32.12.0"), 24) }
                },         //路由表可在此处设置
                    new VpnNamespaceAssignment()
                {
                },                //值得研究,此处似乎可以筛选来源和目标APP,此处是支持ProxyAutoConfigUri,可考虑使用js代理脚本
                    512,          //NIC设置, MTU
                    1024,         //NIC设置, maxFrame 用于ip层拆包策略
                    false,
                    tunnelSocket, //main tunnel
                    null
                    );
            }
            catch (System.Exception e)
            {
                channel.SetErrorMessage(e.Message);
            }
            Debug.WriteLine("UniPacketConnect--");
        }
Exemplo n.º 28
0
        public void Disconnect(VpnChannel channel)
        {
            State = VpnPluginState.Disconnecting;
            if (channel.PlugInContext == null)
            {
                LogLine("Disconnecting with null context", channel);
                State = VpnPluginState.Disconnected;
                return;
            }
            else
            {
                LogLine("Disconnecting with non-null context", channel);
            }
            var context = (DebugVpnContext)channel.PlugInContext;

            context.Stop();
            LogLine("channel stopped", channel);
            //channel.PlugInContext = null;
            State = VpnPluginState.Disconnected;
        }
Exemplo n.º 29
0
 public void Disconnect(VpnChannel channel)
 {
     try
     {
         State = VpnPluginState.Disconnecting;
         DebugLogger.Log("Stopping channel");
         channel.Stop();
         DebugLogger.Log("Stopping context");
         context.Stop();
         DebugLogger.Log("Context stopped");
     }
     catch (Exception ex)
     {
         DebugLogger.Log("Error disconnecting: " + ex.ToString());
     }
     finally
     {
         State = VpnPluginState.Disconnected;
         var _ = DebugLogger.ResetLoggers();
         DebugLogger.initNeeded = null;
     }
 }
Exemplo n.º 30
0
        public void Decapsulate(VpnChannel channel, VpnPacketBuffer encapPacketBuffer, VpnPacketBufferList decapsulatedPackets, VpnPacketBufferList controlPacketsToSend)
        {
            try
            {
                var reader = context.outPackets?.Reader;
                if (reader == null)
                {
                    return;
                }

                while (reader.TryRead(out var bytes))
                {
                    var encapBuffer = channel.GetVpnReceivePacketBuffer();
                    var encapBuf    = encapBuffer.Buffer;
                    bytes.CopyTo(encapBuf);
                    encapBuf.Length = (uint)bytes.Length;
                    decapsulatedPackets.Append(encapBuffer);
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Log("Error decapsulating packets: " + ex.ToString());
            }
        }
 public VpnChannelEvents(VpnChannel This)
 {
     this.This = This;
 }