Inheritance: AuthenticatedStream
        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
 public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter)
 {
     _client = client;
     _stream = stream;
     _binaryReader = binaryReader;
     _binaryWriter = binaryWriter;
 }
        /// <summary>
        /// Create stream used to send and receive bytes from the socket.
        /// </summary>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream</returns>
        /// <exception cref="InvalidOperationException">Stream could not be created.</exception>
        protected override Stream CreateStream(Socket socket)
        {
            Stream stream = base.CreateStream(socket);

            var sslStream = new SslStream(stream, false, OnValidation);
            try
            {
                sslStream.AuthenticateAsServer(_certificate, UseClientCertificate, Protocol, false);
            }
            catch (IOException err)
            {
                Logger.Trace(err.Message);
                throw new InvalidOperationException("Failed to authenticate", err);
            }
            catch (ObjectDisposedException err)
            {
                Logger.Trace(err.Message);
                throw new InvalidOperationException("Failed to create stream.", err);
            }
            catch (AuthenticationException err)
            {
                Logger.Trace((err.InnerException != null) ? err.InnerException.Message : err.Message);
                throw new InvalidOperationException("Failed to authenticate.", err);
            }

            return sslStream;
        }
        public Task AuthenticateAsClient(X509Certificate2 certificate)
        {
            var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
            {
                if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
                {
                    return true;
                }

                // if (errors == SslPolicyErrors.None)
                //return true;
                return true;
            }, null);

            var tempStream = new SslStreamWrapper(ssl);
            Stream = tempStream;

            Func<AsyncCallback, object, IAsyncResult> begin =
                (cb, s) => ssl.BeginAuthenticateAsClient(this.RemoteIpAddress,
                    new X509Certificate2Collection(certificate),SslProtocols.Tls, false, cb, s);

            var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);
           
            return task;
        }
Exemple #5
0
        public void ActivateEncryption(string targethost, X509CertificateCollection clientCerts, SslProtocols sslProtocols)
        {
            RemoteCertificateValidationCallback userCertificateValidationCallback = null;

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The FtpSocketStream object is not connected.");
            }
            if (this.m_netStream == null)
            {
                throw new InvalidOperationException("The base network stream is null.");
            }
            if (this.m_sslStream != null)
            {
                throw new InvalidOperationException("SSL Encryption has already been enabled on this stream.");
            }
            try
            {
                if (userCertificateValidationCallback == null)
                {
                    userCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => this.OnValidateCertificate(certificate, chain, sslPolicyErrors);
                }
                this.m_sslStream = new System.Net.Security.SslStream(this.NetworkStream, true, userCertificateValidationCallback);
                DateTime now = DateTime.Now;
                this.m_sslStream.AuthenticateAsClient(targethost, clientCerts, sslProtocols, true);
                TimeSpan span = DateTime.Now.Subtract(now);
                FtpTrace.WriteLine("Time to activate encryption: {0}h {1}m {2}s, Total Seconds: {3}.", new object[] { span.Hours, span.Minutes, span.Seconds, span.TotalSeconds });
            }
            catch (AuthenticationException exception)
            {
                this.Close();
                throw exception;
            }
        }
Exemple #6
0
        static void DisplayCertificateInformation(SslStream stream)
        {
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

            X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                    localCertificate.Subject,
                    localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
             } else
            {
                Console.WriteLine("Local certificate is null.");
            }
            // Display the properties of the client's certificate.
            X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
            Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                remoteCertificate.Subject,
                remoteCertificate.GetEffectiveDateString(),
                remoteCertificate.GetExpirationDateString());
            } else
            {
                Console.WriteLine("Remote certificate is null.");
            }
        }
Exemple #7
0
        public virtual void Starttls()
        {
            var store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadWrite);
            X509Certificate2 ca_cert = new X509Certificate2();

            ca_cert.Import(System.IO.File.ReadAllBytes("/tmp/CA.p12"));
            store.Add(ca_cert);
            store.Close();

            System.Security.Cryptography.X509Certificates.X509Certificate2 CPrivate = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            CPrivate.Import(System.IO.File.ReadAllBytes("/tmp/ffwronbpi.feuerwehrcloud.de.p12"));
            System.Security.Cryptography.X509Certificates.X509Certificate CPublic = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            CPublic.Import(System.IO.File.ReadAllBytes("/tmp/ffwronbpi.feuerwehrcloud.de.cer"));

            try {
                SSLStream = new System.Net.Security.SslStream(this.NetworkStream, false, null, null);
                SSLStream.AuthenticateAsServer(CPrivate, false, System.Security.Authentication.SslProtocols.Default, true);
                //SSLStream.
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            SSLWriter = new StreamWriter(SSLStream);
            SSLReader = new StringReaderStream(SSLStream, 4096);
            UseSSL    = true;
        }
        public void Close()
        {
            --RefCount;
            //Debug.Log("TcpClients: Destroy " + RefCount);
            try
            {
                if (_ssl != null)
                {
                    _ssl.Close();
                }

                if (_net != null)
                {
                    _net.Close();
                }

                if (_client != null)
                {
                    _client.Close();
                }

                if (_async != null)
                {
                    _async = null;
                }
            }
            catch
            {
            }
            _client = null;
            _ssl    = null;
            _stream = null;
            _async  = null;
            _net    = null;
        }
Exemple #9
0
 static void DisplaySecurityLevel(SslStream stream)
 {
     Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
     Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
     Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
     Console.WriteLine("Protocol: {0}", stream.SslProtocol);
 }
    internal TcpListenerWebSocketContext (
      TcpClient tcpClient,
      string protocol,
      bool secure,
      ServerSslConfiguration sslConfig,
      Logger logger)
    {
      _tcpClient = tcpClient;
      _secure = secure;
      _logger = logger;

      var netStream = tcpClient.GetStream ();
      if (secure) {
        var sslStream = new SslStream (
          netStream, false, sslConfig.ClientCertificateValidationCallback);

        sslStream.AuthenticateAsServer (
          sslConfig.ServerCertificate,
          sslConfig.ClientCertificateRequired,
          sslConfig.EnabledSslProtocols,
          sslConfig.CheckCertificateRevocation);

        _stream = sslStream;
      }
      else {
        _stream = netStream;
      }

      _request = HttpRequest.Read (_stream, 90000);
      _uri = HttpUtility.CreateRequestUrl (
        _request.RequestUri, _request.Headers["Host"], _request.IsWebSocketRequest, secure);

      _websocket = new WebSocket (this, protocol);
    }
        internal static SslStream ManageClientRequest(TcpClient client)
        {
            SslStream sslStream = null;

            try
            {
                bool leaveInnerStreamOpen = true;

                RemoteCertificateValidationCallback validationCallback =
                    new RemoteCertificateValidationCallback(ClientValidationCallback);
                LocalCertificateSelectionCallback selectionCallback =
                    new LocalCertificateSelectionCallback(ServerCertificateSelectionCallback);
                EncryptionPolicy encryptionPolicy = EncryptionPolicy.AllowNoEncryption;

                sslStream = new SslStream(client.GetStream(), leaveInnerStreamOpen, validationCallback, selectionCallback, encryptionPolicy);
                Console.WriteLine("Server starting handshake");
                ServerSideHandshake(sslStream);
                Console.WriteLine("Server finished handshake");
            }
            catch(Exception ex)
            {
                sslStream = null;
                Console.WriteLine("\nError detected in sslStream: " + ex.Message);
            }
            return sslStream;
        }
Exemple #12
0
        public int initialize(IceInternal.Buffer readBuffer, IceInternal.Buffer writeBuffer, ref bool hasMoreData)
        {
            int status = _stream.connect(readBuffer, writeBuffer, ref hasMoreData);
            if(status != IceInternal.SocketOperation.None)
            {
                return status;
            }

            _stream.setBlock(true); // SSL requires a blocking socket

            if(_sslStream == null)
            {
                NetworkStream ns = new NetworkStream(_stream.fd(), false);
                _sslStream = new SslStream(ns, false, new RemoteCertificateValidationCallback(validationCallback),
                                                      new LocalCertificateSelectionCallback(selectCertificate));
                return IceInternal.SocketOperation.Connect;
            }

            Debug.Assert(_sslStream.IsAuthenticated);
            _authenticated = true;
            _instance.verifyPeer((NativeConnectionInfo)getInfo(), _stream.fd(), _host);

            if(_instance.securityTraceLevel() >= 1)
            {
                _instance.traceStream(_sslStream, _stream.ToString());
            }
            return IceInternal.SocketOperation.None;
        }
		/// <summary>
		///   Creates a new instance of the TlsaStream class
		/// </summary>
		/// <param name="innerStream">The underlying stream on which the encrypted stream should work</param>
		/// <param name="resolver">A DNSSEC resolver to get the TLSA records</param>
		/// <param name="enforceTlsaValidation">If true, the use of TLSA records is enforced</param>
		/// <param name="leaveInnerStreamOpen">If true, the underlying stream will not be closed when this instance is closed</param>
		/// <param name="userCertificateSelectionCallback">
		///   A callback to select client certificates to authenticate the client to
		///   the server
		/// </param>
		public DaneStream(Stream innerStream, IDnsSecResolver resolver, bool enforceTlsaValidation = false, bool leaveInnerStreamOpen = false, LocalCertificateSelectionCallback userCertificateSelectionCallback = null)
			: base(innerStream, leaveInnerStreamOpen)
		{
			_resolver = resolver;
			_enforceTlsaValidation = enforceTlsaValidation;
			_sslStream = new SslStream(innerStream, leaveInnerStreamOpen, ValidateRemoteCertificate, userCertificateSelectionCallback);
		}
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
 public SecureConnection(TcpClient client, SslStream stream, MessageExchangeProtocol protocol)
 {
     this.client = client;
     this.stream = stream;
     this.protocol = protocol;
     lastUsed = DateTimeOffset.UtcNow;
 }
Exemple #16
0
        /// <summary>
        /// Creates a communication channel using ServerIpAddress and ServerPort.
        /// </summary>
        /// <returns>Ready communication channel to communicate</returns>
        protected override ICommunicationChannel CreateCommunicationChannel()
        {
            TcpClient client = new TcpClient();
            SslStream sslStream;
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                client = new TcpClient();
                client.Connect(new IPEndPoint(IPAddress.Parse(_serverEndPoint.IpAddress), _serverEndPoint.TcpPort));

                sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateCertificate),
                    new LocalCertificateSelectionCallback(SelectLocalCertificate));

                X509Certificate2Collection clientCertificates = new X509Certificate2Collection();
                if (_clientCert != null)
                {
                    clientCertificates.Add(_clientCert);
                }

                sslStream.AuthenticateAsClient(_nombreServerCert, clientCertificates, SslProtocols.Default, false);

                return new TcpSslCommunicationChannel( _serverEndPoint, client, sslStream);
            }
            catch (AuthenticationException)
            {
                client.Close();
                throw;
            }
        }
Exemple #17
0
        private void processClient(TcpClient client)
        {
            X509Certificate certificate = new X509Certificate("..\\..\\..\\Certificate\\Certificate.pfx", "KTYy77216");
            // SslStream; leaveInnerStreamOpen = false;
            SslStream stream = new SslStream(client.GetStream(), false);
            try
            {
                // clientCertificateRequired = false
                // checkCertificateRevocation = true;
                stream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, true);
                Console.WriteLine("Waiting for client message ...");

                // Read a message from the client
                string input = readMessage(stream);
                Console.WriteLine("Received: {0}", input);

                // Write a message to the client
                byte[] message = Encoding.UTF8.GetBytes("Hello client, this is a message from the server :)<EOF>");
                Console.WriteLine("Sending message to client ...");
                stream.Write(message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                stream.Close();
                client.Close();
                return;
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
    public void Connect(String server, int port, bool ssl)
    {
      String m_response = "";
      m_use_ssl = ssl;
      m_client.Connect(server, port);

      m_network_stream = m_client.GetStream();

      if (m_use_ssl)
      {
        m_ssl_stream = new SslStream((Stream)m_network_stream, true);
        m_ssl_stream.AuthenticateAsClient(server);

        m_stream = (Stream)m_ssl_stream;
      }
      else
      {
        m_stream = m_network_stream;
      }

      m_response = this.Response();

      if (m_response.Substring(0, 3) != "+OK")
      {
        throw new Pop3Exception(m_response);
      }
    }
Exemple #19
0
        public void Connect()
        {
            this.tcpClient = new TcpClient(this.host, this.port);
            this.sslStream = new SslStream(
                this.tcpClient.GetStream(),
                false,
                ValidateServerCertificate,
                null);
            var certificatesCollection = new X509Certificate2Collection(this.certificate);
            try
            {
                this.sslStream.AuthenticateAsClient(this.host, certificatesCollection, SslProtocols.Tls, false);

            }
            catch (AuthenticationException ex)
            {
                throw new NotificationException("Failed to authenticate", ex);

            }

            if (!this.sslStream.IsMutuallyAuthenticated)
            {
                throw new NotificationException("Failed to authenticate");
            }
        }
        public static void Handle(ulong clientId, Packet packet, SslStream stream)
        {
            var client = ClientManager.GetClient(clientId);

            Dictionary<string, Tdf> data = Utilities.DecodePayload(packet.payload);

            TdfInteger gameId = (TdfInteger)data["GID"];
            TdfInteger personaId = (TdfInteger)data["PID"];
            TdfInteger reason = (TdfInteger)data["REAS"];

            // TODO: GameManager.RemovePlayer

            TdfEncoder encoder = new TdfEncoder();

            byte[] payload = encoder.Encode();

            Utilities.SendPacket(new Packet
            {
                componentId = packet.componentId,
                commandId = 0xB,
                errorCode = 0,
                msgType = MessageType.REPLY,
                msgNum = packet.msgNum,

                payload = payload,
                payloadSize = payload.Length
            }, stream);

            // send a notification that a player has been removed
            PlayerRemovedNotification.Notify(gameId.value, personaId.value, (PlayerRemovedReason)reason.value, stream);
        }
        public ServiceEndPoint Discover(Uri remoteUri)
        {
            try
            {
                using (var client = CreateTcpClient())
                {
                    client.ConnectWithTimeout(remoteUri, HalibutLimits.TcpClientConnectTimeout);
                    using (var stream = client.GetStream())
                    {
                        using (var ssl = new SslStream(stream, false, ValidateCertificate))
                        {
                            ssl.AuthenticateAsClient(remoteUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false);
                            ssl.Write(HelloLine, 0, HelloLine.Length);
                            ssl.Flush();

                            if (ssl.RemoteCertificate == null)
                                throw new Exception("The server did not provide an SSL certificate");

                            return new ServiceEndPoint(remoteUri, new X509Certificate2(ssl.RemoteCertificate).Thumbprint);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new HalibutClientException(ex.Message, ex);
            }
        }
Exemple #22
0
        public void handler()
        {
            DataPacket data = null;

            sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), null);

            try
            {
                sslStream.AuthenticateAsClient(ipAdress);
            }
            catch
            {
                Console.WriteLine("Could not connect to server.");
            }

            for(; ; )
            {
                if (sslStream != null && sslStream.CanRead)
                {
                    try
                    {
                        data = formatter.Deserialize(sslStream) as DataPacket;
                        handleDataPacket(data);
                    }
                    catch
                    {
                        Console.WriteLine("Received data from server.");
                        //disconnect();
                    }

                }

                Thread.Sleep(100);
            }
        }
 public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
 {
     _remoteEndPoint = remoteEndPoint;
     _localEndPoint = localEndPoint;
     Debug.Assert(length == 0);
     try
     {
         _ssl = new SslStream(_inputStream, true);
         _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverCertificate, false, _protocols, false).ContinueWith((t, selfObject) =>
         {
             var self = (SslTransportHandler)selfObject;
             if (t.IsFaulted || t.IsCanceled)
                 self._next.FinishAccept(null, 0, 0, null, null);
             else
                 self._ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) =>
                 {
                     var self2 = (SslTransportHandler)selfObject2;
                     if (t2.IsFaulted || t2.IsCanceled)
                         self2._next.FinishAccept(null, 0, 0, null, null);
                     else
                         self2._next.FinishAccept(self2._recvBuffer, self2._recvOffset, t2.Result, self2._remoteEndPoint, self2._localEndPoint);
                 }, self);
         }, this);
     }
     catch (Exception)
     {
         Callback.StartDisconnect();
     }
 }
        public static void Handle(Packet packet, SslStream stream)
        {
            Dictionary<string, Tdf> data = Utilities.DecodePayload(packet.payload);

            TdfInteger gid = (TdfInteger)data["GID"];
            TdfInteger gsta = (TdfInteger)data["GSTA"];

            // update game state
            Database.UpdateGameState(gid.value, (GameState)gsta.value);

            Log.Info(string.Format("Advancing game state to {0} for game {1}.", (GameState)gsta.value, gid.value));

            TdfEncoder encoder = new TdfEncoder();

            byte[] payload = encoder.Encode();

            Utilities.SendPacket(new Packet
            {
                componentId = packet.componentId,
                commandId = 0x3,
                errorCode = 0,
                msgType = MessageType.REPLY,
                msgNum = packet.msgNum,

                payload = payload,
                payloadSize = payload.Length
            }, stream);

            GameStateChangeNotification.Notify(gid.value, (GameState)gsta.value, stream);
        }
        /// <summary>
        /// Initializes a client instance of <see cref="DesktopNetworkStream"/>.
        /// </summary>
        /// <param name="host">Network host.</param>
        /// <param name="port">Network port.</param>
        /// <param name="useTls">Use TLS layer?</param>
        /// <param name="noDelay">No delay?</param>
        /// <param name="ignoreSslPolicyErrors">Ignore SSL policy errors?</param>
        internal DesktopNetworkStream(string host, int port, bool useTls, bool noDelay, bool ignoreSslPolicyErrors)
        {
            this.Host = host;
            this.Port = port;
#if NETSTANDARD
            this.tcpClient = new TcpClient { NoDelay = noDelay };
            this.tcpClient.ConnectAsync(host, port).Wait();
#else
            this.tcpClient = new TcpClient(host, port) { NoDelay = noDelay };
#endif

            Stream stream = this.tcpClient.GetStream();
            if (useTls)
            {
                var ssl = new SslStream(
                    stream,
                    false,
                    (sender, certificate, chain, errors) => errors == SslPolicyErrors.None || ignoreSslPolicyErrors);
#if NETSTANDARD
                ssl.AuthenticateAsClientAsync(host).Wait();
#else
                ssl.AuthenticateAsClient(host);
#endif
                stream = ssl;
            }

            this.networkStream = stream;
        }
Exemple #26
0
 public ServerClient(TcpClient client, Serverapplication server, SslStream stream)
 {
     this.server = server;
     this.client = client;
     this.stream = stream;
     if (client != null)
     {
         new Thread(() =>
         {
             BinaryFormatter formatter = new BinaryFormatter();
             while (client.Connected)
             {
                 Packet packet = NetworkFlow.ReadPacket(stream);
                 if (packet != null)
                 {
                     Console.WriteLine("recieved packet");
                     packet.handleServerSide(this);
                 }
             }
             server.getConnectedClients().Remove(this);
             if (user != null)
                 user.isOnline = false;
             Console.WriteLine("Client disconnected");
         }).Start();
     }
 }
Exemple #27
0
 public SslClient(string ip, int port, UserCertificate certificate = null, int bufferSize = 1024) : base(ip, port)
 {
     try
     {
         _bufferSize = bufferSize;
         if (certificate != null)
         {
             _certificate = certificate;
         }
         else
         {
             _certificate = new X509Certificate2();
         }
         _stream = new SslStream(GetStream(), false, ServerCertificateValidation, UserCertificateSelection);
         _stream.AuthenticateAsClient(ip);
     }
     catch (AuthenticationException err)
     {
         ErrorOnAuthentication();
     }
     catch (SocketException)
     {
         ErrorOnAuthentication();
     }
     catch (Win32Exception)
     {
         ErrorOnAuthentication();
     }
 }
Exemple #28
0
        internal override async Task<HttpSession> CreateSession(long sessionId, TcpClient client)
        {
            var sslStream = new SslStream(client.GetStream());
            await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false).ConfigureAwait(false);

            return new HttpSession(sessionId, client, sslStream, true, maxKeepAlives, sessionReadBufferSize, (int)sessionReadTimeout.TotalMilliseconds, (int)sessionWriteTimeout.TotalMilliseconds);
        }
Exemple #29
0
        private void Parse()
        {
            TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
            tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP
            System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
            sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client
            //bool flag = sslstream.IsAuthenticated; // check flag
            System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
            System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
            sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command
            sw.Flush(); // sent to server
            sw.WriteLine("PASS utybfkmyjcnm321");
            sw.Flush();
            sw.WriteLine("RETR 5");
            sw.Flush();
            sw.WriteLine("Quit "); // close the connection
            sw.Flush();
            string str = string.Empty;
            string strTemp = string.Empty;

            while ((strTemp = reader.ReadLine()) != null)
            {
                if (".".Equals(strTemp))
                {
                    break;
                }
                if (strTemp.IndexOf("-ERR") != -1)
                {
                    break;
                }
                str += strTemp;
            }

            MessageBox.Show(str);
        }
        public static void Handle(ulong clientId, Packet packet, SslStream stream)
        {
            TdfEncoder encoder = new TdfEncoder();

            //TdfMap smap = new TdfMap("SMAP", TdfBaseType.TDF_TYPE_STRING, TdfBaseType.TDF_TYPE_STRING);
            //smap.Map("cust", ""); // TODO: fetch from userSettingsSave 0x000B

            encoder.WriteTdf(new List<Tdf>
            {

            });

            byte[] payload = encoder.Encode();

            Utilities.SendPacket(new Packet
            {
                componentId = Component.UTIL,
                commandId = 0xB,
                errorCode = 0,
                msgType = MessageType.REPLY,
                msgNum = packet.msgNum,

                payload = payload,
                payloadSize = payload.Length
            }, stream);
        }
        public override void Open()
        {
            base.Open();
            MailConnection.EmailStreamReader = new StreamReader(MailConnection.TcpClient.GetStream());
            MailConnection.EmailStream = MailConnection.TcpClient.GetStream();
            LoggerHolders.ConsoleLogger.Log(MailConnection.EmailStreamReader.ReadLine());
            MailCommand command = MailConnection.CreateCommand();
            command.Command = "STARTTLS";
            command.ExecuteCommand();

            LoggerHolders.ConsoleLogger.Log(command.Response);

            var sslStrm = new SslStream(MailConnection.TcpClient.GetStream(), false);

            try
            {
                sslStrm.AuthenticateAsClient(MailConnection.Host);
            }
            catch (AuthenticationException ex)
            {
                LoggerHolders.ConsoleLogger.Log("Exception", LogType.Critical, ex);
                if (ex.InnerException != null)
                {
                    LoggerHolders.ConsoleLogger.Log("Exception", LogType.Critical, ex.InnerException);
                }
                MailConnection.TcpClient.Close();
            }

            MailConnection.EmailStream = sslStrm;
            MailConnection.EmailStreamReader = new StreamReader(sslStrm);
        }
Exemple #32
0
 internal static string OpenConnection()
 {
     errorMsg = string.Empty;
     _dataBuffer = string.Empty;
     int result = 0;
     int.TryParse(ConfigurationSupport.currentPort, out result);
     try
     {
         _client = new TcpClient(ConfigurationSupport.currentHost, result);
         string str = QuickRead(null);
         if (str != ConfigurationSupport.version)
         {
             errorMsg = errorMsg + "Mismatched versions." + Environment.NewLine;
             errorMsg = errorMsg + string.Format("SERVER: ({0})" + Environment.NewLine, str);
             errorMsg = errorMsg + string.Format("CLIENT: ({0})" + Environment.NewLine, ConfigurationSupport.version);
             CloseConnection();
         }
         if (_client.Connected)
         {
             StreamWriter writer = new StreamWriter(_client.GetStream());
             writer.WriteLine(string.Format("VersionInfo {{{0}}}", ConfigurationSupport.version));
             writer.Flush();
             _sslStreamReader = new SslStream(_client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallBack));
             try
             {
                 _sslStreamReader.AuthenticateAsClient(ConfigurationSupport.currentHost, null, SslProtocols.Ssl3, false);
             }
             catch (AuthenticationException exception)
             {
                 errorMsg = errorMsg + "SSL Authentication Error." + Environment.NewLine;
                 errorMsg = errorMsg + exception.ToString();
             }
             _sslStreamWriter = new StreamWriter(_sslStreamReader);
             _sslStreamWriter.AutoFlush = true;
             _sslStreamWriter.WriteLine(string.Format("ValidateUser {0} {1}", ConfigurationSupport.currentUsername, ConfigurationSupport.currentPassword));
             string str2 = QuickRead(_sslStreamReader);
             if (str2 == "UserID INVALID")
             {
                 CloseConnection();
                 errorMsg = "Invalid USERNAME and/or PASSWORD";
             }
             else
             {
                 isConnected = true;
                 ConfigurationSupport.userID = str2.Split(new char[0])[1];
             }
         }
     }
     catch (Exception ex)
     {
         isConnected = false;
         errorMsg = string.Format("Could not connect to {0}:{1}", ConfigurationSupport.currentHost, ConfigurationSupport.currentPort);
     }
     if (isConnected)
     {
         _readBuffer = new byte[0x100];
         _sslStreamReader.BeginRead(_readBuffer, 0, _readBuffer.Length, new AsyncCallback(SguildConnection.OnReceivedData), _client.GetStream());
     }
     return errorMsg;
 }
		/// <summary>
		/// Connects the client to a remote host using the specified 
		/// IP address and port number as an asynchronous operation.
		/// </summary>
		/// <param name="host">host.</param>
		/// <param name="port">port.</param>
		/// <param name="certificate">certificate.</param>
		/// <exception cref="ConnectionInterruptedException"></exception>
		public async Task ConnectAsync(string host, int port, X509Certificate2 certificate)
		{
			try
			{
				// connect via tcp
				tcpClient = new TcpClient();
				await tcpClient.ConnectAsync(host, port);

				await Task.Run(() =>
				{
					// create ssl stream
					sslStream = new SslStream(tcpClient.GetStream(), true,
						Ssl.ServerValidationCallback,
						Ssl.ClientCertificateSelectionCallback,
						EncryptionPolicy.RequireEncryption);

					// handshake
					Ssl.ClientSideHandshake(certificate, sslStream, host);
				});
			}
			catch (CertificateException e)
			{
				throw new ConnectionInterruptedException("Connection failed. Reason: " + e.Message);
			}
			catch
			{
				throw new ConnectionInterruptedException("Connection failed.");
			}
		}
Exemple #34
0
        bool TryConnect(string hostname, System.Net.IPAddress ip, int port, int connectTimeout)
        {
            //EB.Debug.Log("Try connect {0}:{1}", ip, port);

            if (_client.Client.AddressFamily != ip.AddressFamily)
            {
                _client.Close();
                _client         = new System.Net.Sockets.TcpClient(ip.AddressFamily);
                _client.NoDelay = true;
            }

            var async = _client.BeginConnect(ip, port, null, null);

            if (!async.AsyncWaitHandle.WaitOne(System.TimeSpan.FromMilliseconds(connectTimeout)))
            {
                _error = NetworkFailure.TimedOut;
                return(false);
            }
            if (!async.IsCompleted)
            {
                _error = NetworkFailure.TimedOut;
                return(false);
            }
            _client.EndConnect(async);

            if (_client.Connected == false)
            {
                EB.Debug.LogError("Failed to connect to {0}:{1}", ip, port);
                _error = NetworkFailure.CannotConnectToHost;
                return(false);
            }

            OnConnected();

            _net    = _client.GetStream();
            _stream = _net;

            if (_secure)
            {
                //EB.Debug.Log("Doing ssl connect {0}:{1}", ip, port);
                _ssl = new System.Net.Security.SslStream(_stream, true, RemoteCertificateValidationCallback, null);
                try
                {
                    _ssl.AuthenticateAsClient(hostname);
                }
                catch (System.Exception e)
                {
                    EB.Debug.LogError("Failed to authenticate: " + e);
                    return(false);
                }
                _stream = _ssl;
            }

            //EB.Debug.Log("Connected to {0}:{1}", ip, port);

            LastTime = System.DateTime.Now;

            return(true);
        }
Exemple #35
0
 public override void Close()
 {
     if (this.m_socket != null)
     {
         try
         {
             if (this.m_socket.Connected)
             {
                 this.m_socket.Close();
             }
             this.m_socket.Dispose();
         }
         catch (SocketException exception)
         {
             FtpTrace.WriteLine("Caught and discarded a SocketException while cleaning up the Socket: {0}", new object[] { exception.ToString() });
         }
         finally
         {
             this.m_socket = null;
         }
     }
     if (this.m_netStream != null)
     {
         try
         {
             this.m_netStream.Dispose();
         }
         catch (IOException exception2)
         {
             FtpTrace.WriteLine("Caught and discarded an IOException while cleaning up the NetworkStream: {0}", new object[] { exception2.ToString() });
         }
         finally
         {
             this.m_netStream = null;
         }
     }
     if (this.m_sslStream != null)
     {
         try
         {
             this.m_sslStream.Dispose();
         }
         catch (IOException exception3)
         {
             FtpTrace.WriteLine("Caught and discarded an IOException while cleaning up the SslStream: {0}", new object[] { exception3.ToString() });
         }
         finally
         {
             this.m_sslStream = null;
         }
     }
 }
Exemple #36
0
        /// <summary>
        /// Begin the secure negotiation and server authentication.
        /// </summary>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="System.Security.Authentication.AuthenticationException"></exception>
        public virtual void BeginSslNegotiation()
        {
            if (!_isSslAuthenticated && _useSslConnection && _networkStream == null)
            {
                // Block the socket for now.
                _socket.Blocking = true;

                // Initialy assign the network stream
                _networkStream = new NetworkStream(_socket);
            }

            try
            {
                // If not authenticated.
                if (!_isSslAuthenticated)
                {
                    // If ssl certificate has not been assigned.
                    if (_x509Certificate == null)
                    {
                        throw new Exception("Please add an SSL certificate for secure connections.");
                    }

                    // Get the current ssl stream
                    // from the socket.
                    _sslStream = new SslStream(_networkStream);

                    // Load the certificate into the
                    // secure stream used for secure communication.
                    _sslStream.AuthenticateAsServer(_x509Certificate, false, _sslProtocols, false);

                    // Get the state of the authentication.
                    if (_sslStream.IsAuthenticated && _sslStream.IsEncrypted)
                    {
                        _isSslAuthenticated = true;
                    }
                    else
                    {
                        _isSslAuthenticated = false;
                    }
                }
            }
            catch (System.Security.Authentication.AuthenticationException)
            {
                if (_sslStream != null)
                {
                    _sslStream.Dispose();
                }

                throw;
            }
        }
Exemple #37
0
 byte[] receiveData(System.Net.Sockets.TcpClient c, System.Net.Security.SslStream ssl)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         System.Threading.Thread.Sleep(2000);
         while (c.Available > 0)
         {
             byte[] buf = new byte[10000];
             int    len = ssl.Read(buf, 0, buf.Length);
             ms.Write(buf, 0, len);
         }
         return(ms.ToArray());
     }
 }
        void ConstructorArguments()
        {
            var optA = new OptionalConstructorArguments(this, cb: InvalidValidation);
            var optB = new OptionalConstructorArguments(this, cb: CompliantValidation);

            using (var ms = new System.IO.MemoryStream())
            {
                using (var ssl = new System.Net.Security.SslStream(ms, true, (sender, chain, certificate, SslPolicyErrors) => true))
                {
                }
                using (var ssl = new System.Net.Security.SslStream(ms, true, InvalidValidation))
                {
                }
                using (var ssl = new System.Net.Security.SslStream(ms, true, CompliantValidation))
                {
                }
            }
        }
        void ConstructorArguments()
        {
            var optA = new OptionalConstructorArguments(this, cb: InvalidValidation);   //Noncompliant [flow15]
            var optB = new OptionalConstructorArguments(this, cb: CompliantValidation);

            using (var ms = new System.IO.MemoryStream())
            {
                using (var ssl = new System.Net.Security.SslStream(ms, true, (sender, chain, certificate, SslPolicyErrors) => true))
//                                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Enable server certificate validation on this SSL/TLS connection}}
//                                                                                                                            ^^^^ Secondary@-1
                {
                }
                using (var ssl = new System.Net.Security.SslStream(ms, true, InvalidValidation))   //Noncompliant [flow16]
                {
                }
                using (var ssl = new System.Net.Security.SslStream(ms, true, CompliantValidation))
                {
                }
            }
        }
        protected virtual void DoSslHandShake(ActiveUp.Net.Security.SslHandShake sslHandShake)
        {
            Logger.AddEntry("DoSslHandShake:Creating SslStream...", 2);
            this._sslStream = new System.Net.Security.SslStream(base.GetStream(), false,
                                                                CertificatePermit
                                                                    ? (sender, certificate, chain, sslPolicyErrors) => true
                                                                    : sslHandShake.ServerCertificateValidationCallback,
                                                                sslHandShake.ClientCertificateSelectionCallback);
            Logger.AddEntry("DoSslHandShake:AuthenticateAsClient...", 2);

            try
            {
                this._sslStream.AuthenticateAsClient(sslHandShake.HostName, sslHandShake.ClientCertificates,
                                                     sslHandShake.SslProtocol, sslHandShake.CheckRevocation);
            }
            catch (Exception ex)
            {
                Logger.AddEntry(string.Format("DoSslHandShake:AuthenticateAsClient failed with Exception {0}", ex), 2);
                this._sslStream = null;
                throw;
            }
        }
Exemple #41
0
        public static void CloseNotify(SslStream sslStream)
        {
            if (sslStream.IsAuthenticated)
            {
                bool isServer = sslStream.IsServer;

                byte[] result;
                int    resultSz;

                int SCHANNEL_SHUTDOWN = 1;
                var workArray         = BitConverter.GetBytes(SCHANNEL_SHUTDOWN);

                var nativeApiHelpers = GetNativeApiHelpers(sslStream);
                var(securityContextHandle, credentialsHandleHandle) = nativeApiHelpers.GetHandlesFunc();

                int bufferSize = 1;
                NativeApi.SecurityBufferDescriptor securityBufferDescriptor = new NativeApi.SecurityBufferDescriptor(bufferSize);
                NativeApi.SecurityBufferStruct[]   unmanagedBuffer          = new NativeApi.SecurityBufferStruct[bufferSize];

                fixed(NativeApi.SecurityBufferStruct *ptr = unmanagedBuffer)
                fixed(void *workArrayPtr = workArray)
                {
                    securityBufferDescriptor.UnmanagedPointer = (void *)ptr;

                    unmanagedBuffer[0].token = (IntPtr)workArrayPtr;
                    unmanagedBuffer[0].count = workArray.Length;
                    unmanagedBuffer[0].type  = NativeApi.BufferType.Token;

                    NativeApi.SecurityStatus status;
                    status = (NativeApi.SecurityStatus)NativeApi.ApplyControlToken(ref securityContextHandle, securityBufferDescriptor);
                    if (status == NativeApi.SecurityStatus.OK)
                    {
                        unmanagedBuffer[0].token = IntPtr.Zero;
                        unmanagedBuffer[0].count = 0;
                        unmanagedBuffer[0].type  = NativeApi.BufferType.Token;

                        NativeApi.SSPIHandle   contextHandleOut = default(NativeApi.SSPIHandle);
                        NativeApi.ContextFlags outflags         = NativeApi.ContextFlags.Zero;
                        long ts = 0;

                        var inflags = NativeApi.ContextFlags.SequenceDetect |
                                      NativeApi.ContextFlags.ReplayDetect |
                                      NativeApi.ContextFlags.Confidentiality |
                                      NativeApi.ContextFlags.AcceptExtendedError |
                                      NativeApi.ContextFlags.AllocateMemory |
                                      NativeApi.ContextFlags.InitStream;

                        if (isServer)
                        {
                            status = (NativeApi.SecurityStatus)NativeApi.AcceptSecurityContext(ref credentialsHandleHandle, ref securityContextHandle, null,
                                                                                               inflags, NativeApi.Endianness.Native, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts);
                        }
                        else
                        {
                            status = (NativeApi.SecurityStatus)NativeApi.InitializeSecurityContextW(ref credentialsHandleHandle, ref securityContextHandle, null,
                                                                                                    inflags, 0, NativeApi.Endianness.Native, null, 0, ref contextHandleOut, securityBufferDescriptor, ref outflags, out ts);
                        }
                        if (status == NativeApi.SecurityStatus.OK)
                        {
                            byte[] resultArr = new byte[unmanagedBuffer[0].count];
                            Marshal.Copy(unmanagedBuffer[0].token, resultArr, 0, resultArr.Length);
                            Marshal.FreeCoTaskMem(unmanagedBuffer[0].token);
                            result   = resultArr;
                            resultSz = resultArr.Length;
                        }
                        else
                        {
                            throw new InvalidOperationException(string.Format("AcceptSecurityContext/InitializeSecurityContextW returned [{0}] during CloseNotify.", status));
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("ApplyControlToken returned [{0}] during CloseNotify.", status));
                    }
                }

                var innerStream = nativeApiHelpers.GetInnerStreamFunc();
                innerStream.Write(result, 0, resultSz);
            }
        }
Exemple #42
0
        static int Main(string[] args)
        {
            if (!args.Length.Equals(3))
            {
                Console.WriteLine("\nOSSEC HIDS: Connects to the manager to extract the agent key.\n");
                Console.WriteLine("ossec_auth_net <manager_ip> <port> <OSSEC Dir>");
                return(-1);
            }

            string manager          = args[0];
            int    port             = Convert.ToInt32(args[1]);
            string ossecInstallPath = args[2];
            string agentname        = Dns.GetHostName();
            string key = string.Empty;

            Console.WriteLine("Program Started");

            RemoteCertificateValidationCallback validationCallback =
                new RemoteCertificateValidationCallback(SslHelper.ServerValidationCallback);

            LocalCertificateSelectionCallback selectionCallback =
                new LocalCertificateSelectionCallback(SslHelper.ClientCertificateSelectionCallback);

            EncryptionPolicy encryptionPolicy = EncryptionPolicy.RequireEncryption;

            try
            {
                TcpClient client = new TcpClient(manager, port);

                Console.WriteLine("Starting SSL comunication");
                using (SslStream sslStream = new System.Net.Security.SslStream(client.GetStream(), false, validationCallback, selectionCallback, encryptionPolicy))
                {
                    Console.WriteLine("Connected to manager");
                    SslHelper sslHelper = new SslHelper(manager, sslStream);

                    //1. start the authentication process. If it doesn't succeed
                    //an AuthenticationException is thrown
                    sslHelper.ClienSideHandshake(ossecInstallPath);

                    //2. send the input message to the server
                    Console.WriteLine("Adding agent: " + agentname);
                    //sslHelper.SendDataToServer(string.Format("OSSEC A:'%0'", agentname));
                    StreamWriter writer = new StreamWriter(sslStream);
                    writer.WriteLine(string.Format("OSSEC A:'{0}'", agentname));
                    writer.Flush();


                    Console.WriteLine("Send request to manager. Waiting for reply.");

                    StreamReader reader   = new StreamReader(sslStream, true);
                    string       response = reader.ReadToEnd();

                    if (response.Contains(OssecResponseTag))
                    {
                        ServiceController ossecAgentService = ServiceController.GetServices().Where(s => s.DisplayName.CompareTo(OssecServiceName).Equals(0)).FirstOrDefault();
                        if (ossecAgentService.Status != ServiceControllerStatus.Stopped)
                        {
                            ossecAgentService.Stop();
                        }

                        key = response.Replace(OssecResponseTag, string.Empty).Replace("'", string.Empty);
                        string clientKeys = Path.Combine(ossecInstallPath, OssecClientKeyFile);
                        if (File.Exists(clientKeys))
                        {
                            File.Delete(clientKeys);
                        }
                        File.WriteAllText(clientKeys, key);
                        Console.WriteLine("File saved succesfully");
                        ossecAgentService.Start();
                        Console.WriteLine("Starting agent");
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Response from manager error: %0", response));
                        return(-1);
                    }
                }

                Console.WriteLine("Connection closed");
                Console.WriteLine("OSSEC Agent succesfully configured!");
                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error connecting to manager: " + ex.Message);
                return(-1);
            }
        }
        /// <summary>
        /// Uses a TCPClient and SSLStream to perform a POST.
        /// </summary>
        /// <param name="requestUrl">URL that the POST must be directed to.</param>
        /// <param name="body">Message that is to be sent.</param>
        /// <param name="user">UserId in your Zeep System. Only required if your sending a Single Message to a User.
        /// Otherwise, just send a string.Empty.</param>
        /// <returns>Response from the server. (although it will write the response to console)</returns>
        public static string SendSMS(string requestUrl, string body, string user)
        {
            string parameters     = "";
            string requestHeaders = "";
            string responseData   = "";

            // FORMAT must be Sun, 06 Nov 1994 08:49:37 GMT
            string http_date = DateTime.UtcNow.ToString("r");

            // Clean the text to send
            body = HttpUtility.UrlEncode(body, System.Text.Encoding.UTF8);

            if (user.Length > 0)
            {
                parameters += "user_id=" + user + "&";
            }
            if (body.Length > 0)
            {
                parameters += "body=" + body;
            }


            // String that will be converted into a signature.
            string canonicalString = API_KEY + http_date + parameters;


            //------------START HASH COMPUTATION---------------------
            // Compute the Base64 HMACSHA1 value
            HMACSHA1 hmacsha1 = new HMACSHA1(SECRET_ACCESS_KEY.ToByteArray());

            // Compute the hash of the input file.
            byte[] hashValue = hmacsha1.ComputeHash(canonicalString.ToByteArray());

            String b64Mac         = hashValue.ToBase64String();
            String authentication = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);
            //-----------END HASH COMPUTATION------------------------


            string auth = String.Format("Zeep {0}:{1}", API_KEY, b64Mac);


            System.Uri uri = new Uri(requestUrl);
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(uri.Host, uri.Port);
            string requestMethod = "POST " + uri.LocalPath + " HTTP/1.1\r\n";

            // Set Headers for the POST message
            requestHeaders += "Host: api.zeepmobile.com\r\n";
            requestHeaders += "Authorization: " + auth + "\r\n";
            requestHeaders += "Date: " + DateTime.UtcNow.ToString("r") + "\r\n";
            requestHeaders += "Content-Type: application/x-www-form-urlencoded\r\n";
            requestHeaders += "Content-Length: " + parameters.ToByteArray().Length + "\r\n";
            requestHeaders += "\r\n";


            // Get the data to be sent as a byte array.
            Byte[] data = System.Text.Encoding.UTF8.GetBytes(requestMethod + requestHeaders + parameters + "\r\n");
            // Send the message to the connected TcpServer.
            NetworkStream stream = client.GetStream();


            // SSL Authentication is used because the Server requires https.
            System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                stream,
                false,
                new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate));
            sslStream.AuthenticateAsClient(uri.Host);

            // Send the data over the SSL stream.
            sslStream.Write(data, 0, data.Length);
            sslStream.Flush();


            // Receive the TcpServer.response.
            for (int i = 0; i < 100; i++)
            {
                if (stream.DataAvailable)
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            Byte[] bytes = new byte[1024];
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            while (stream.DataAvailable)
            {
                int count = sslStream.Read(bytes, 0, 1024);
                if (count == 0)
                {
                    break;
                }
                sb.Append(System.Text.Encoding.UTF8.GetString(bytes, 0, count));
            }

            responseData = sb.ToString();
            Console.WriteLine(responseData);
            // Close everything.
            client.Close();

            return(responseData);
        }
Exemple #44
0
        private void PopBeforeSmtp(MailParameters mailParams)
        {
            Stream stream = null;

            System.Net.Sockets.TcpClient popclient = null;
            try
            {
                string rstr;
                popclient = new System.Net.Sockets.TcpClient();

                // POPサーバーに接続
                popclient.Connect(mailParams.PopServer, mailParams.PopPort);
                logs.AppendLine("POP: Connected.");

                X509CertificateCollection clientCertificateCollection = new X509CertificateCollection();
                if (mailParams.IsClientCertValidate)
                {
                    var clientCertificate = Cert.GetCert(mailParams.ClientCertSerialNo);
                    clientCertificateCollection.Add(clientCertificate);
                }

                // サーバーとデータの送受信を行うストリームを取得する
                // 通信開始(SSL有り)
                switch (mailParams.PopSecureMode)
                {
                case SecureMode.SSL2:                   // SSL2で運用しているサーバは存在しないはずだが、一応対応しておく
                    stream = new System.Net.Security.SslStream(popclient.GetStream(), false, ServerCertificateValidation);
                    ((System.Net.Security.SslStream)stream).AuthenticateAsClient(mailParams.SmtpServer, clientCertificateCollection, SslProtocols.Ssl2, false);
                    logs.AppendLine("POP: socket is over SSL2.");
                    break;

                case SecureMode.SSL3:                   // SSL3で運用しているサーバはあるかもしれない
                    stream = new System.Net.Security.SslStream(popclient.GetStream(), false, ServerCertificateValidation);
                    ((System.Net.Security.SslStream)stream).AuthenticateAsClient(mailParams.SmtpServer, clientCertificateCollection, SslProtocols.Ssl3, false);
                    logs.AppendLine("POP: socket is over SSL3.");
                    break;

                case SecureMode.TLS:                    // TLSは現状では主流
                case SecureMode.STARTTLS:
                    stream = new System.Net.Security.SslStream(popclient.GetStream(), false, ServerCertificateValidation);
                    ((System.Net.Security.SslStream)stream).AuthenticateAsClient(mailParams.SmtpServer, clientCertificateCollection, SslProtocols.Tls, false);

                    logs.AppendLine("POP: socket is over TLS.");
                    break;

                case SecureMode.None:
                    stream = popclient.GetStream();
                    logs.AppendLine("POP: socket unsecure.");
                    break;
                }
                stream.ReadTimeout  = 5000;
                stream.WriteTimeout = 500;

                //サーバーからのはじめのメッセージを受信

                // POPサーバー接続時のレスポンス受信
                string connectstr = PopWriteAndRead(stream, "");
                if (connectstr.StartsWith("+OK") != true)
                {
                    throw new PopException("POPサーバー接続エラー");
                }

                switch (mailParams.PopAuth)
                {
                case PopAuthMethod.Standard:
                    // ユーザIDの送信
                    rstr = PopWriteAndRead(stream, "USER " + mailParams.PopUserId + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("ユーザIDエラー");
                    }

                    // パスワードの送信
                    rstr = PopWriteAndRead(stream, "PASS " + mailParams.PopPasswd + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("パスワードエラー");
                    }
                    break;

                case PopAuthMethod.APOP:
                    // APOP用のタイムスタンプ文字列を取得しておく
                    var timestamp = GetAPopTimeStamp(connectstr);
                    if (string.IsNullOrWhiteSpace(timestamp))
                    {
                        throw new PopException("APOP未対応");
                    }
                    Byte[] byt = System.Text.Encoding.ASCII.GetBytes(string.Format("<{0}>{1}", mailParams.PopUserId, mailParams.PopPasswd));
                    System.Security.Cryptography.MD5CryptoServiceProvider md5 =
                        new System.Security.Cryptography.MD5CryptoServiceProvider();
                    Byte[] res = md5.ComputeHash(byt);
                    string aps = BitConverter.ToString(res).Replace("-", "").ToLower();
                    rstr = PopWriteAndRead(stream, "APOP " + mailParams.PopUserId + " " + aps + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("ユーザIDまたはパスワードエラー");
                    }
                    break;

                case PopAuthMethod.NTLM:
                    // ユーザIDの送信
                    rstr = PopWriteAndRead(stream, "USER " + mailParams.PopUserId + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("ユーザIDエラー");
                    }

                    // パスワードの送信
                    rstr = PopWriteAndRead(stream, "PASS " + mailParams.PopPasswd + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("パスワードエラー");
                    }
                    break;

                case PopAuthMethod.CramMd5:
                    rstr = PopWriteAndRead(stream, "AUTH CRAM-MD5\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("CRAM-MD5未対応");
                    }

                    rstr = PopWriteAndRead(stream, CreateCramMd5ResponseString(rstr.Substring(4), mailParams.PopUserId, mailParams.PopPasswd) + "\r\n");
                    if (rstr.StartsWith("+OK") != true)
                    {
                        throw new PopException("認証エラー");
                    }
                    break;
                }

                // ステータスの送信
                rstr = PopWriteAndRead(stream, "STAT" + "\r\n");
                if (rstr.StartsWith("+OK") != true)
                {
                    throw new PopException("STATエラー");
                }

                // 終了の送信
                rstr = PopWriteAndRead(stream, "QUIT" + "\r\n");
                // 戻り値は無視
            }
            catch (PopException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new PopException("内部例外発生", ex);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (popclient != null)
                {
                    popclient.Close();
                }
            }
        }
Exemple #45
0
        internal static IMonoSslStream CreateMonoSslStream(Stream innerStream, bool leaveInnerStreamOpen, MonoTlsProvider provider, MonoTlsSettings settings)
        {
            var sslStream = new SslStream(innerStream, leaveInnerStreamOpen, provider, settings);

            return(sslStream.Impl);
        }
 public SyncSslIOAdapter(SslStream sslStream) => _sslStream = sslStream;
Exemple #47
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Set the web socket state to closed.
                if (_context != null)
                {
                    _context.SocketState = SocketState.Closed;
                }

                // Release the receive and send spin wait handler.
                Interlocked.Exchange(ref _exitWaitReceiveIndicator, 0);
                Interlocked.Exchange(ref _exitWaitSendIndicator, 0);
                Interlocked.Exchange(ref _isContextActive, 0);

                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Close the connection.
                    CloseEx();

                    if (_socket != null)
                    {
                        _socket.Dispose();
                    }

                    if (_sslStream != null)
                    {
                        _sslStream.Dispose();
                    }

                    if (_networkStream != null)
                    {
                        _networkStream.Dispose();
                    }

                    if (_requestBuffer != null)
                    {
                        _requestBuffer.Dispose();
                    }

                    if (_responseBuffer != null)
                    {
                        _responseBuffer.Dispose();
                    }

                    if (_requestStream != null)
                    {
                        _requestStream.Dispose();
                    }

                    if (_responseStream != null)
                    {
                        _responseStream.Dispose();
                    }

                    if (_context != null)
                    {
                        if (_context.ContextState != null)
                        {
                            // If the current state context
                            // implements IDisposable then
                            // dispose of the resources.
                            if (_context.ContextState is IDisposable)
                            {
                                IDisposable disposable = (IDisposable)_context.ContextState;
                                disposable.Dispose();
                            }
                        }
                        _context.Dispose();
                    }
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _socket                = null;
                _sslStream             = null;
                _networkStream         = null;
                _x509Certificate       = null;
                _endConnectionCallback = null;

                _requestBuffer  = null;
                _responseBuffer = null;

                _requestStream  = null;
                _responseStream = null;

                _request  = null;
                _response = null;

                _context.ContextState = null;
                _context = null;
            }
        }
Exemple #48
0
        /// <summary>
        /// Begin the secure negotiation and server authentication.
        /// </summary>
        /// <param name="tlsNegotiationCommand">Send a TLS negotiation command (e.g. OK Begin TLS negotiation now) if not null.</param>
        /// <returns>True if authentication has started; else false.</returns>
        /// <remarks>This is generally used for TLS protcol.</remarks>
        private bool BeginTlsNegotiation(string tlsNegotiationCommand = null)
        {
            if (!_isSslAuthenticated && _useSslConnection && _networkStream == null)
            {
                // Block the socket for now.
                _socket.Blocking = true;

                // Initialy assign the network stream
                _networkStream = new NetworkStream(_socket);
            }

            try
            {
                // If not authenticated.
                if (!_isSslAuthenticated)
                {
                    // If ssl certificate has not been assigned.
                    if (_x509Certificate == null)
                    {
                        throw new Exception("Please add an SSL certificate for secure connections.");
                    }

                    // Get the current ssl stream
                    // from the socket.
                    _sslStream = new SslStream(_networkStream);

                    // Load the certificate into the
                    // secure stream used for secure communication.
                    _sslStream.AuthenticateAsServer(_x509Certificate, false, _sslProtocols, false);

                    // Get the state of the authentication.
                    if (_sslStream.IsAuthenticated && _sslStream.IsEncrypted)
                    {
                        _isSslAuthenticated = true;
                    }
                    else
                    {
                        _isSslAuthenticated = false;
                    }

                    // If not null then send the begin TLS negotiation command.
                    // This is in plain text letting the client know to start
                    // the TLS negotiation.
                    if (!String.IsNullOrEmpty(tlsNegotiationCommand))
                    {
                        // Send the data.
                        byte[] data = Encoding.Default.GetBytes(tlsNegotiationCommand);
                        _responseStream.Write(data, 0, data.Length);
                    }
                }
            }
            catch (System.Security.Authentication.AuthenticationException)
            {
                if (_sslStream != null)
                {
                    _sslStream.Dispose();
                }

                throw;
            }

            // Return the result.
            return(_isSslAuthenticated);
        }
Exemple #49
0
        public string DonwloadTimeSheetMail()
        {
            string sUserid, sPassword;

            GetMailUseridAndPassword(out sUserid, out sPassword);

            string sTempDir = GetTempDir();
            string sPrefix  = GetTempFileNamePrefix();
            string sLpath   = sTempDir + "\\" + sPrefix + "maillog.txt";
//			if (File.Exists(sLpath)) File.Delete(sLpath);
            string sDpath = sTempDir + "\\" + sPrefix + "mailtext.txt";
//			if (File.Exists(sDpath)) File.Delete(sDpath);
            string sEpath = sTempDir + "\\" + sPrefix + "timesheet";
            string sRes;

            StreamWriter strmlgw = new System.IO.StreamWriter(System.IO.File.Create(sLpath));
            TcpClient    tcpclnt = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
            SslStream    sslstrm = new System.Net.Security.SslStream(tcpclnt.GetStream());

            // There should be no gap between the imap command and the \r\n
            // sslstrm.read() -- while sslstrm.readbyte!= eof does not work
            // because there is no eof from server and  cannot check for \r\n
            // because in case of larger response from server ex:read email
            // message. There are lot of lines so \r\n appears at the end of
            // each line sslstrm.timeout sets the underlying tcp connections
            // timeout if the read or writetime out exceeds then the undelying
            // connectionis closed.

            strmlgw.WriteLine("### START ====================================", sslstrm);
            sslstrm.AuthenticateAsClient("imap.gmail.com");
            strmlgw.WriteLine("# Send blank =================================", sslstrm);
            SendImapCommand("", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'LOGIN' ===============================", sslstrm);
            SendImapCommand("$ LOGIN " + sUserid + " " + sPassword + "  \r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'SELECT INBOX' ========================", sslstrm);
            SendImapCommand("$ SELECT INBOX\r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);

//			strmlgw.WriteLine("# Send 'TATUS INBOX (MESSAGES)' ==============", sslstrm);
//			SendImapCommand("$ STATUS INBOX (MESSAGES)\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);
//			int number = 1;
//			strmlgw.WriteLine("# Send 'FETCH " + number.ToString() + " BODYSTRUCTURE' =======", sslstrm);
//			SendImapCommand("$ FETCH " + number + " bodystructure\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);
//			strmlgw.WriteLine("# Send 'FETCH " + number.ToString() + " BODY[HEADER]' ========", sslstrm);
//			SendImapCommand("$ FETCH " + number + " body[header]\r\n", sslstrm);
//			sRes = ReceiveImapRespons(sslstrm);
//			strmlgw.Write(sRes);

            strmlgw.WriteLine("# Send 'FETCH 1 body[text]' ==================", sslstrm);
            SendImapCommand("$ FETCH 1 body[text]\r\n", sslstrm);
            ReceiveMailBody(sDpath, tcpclnt, sslstrm);

            string sTempTimeSheetPath = ExtractAttachedFile(sDpath, sEpath);

            strmlgw.WriteLine("# Send 'LOGOUT' ==============================", sslstrm);
            SendImapCommand("$ LOGOUT\r\n", sslstrm);
            sRes = ReceiveImapRespons(sslstrm);
            strmlgw.Write(sRes);
            strmlgw.WriteLine("### END ======================================", sslstrm);

            strmlgw.Close(); strmlgw.Dispose();
            sslstrm.Close(); sslstrm.Dispose();
            tcpclnt.Close();

            File.Delete(sLpath);
            File.Delete(sDpath);

            return(sTempTimeSheetPath);
        }
 public AsyncSslIOAdapter(SslStream sslStream, CancellationToken cancellationToken)
 {
     _cancellationToken = cancellationToken;
     _sslStream         = sslStream;
 }
        public void Scan(BackgroundWorker _bgWorker, SParams parm)
        {
            bgWorker = _bgWorker;

            cur_cursor = 0;
            buffer     = "";

            ConsoleSetSection(3);
            ConsoleAppend("Scan started");
            ConsoleFlush(Color.Blue);

            // TCPCLIENT!! dla reszty testów


            string url = parm.base_url;

            int from = parm.test_mode;
            int to   = parm.test_mode;

            if (parm.test_mode == 18) // select all
            {
                from = 3;
                to   = 18;
            }

            for (int i = from; i <= to; i++) // tests
            {
                if (i == 18)                 // 'select all' test
                {
                    continue;
                }

                results[i].full_response = "";
                results[i].full_request  = "";
                results[i].response      = "";
                results[i].request       = "";

                url = parm.base_url;

                ConsoleSeparator(Color.Black);
                ConsoleAppend(parm.test_names[i - 3]);
                //ConsoleSetSection(1);
                ConsoleFlush(Color.Black);

                results[i].name = parm.test_names[i - 3];

                // USING WEBREQUEST
                // POST, GET, HEAD, wrongmethod, OPTIONS, TRACE, PUT
                //if (  (i == 13) )
                if (false) /// CAN DELETE THIS
                {
                    if ((i == 13) && (parm.put_uri != ""))
                    {
                        url = parm.put_uri;
                    }

                    if (url.Contains("https"))
                    {
                        AllowInvalidCertificate();
                    }

                    var request = (HttpWebRequest)WebRequest.Create(url);

                    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0";
                    request.Headers.Add("Accept-Language", "en-US");
                    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                    if (i == 7)
                    {
                        request.Method = WebRequestMethods.Http.Get;
                    }
                    else if (i == 6)
                    {
                        request.Method      = WebRequestMethods.Http.Post;
                        request.ContentType = "application/x-www-form-urlencoded";
                    }
                    else if (i == 14)
                    {
                        request.Method = WebRequestMethods.Http.Head;
                    }
                    else if (i == 11)
                    {
                        request.Method = "OPTIONS";
                    }
                    else if (i == 16)
                    {
                        request.Method = parm.wrongmethod_met;
                    }
                    else if (i == 9)
                    {
                        request.Method = "TRACE";
                    }
                    else if (i == 13)
                    {
                        request.Method      = WebRequestMethods.Http.Put;
                        request.ContentType = "application/octet-stream";
                    }

                    // request.Method = WebRequestMethods.Http.Put
                    //request.Method = WebRequestMethods.Http.Connect

                    request.KeepAlive   = false;
                    request.Proxy       = null;
                    request.Credentials = CredentialCache.DefaultCredentials;

                    if (i == 6) // post data
                    {
                        byte[] bytes = Encoding.ASCII.GetBytes(parm.post_data);
                        request.ContentLength = bytes.Length;

                        Stream stream = request.GetRequestStream();
                        stream.Write(bytes, 0, bytes.Length);
                        stream.Close();
                    }

                    if (i == 13) // put data
                    {
                        if (parm.put_path == "")
                        {
                            request.ContentLength = 0;
                        }
                        else
                        {
                            FileStream ReadIn = new FileStream(parm.put_path, FileMode.Open, FileAccess.Read);
                            ReadIn.Seek(0, SeekOrigin.Begin);
                            request.ContentLength = ReadIn.Length;
                            Byte[] FileData   = new Byte[ReadIn.Length];
                            int    DataRead   = 0;
                            Stream tempStream = request.GetRequestStream();
                            do
                            {
                                DataRead = ReadIn.Read(FileData, 0, (Math.Min(2048, (int)ReadIn.Length)));
                                if (DataRead > 0)
                                {
                                    tempStream.Write(FileData, 0, DataRead);
                                    Array.Clear(FileData, 0, DataRead);
                                }
                            } while (DataRead > 0);

                            ReadIn.Close();
                            tempStream.Close();
                        }
                    }

                    HttpStatusCode  status   = 0;
                    HttpWebResponse response = null;

                    string send4 = request.Method + " ";

                    if (url.Substring(0, 7) == "http://")
                    {
                        url = url.Substring(7, url.Length - 7);
                    }
                    else if (url.Substring(0, 8) == "https://")
                    {
                        url = url.Substring(8, url.Length - 8);
                    }

                    int c = url.Length;
                    for (int b = 0; b < url.Length; b++)
                    {
                        if (url[b] == '/')
                        {
                            c = b;
                            break;
                        }
                    }
                    if (c == url.Length)
                    {
                        url = "/";
                    }
                    else
                    {
                        url = url.Substring(c, url.Length - c);
                    }

                    //HttpUtility.UrlEncode(url)
                    send4 += HttpUtility.UrlPathEncode(url) + " HTTP/1.1";

                    ConsoleSetSection(1);
                    ConsoleAppend(send4);
                    ConsoleFlush(Color.SlateGray);

                    results[i].request = send4;

                    results[i].full_request = "";

                    try
                    {
                        response = (HttpWebResponse)request.GetResponse();

                        status = response.StatusCode;

                        Stream receiveStream = response.GetResponseStream();
                        // Encoding encode = System.Text.Encoding. GetEncoding("utf-8");
                        // Pipes the stream to a higher level stream reader with the required encoding format.
                        StreamReader readStream = new StreamReader(receiveStream);

                        results[i].full_response = readStream.ReadToEnd();
                        readStream.Close();

                        response.Close();
                    }
                    catch (WebException e)
                    {
                        if (e.Status == WebExceptionStatus.ProtocolError)
                        {
                            status = ((HttpWebResponse)e.Response).StatusCode;
                        }
                        //else
                        // e.Status.ToString();
                    }

                    int mt = ((int)status) / 100;

                    ConsoleSetSection(2);
                    ConsoleAppend(((int)status).ToString() + " " + status.ToString());

                    results[i].response = ((int)status).ToString() + " " + status.ToString();

                    if (mt == 2)
                    {
                        ConsoleFlush(Color.Green);
                    }
                    else if (mt == 4)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else if (mt == 5)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else
                    {
                        ConsoleFlush(Color.Black);
                    }
                }

                // USING TCPCLIENT
                // Fake End in URI, URI encoding, URI backslashes, Header multiple lines, HTTP wrong version,
                // CONNECT, PROPFIND, DELETE, POST, GET, OPTIONS
                // if ((i == 3) || (i == 4) || (i == 5) || (i == 6) || (i == 7) || (i == 8) || (i == 9)
                //    || (i == 11) || (i == 12) || (i == 14) || (i == 15) || (i==16) ||  (i == 17) || (i == 10))

                if (true)
                {
                    if ((i == 6) && (parm.post_uri != ""))
                    {
                        url = parm.post_uri;
                    }
                    else if ((i == 17) && (parm.propfind_uri != ""))
                    {
                        url = parm.propfind_uri;
                    }
                    else if ((i == 10) && (parm.delete_uri != ""))
                    {
                        url = parm.delete_uri;
                    }
                    else if ((i == 12) && (parm.connect_uri != ""))
                    {
                        url = parm.connect_uri;
                    }
                    else if ((i == 7) && (parm.get_uri != ""))
                    {
                        url = parm.get_uri;
                    }
                    else if ((i == 11) && (parm.options_uri != ""))
                    {
                        url = parm.options_uri;
                    }
                    else if ((i == 9) && (parm.trace_uri != ""))
                    {
                        url = parm.trace_uri;
                    }
                    else if ((i == 14) && (parm.head_uri != ""))
                    {
                        url = parm.head_uri;
                    }
                    else if ((i == 13) && (parm.put_uri != ""))
                    {
                        url = parm.put_uri;
                    }

                    bool is_https = false;
                    int  port     = 80;
                    if (url.Substring(0, 7) == "http://")
                    {
                        url = url.Substring(7, url.Length - 7);
                    }
                    else if (url.Substring(0, 8) == "https://")
                    {
                        url      = url.Substring(8, url.Length - 8);
                        is_https = true;
                        port     = 443;
                        AllowInvalidCertificate();
                    }

                    int c = url.Length;
                    for (int b = 0; b < url.Length; b++)
                    {
                        if (url[b] == '/')
                        {
                            c = b;
                            break;
                        }
                    }

                    string url2;
                    if (c == url.Length)
                    {
                        url2 = "/";
                    }
                    else
                    {
                        url2 = url.Substring(c, url.Length - c);
                    }
                    // /index.html

                    url = url.Substring(0, c); // www.site.com



                    //method
                    string send = "";

                    if (i == 12)
                    {
                        send += "CONNECT ";
                    }
                    else if (i == 17)
                    {
                        send += "PROPFIND ";
                    }
                    else if (i == 10)
                    {
                        send += "DELETE ";
                    }
                    else if (i == 6)
                    {
                        send += "POST ";
                    }
                    else if (i == 11)
                    {
                        send += "OPTIONS ";
                    }
                    else if (i == 9)
                    {
                        send += "TRACE ";
                    }
                    else if (i == 14)
                    {
                        send += "HEAD ";
                    }
                    else if (i == 16)
                    {
                        send += parm.wrongmethod_met + " ";
                    }
                    else if (i == 13)
                    {
                        send += "PUT ";
                    }
                    else
                    {
                        send += "GET ";
                    }

                    //URI
                    if (i == 3)
                    {
                        send += "/%20HTTP/1.1/../../ ";
                    }
                    else if (i == 4)
                    {
                        send += "/%2F ";// ??????????????????????
                    }
                    else if (i == 5)
                    {
                        send += "\\ ";
                    }
                    else if (i == 8)
                    {
                        send += "/ ";
                    }
                    else if (i == 15)
                    {
                        send += "/ ";
                    }
                    else if (i == 12)
                    {
                        send += url + " ";
                    }
                    else
                    {
                        send += url2 + " ";
                    }

                    //version
                    if (i == 15)
                    {
                        send += "HTTP/" + parm.wrongversion_ver;
                    }
                    else if (i == 5)
                    {
                        send += "HTTP\\1.1";
                    }
                    else
                    {
                        send += "HTTP/1.1";
                    }

                    ConsoleSetSection(1);
                    ConsoleAppend(send);
                    ConsoleFlush(Color.SlateGray);

                    results[i].request = send;

                    //newline
                    send += "\r\n";
                    if (i == 8)
                    {
                        send += "\r\n";
                    }

                    //

                    send += "Host: " + url + "\r\n";
                    send += "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0\r\n";
                    send += "Accept-Language: en-US\r\n";
                    send += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";

                    if (i == 6)
                    {
                        send += "Content-Type: application/x-www-form-urlencoded\r\n";
                        send += "Content-Length: " + System.Web.HttpUtility.UrlEncode(parm.post_data).Length.ToString() + "\r\n";
                        //send += "Expect: 100-continue\r\n";
                    }

                    Byte[] FileData      = null;
                    long   ContentLength = 0;

                    if (i == 13)
                    {
                        if (parm.put_path != "")
                        {
                            FileStream ReadIn = new FileStream(parm.put_path, FileMode.Open, FileAccess.Read);
                            ReadIn.Seek(0, SeekOrigin.Begin);
                            ContentLength = ReadIn.Length;
                            FileData      = new Byte[ReadIn.Length];
                            int DataRead = 0;
                            int offset   = 0;

                            int numBytesToRead = (int)ReadIn.Length;
                            int numBytesRead   = 0;
                            while (numBytesToRead > 0)
                            {
                                int n = ReadIn.Read(FileData, numBytesRead, numBytesToRead);

                                if (n == 0)
                                {
                                    break;
                                }

                                numBytesRead   += n;
                                numBytesToRead -= n;
                            }
                            numBytesToRead = (int)ReadIn.Length;

                            ReadIn.Close();
                        }
                        else
                        {
                            ContentLength = 0;
                        }

                        send += "Content-Type: application/octet-stream\r\n";
                        send += "Content-Length: " + ContentLength.ToString() + "\r\n";
                    }

                    send += "Connection: Close\r\n";
                    send += "\r\n";

                    if (i == 6)
                    {
                        send += System.Web.HttpUtility.UrlEncode(parm.post_data);
                    }
                    // if (i == 13)
                    // send += System.Text.Encoding.ASCII.GetString(FileData,0,(int)ContentLength);
                    //send += System.Text.Encoding.UTF8.GetString(FileData, 0, (int)ContentLength);
                    // send += BitConverter.ToString(FileData);
                    //BitConverter.

                    //results[i].full_request = send;

                    TcpClient tcp = new TcpClient(url, port);
                    tcp.SendTimeout    = 8000;
                    tcp.ReceiveTimeout = 8000;

                    StreamReader reader;
                    StreamWriter writer;
                    //SslStream gga= null;

                    SslStream     sstre = null;
                    NetworkStream nets  = null;

                    if (is_https)
                    {
                        sstre = new System.Net.Security.SslStream(tcp.GetStream(), true, allowCert, null);
                        sstre.AuthenticateAsClient(url);

                        reader = new StreamReader(sstre);
                        //writer = new StreamWriter(sstre);
                        //gga = sstre;
                    }
                    else
                    {
                        nets   = tcp.GetStream();
                        reader = new StreamReader(tcp.GetStream());
                        //writer = new StreamWriter(tcp.GetStream());
                    }

                    string respon = "";

                    byte[] sbyt = System.Text.Encoding.ASCII.GetBytes(send);

                    int    siz  = sbyt.Length + (int)ContentLength;
                    byte[] full = new byte[siz];
                    sbyt.CopyTo(full, 0);
                    if (FileData != null)
                    {
                        FileData.CopyTo(full, sbyt.Length);
                    }

                    results[i].full_request = System.Text.Encoding.ASCII.GetString(full, 0, siz);

                    try
                    {
                        if (is_https)
                        {
                            sstre.Write(full, 0, siz);
                            sstre.Flush();
                        }
                        else
                        {
                            nets.Write(full, 0, siz);
                            nets.Flush();
                        }
                        // writer.Write(send);

                        //writer.Flush();
                    }
                    catch (System.Net.Sockets.SocketException e)
                    {
                        respon = "ERROR";
                    }
                    catch (System.IO.IOException e2)
                    {
                        respon = "ERROR";
                    }

                    //char[] rbuff = null;
                    //rbuff = new char[2048];



                    try
                    {
                        string agg = reader.ReadToEnd();
                        //reader.Read(rbuff,0,2047);

                        results[i].full_response = agg;

                        bool t4   = false;
                        int  pos1 = 0;
                        int  pos2 = 0;
                        for (int h = 0; h < agg.Length; h++)
                        {
                            if (!t4)
                            {
                                if (agg[h] == ' ')
                                {
                                    pos1 = h + 1;
                                    t4   = true;
                                }
                            }
                            else
                            {
                                if ((agg[h] == '\r') || (agg[h] == '\n'))
                                {
                                    pos2   = h;
                                    respon = agg.Substring(pos1, pos2 - pos1);
                                    break;
                                }
                            }
                        }
                    }
                    catch (IOException e)
                    {
                        respon = "ERROR";
                    }

                    int mt = 4;
                    if ((respon != "") && (respon != "ERROR"))
                    {
                        mt = Convert.ToInt32(respon.Substring(0, 1));
                    }

                    //ConsoleSetSection(2);
                    //ConsoleAppend(((int)status).ToString() + " " + status.ToString());

                    ConsoleSetSection(2);
                    ConsoleAppend(respon);

                    results[i].response = respon;

                    if (mt == 2)
                    {
                        ConsoleFlush(Color.Green);
                    }
                    else if (mt == 4)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else if (mt == 5)
                    {
                        ConsoleFlush(Color.Red);
                    }
                    else
                    {
                        ConsoleFlush(Color.Black);
                    }
                }

                ConsoleSetSection(3);
                ConsoleAppend("Done.");
                //ConsoleNewline();
                ConsoleFlush(Color.Blue);

                if (bgWorker.CancellationPending == true)
                {
                    break;
                }
            }

            while (true)
            {
                if (a1.AddToConsoleStr.Count == 0)
                {
                    break;
                }

                Thread.Sleep(100);
            }
        }