Exemplo n.º 1
1
        public void PerformInitialHandshake(string hostName, X509CertificateCollection clientCertificates, System.Net.Security.RemoteCertificateValidationCallback remoteCertificateValidationCallback, bool checkCertificateRevocation)
        {
            if (_connState.CipherSuite != null || _pendingConnState != null || _closed)
                throw new InvalidOperationException("Already performed initial handshake");

            _hostName = hostName;
            _clientCertificates = clientCertificates;
            _remoteCertificationValidationCallback = remoteCertificateValidationCallback;
            _checkCertificateRevocation = checkCertificateRevocation;

            try
            {
                int offset = 0;
                SendHandshakeMessage(SendClientHello, ref offset, 0);
                _baseStream.Write(_buf, 0, offset);
                _baseStream.Flush();
                GetInitialHandshakeMessages();

                var keyExchange = _connState.CipherSuite.KeyExchange;
                if (keyExchange == KeyExchange.RSA || keyExchange == KeyExchange.ECDH_ECDSA || keyExchange == KeyExchange.ECDH_RSA)
                {
                    // Don't use false start for non-forward-secrecy key exchanges; we have to wait for the finished message and verify it

                    WaitForHandshakeCompleted(true);
                }
            }
            catch (ClientAlertException e)
            {
                WriteAlertFatal(e.Description);
                throw new IOException(e.ToString(), e);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Disable encryption certificate validation within PlayFabWebRequest using this request.
        /// This is not generally recommended.
        /// As of early 2018:
        ///   None of the built-in Unity mechanisms validate the certificate, using .Net 3.5 equivalent runtime
        ///   It is also not currently feasible to provide a single cross platform solution that will correctly validate a certificate.
        /// The Risk:
        ///   All Unity HTTPS mechanisms are vulnerable to Man-In-The-Middle attacks.
        ///   The only more-secure option is to define a custom CustomCertValidationHook, specifically tailored to the platforms you support,
        ///   which validate the cert based on a list of trusted certificate providers. This list of providers must be able to update itself, as the
        ///   base certificates for those providers will also expire and need updating on a regular basis.
        /// </summary>
        public static void SkipCertificateValidation()
        {
            var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true

            ServicePointManager.ServerCertificateValidationCallback = rcvc;
            certValidationSet = true;
        }
Exemplo n.º 3
0
        public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection = new TcpClient(hostname, port);
                _Stream     = _Connection.GetStream();
                if (ssl)
                {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    }
                    else
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    }
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(hostname);
                }

                OnConnected(GetResponse());

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
        public static TransportSettings CreateTcpTransportSettings(
            string networkHost,
            string hostName,
            int port,
            bool useSslStreamSecurity,
            bool sslStreamUpgrade = false,
            string sslHostName    = null,
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate            = null,
            System.Net.Security.RemoteCertificateValidationCallback certificateValidationCallback = null)
        {
            TcpTransportSettings tcpSettings = new TcpTransportSettings
            {
                Host = networkHost,
                Port = port < 0 ? AmqpConstants.DefaultSecurePort : port,
                ReceiveBufferSize = AmqpConstants.TransportBufferSize,
                SendBufferSize    = AmqpConstants.TransportBufferSize
            };

            TransportSettings tpSettings = tcpSettings;

            if (useSslStreamSecurity && !sslStreamUpgrade)
            {
                TlsTransportSettings tlsSettings = new TlsTransportSettings(tcpSettings)
                {
                    TargetHost  = sslHostName ?? hostName,
                    Certificate = certificate,
                    CertificateValidationCallback = certificateValidationCallback
                };
                tpSettings = tlsSettings;
            }

            return(tpSettings);
        }
Exemplo n.º 5
0
        public static AmqpSettings CreateAmqpSettings(
            Version amqpVersion,
            bool useSslStreamSecurity,
            bool hasTokenProvider,
            string sslHostName    = null,
            bool useWebSockets    = false,
            bool sslStreamUpgrade = false,
            System.Net.NetworkCredential networkCredential = null,
            System.Net.Security.RemoteCertificateValidationCallback certificateValidationCallback = null,
            bool forceTokenProvider = true)
        {
            AmqpSettings settings = new AmqpSettings();

            if (useSslStreamSecurity && !useWebSockets && sslStreamUpgrade)
            {
                var tlsSettings = new TlsTransportSettings
                {
                    CertificateValidationCallback = certificateValidationCallback,
                    TargetHost = sslHostName
                };

                var tlsProvider = new TlsTransportProvider(tlsSettings);
                tlsProvider.Versions.Add(new AmqpVersion(amqpVersion));
                settings.TransportProviders.Add(tlsProvider);
            }

            if (hasTokenProvider || networkCredential != null)
            {
                SaslTransportProvider saslProvider = new SaslTransportProvider();
                saslProvider.Versions.Add(new AmqpVersion(amqpVersion));
                settings.TransportProviders.Add(saslProvider);

                if (forceTokenProvider)
                {
                    saslProvider.AddHandler(new SaslAnonymousHandler(CbsSaslMechanismName));
                }
                else if (networkCredential != null)
                {
                    var plainHandler = new SaslPlainHandler
                    {
                        AuthenticationIdentity = networkCredential.UserName,
                        Password = networkCredential.Password
                    };
                    saslProvider.AddHandler(plainHandler);
                }
                else
                {
                    // old client behavior: keep it for validation only
                    saslProvider.AddHandler(new SaslExternalHandler());
                }
            }

            AmqpTransportProvider amqpProvider = new AmqpTransportProvider();

            amqpProvider.Versions.Add(new AmqpVersion(amqpVersion));
            settings.TransportProviders.Add(amqpProvider);

            return(settings);
        }
Exemplo n.º 6
0
 public CertificateIgnorer()
 {
     oldCallback = ServicePointManager.ServerCertificateValidationCallback;
     ServicePointManager.ServerCertificateValidationCallback = delegate(
         Object obj, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors)
     {
         return(true);
     };
 }
Exemplo n.º 7
0
 public virtual void Connect(string hostname, int port, bool ssl, bool skipSslValidation)
 {
     System.Net.Security.RemoteCertificateValidationCallback validateCertificate = null;
     if (skipSslValidation)
     {
         validateCertificate = (sender, cert, chain, err) => true;
     }
     Connect(hostname, port, ssl, validateCertificate);
 }
Exemplo n.º 8
0
 public SslHandShake(string hostName, System.Security.Authentication.SslProtocols sslProtocol, System.Net.Security.RemoteCertificateValidationCallback serverCallback, System.Net.Security.LocalCertificateSelectionCallback clientCallback, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, bool checkRevocation)
 {
     _hostName           = hostName;
     _sslProtocol        = sslProtocol;
     _serverCallback     = serverCallback;
     _clientCallback     = clientCallback;
     _clientCertificates = clientCertificates;
     _checkRevocation    = checkRevocation;
 }
        /// <summary>
        /// Configure validation delegate for remote certificate validation callback.
        /// </summary>
        public LdapConnectionOptions ConfigureRemoteCertificateValidationCallback(
            System.Net.Security.RemoteCertificateValidationCallback remoteCertificateValidationCallback)
        {
            RemoteCertificateValidationCallback = remoteCertificateValidationCallback ??
                                                  throw new ArgumentNullException(
                                                            nameof(remoteCertificateValidationCallback));

            return(this);
        }
Exemplo n.º 10
0
        private void SetupCertificates()
        {
            // These are performance Optimizations for HttpWebRequests.
            ServicePointManager.DefaultConnectionLimit = 10;
            ServicePointManager.Expect100Continue = false;

            //Support for SSL
            var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true
            ServicePointManager.ServerCertificateValidationCallback = rcvc;
        }
        public HttpRequestApi()
        {
            _isApplicationPlaying = true;
            ServicePointManager.DefaultConnectionLimit = 10;
            ServicePointManager.Expect100Continue      = false;

            var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            ServicePointManager.ServerCertificateValidationCallback = rcvc;
        }
Exemplo n.º 12
0
        private void SetupCertificates()
        {
            // These are performance Optimizations for HttpWebRequests.
            ServicePointManager.DefaultConnectionLimit = 10;
            ServicePointManager.Expect100Continue      = false;

            //Support for SSL
            var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true

            ServicePointManager.ServerCertificateValidationCallback = rcvc;
        }
Exemplo n.º 13
0
 public string DELETE(string url, Func <SSLVerificationEvent, bool> verifySSLcallback)
 {
     using (WebClient client = new WebClient()) {
         System.Net.Security.RemoteCertificateValidationCallback verifyssl = (sender, cert, chain, errors) => verifySSLcallback.Invoke(new SSLVerificationEvent(cert, chain, errors));
         System.Net.ServicePointManager.ServerCertificateValidationCallback += verifyssl;
         client.Headers[HttpRequestHeader.UserAgent] = UserAgent;
         string result = client.UploadString(url, "DELETE", "");
         System.Net.ServicePointManager.ServerCertificateValidationCallback -= verifyssl;
         return(result);
     }
 }
Exemplo n.º 14
0
 public string PATCH(string url, string data, Func <SSLVerificationEvent, bool> verifySSLcallback)
 {
     using (WebClient client = new WebClient()) {
         System.Net.Security.RemoteCertificateValidationCallback verifyssl = (sender, cert, chain, errors) => verifySSLcallback.Invoke(new SSLVerificationEvent(cert, chain, errors));
         System.Net.ServicePointManager.ServerCertificateValidationCallback += verifyssl;
         client.Headers[HttpRequestHeader.UserAgent]   = UserAgent;
         client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         string result = client.UploadString(url, "PATCH", data);
         System.Net.ServicePointManager.ServerCertificateValidationCallback -= verifyssl;
         return(result);
     }
 }
Exemplo n.º 15
0
        public void Awake()
        {
#if !UNITY_WP8
            // These are performance Optimizations for HttpWebRequests.
            ServicePointManager.DefaultConnectionLimit = 10;
            ServicePointManager.Expect100Continue      = false;

            //Support for SSL
            var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            ServicePointManager.ServerCertificateValidationCallback = rcvc;
#endif
        }
Exemplo n.º 16
0
        public virtual void Connect(string hostname, int port, bool ssl, System.Net.Security.RemoteCertificateValidationCallback validateCertificate)
        {
            try {
                Host = hostname;
                Port = port;
                Ssl  = ssl;

                _Connection.SendTimeout    = this.Timeout;
                _Connection.ReceiveTimeout = this.Timeout;
                IAsyncResult ar = _Connection.BeginConnect(hostname, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(this.Timeout), true))
                    {
                        throw new TimeoutException(string.Format("Could not connect to {0} on port {1}.", hostname, port));
                    }
                    _Connection.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }
                _Stream = _Connection.GetStream();
                if (ssl)
                {
                    System.Net.Security.SslStream sslStream;
                    if (validateCertificate != null)
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false, validateCertificate);
                    }
                    else
                    {
                        sslStream = new System.Net.Security.SslStream(_Stream, false);
                    }
                    _Stream = sslStream;
                    sslStream.AuthenticateAsClient(hostname);
                }

                OnConnected(GetResponse());

                IsConnected = true;
                Host        = hostname;
            } catch (Exception) {
                IsConnected = false;
                Utilities.TryDispose(ref _Stream);
                throw;
            }
        }
        static StackObject *set_ServerCertificateValidationCallback_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Net.Security.RemoteCertificateValidationCallback @value = (System.Net.Security.RemoteCertificateValidationCallback) typeof(System.Net.Security.RemoteCertificateValidationCallback).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);


            System.Net.ServicePointManager.ServerCertificateValidationCallback = value;

            return(__ret);
        }
Exemplo n.º 18
0
    internal static WsStream CreateClientStream (
      TcpClient client,
      bool secure,
      string host,
      System.Net.Security.RemoteCertificateValidationCallback validationCallback)
    {
      var netStream = client.GetStream ();
      if (secure) {
        if (validationCallback == null)
          validationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

        var sslStream = new SslStream (netStream, false, validationCallback);
        sslStream.AuthenticateAsClient (host);

        return new WsStream (sslStream);
      }

      return new WsStream (netStream);
    }
Exemplo n.º 19
0
        private static HttpClient SetUpHttpClient()
        {
            // Even with cert errors we go all in
            //https://docs.microsoft.com/en-us/dotnet/api/system.net.security.remotecertificatevalidationcallback
            System.Net.Security.RemoteCertificateValidationCallback p = (sender, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.ServerCertificateValidationCallback += p;
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
            var httpClientHandler = new HttpClientHandler
            {
                CheckCertificateRevocationList = false,
                AllowAutoRedirect = false
            };
            var _httpClient = new HttpClient(httpClientHandler)
            {
                Timeout = new TimeSpan(0, 0, 10)
            };

            return(_httpClient);
        }
Exemplo n.º 20
0
        internal static WsStream CreateClientStream(TcpClient client, string host, bool secure)
        {
            var netStream = client.GetStream();

            if (secure)
            {
                System.Net.Security.RemoteCertificateValidationCallback validationCb = (sender, certificate, chain, sslPolicyErrors) =>
                {
                    // FIXME: Always returns true
                    return(true);
                };

                var sslStream = new SslStream(netStream, false, validationCb);
                sslStream.AuthenticateAsClient(host);

                return(new WsStream(sslStream));
            }

            return(new WsStream(netStream));
        }
Exemplo n.º 21
0
    public static void Main(string [] args)
    {
        mIgnoreInvalidCertificates = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return(true); });
        MagentoService mageService = new MagentoService();
        string         mageSession = null;

        if (args.Length < 3)
        {
            Console.WriteLine("Usage; ListOrders apiUser apiKey status [processing|complete|pending]");
            return;
        }

        try {
            _apiUser        = args[0];
            _apiKey         = args[1];
            _orderToInvoice = args[2];
            Console.WriteLine("Connecting to " + mageService.Url);
            if (_beSecure)                  //require secure communications
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback -= mIgnoreInvalidCertificates;
                Console.WriteLine("Requiring Valid Certificates from Remote Sites");
            }
            else                 /// Allow connections to SSL sites that have unsafe certificates.
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback += mIgnoreInvalidCertificates;
                Console.WriteLine("Ignoring Invalid Certificates from Remote Sites");
            }
            mageSession = mageService.login(_apiUser, _apiKey);
        }
        catch (Exception ex) {
            Console.WriteLine("Login failed: \"" + ex.Message + "\"\n");
            return;
        }

        try {
            salesOrderEntity      orderDetail = mageService.salesOrderInfo(mageSession, _orderToInvoice);
            List <orderItemIdQty> invoiceInfo = new List <orderItemIdQty>();
            foreach (salesOrderItemEntity li in orderDetail.items)
            {
                Console.WriteLine("Item:" + li.item_id + " Qty:" + li.qty_ordered + " (" + li.name + ")");
                orderItemIdQty invoiceLineItem = new orderItemIdQty();
                invoiceLineItem.order_item_id = Convert.ToInt32(li.item_id);
                invoiceLineItem.qty           = Convert.ToDouble(li.qty_ordered);
                invoiceInfo.Add(invoiceLineItem);
                if (_wantXml)
                {
                    System.Xml.Serialization.XmlSerializer xmlLineItemDetail =
                        new System.Xml.Serialization.XmlSerializer(li.GetType());
                    xmlLineItemDetail.Serialize(Console.Out, li);
                    Console.WriteLine();
                }
            }
            orderItemIdQty[] invoiceQtys = invoiceInfo.ToArray();

            /* Create an invoice, and then capture it. Although we are reporting errors,
             *      we don't do anything about them, Nor do we stop processing.
             */
            try {
                string invoiceIncrementId = mageService.salesOrderInvoiceCreate(mageSession, _orderToInvoice,
                                                                                invoiceQtys, "Invoiced via API", "1", "1");
                try {
                    mageService.salesOrderInvoiceCapture(mageSession, invoiceIncrementId);
                }
                catch (Exception ex) {
                    Console.WriteLine("Invoice Capture Error: \"" + ex.Message + "\"");
                }
            }
            catch (Exception ex) {
                Console.WriteLine("Invoice Create Error: \"" + ex.Message + "\"");
            }

            // Create the shipment, and add tracking for it. Similar to invoicing, we don't stop for errors.
            try {
                string shipmentIncrementId = mageService.salesOrderShipmentCreate(mageSession, _orderToInvoice, invoiceQtys,
                                                                                  "Shipment via API", 1, 1);

                associativeEntity[] validCarriers = mageService.salesOrderShipmentGetCarriers(mageSession, _orderToInvoice);
                if (_wantXml)
                {
                    System.Xml.Serialization.XmlSerializer xmlValidCarriers =
                        new System.Xml.Serialization.XmlSerializer(validCarriers.GetType());
                    xmlValidCarriers.Serialize(Console.Out, validCarriers);
                    Console.WriteLine();
                }
                try {
                    mageService.salesOrderShipmentAddTrack(mageSession, shipmentIncrementId, "ups", "Schiff UPS Shipping", "1Z9999999999999999");
                }
                catch (Exception ex) {
                    Console.WriteLine("Add Shipment Tracking Error: \"" + ex.Message + "\"");
                }
            }
            catch (Exception ex) {
                Console.WriteLine("Shipment Create Error: \"" + ex.Message + "\"");
            }

            /* Assuming everything went well (which we do ASSume), this order has been Imported into ERP, Invoiced,
             *      Captured, and Shipped Complete.
             */
            mageService.salesOrderAddComment(mageSession, _orderToInvoice, "complete", "Order Completed via API", "0");
            mageService.endSession(mageSession);
        }
        catch (Exception ex) {
            Console.WriteLine("Error: \"" + ex.Message + "\"\n");
        }
    }
Exemplo n.º 22
0
 public SslHandShake(string hostName, System.Security.Authentication.SslProtocols sslProtocol, System.Net.Security.RemoteCertificateValidationCallback serverCallback) : this(hostName, sslProtocol, serverCallback, null, null, false)
 {
 }
Exemplo n.º 23
0
 public SslHandShake(string hostName, System.Security.Authentication.SslProtocols sslProtocol, System.Net.Security.RemoteCertificateValidationCallback serverCallback, System.Net.Security.LocalCertificateSelectionCallback clientCallback, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates) : this(hostName, sslProtocol, serverCallback, clientCallback, clientCertificates, false)
 {
 }
Exemplo n.º 24
0
        /// <summary>
        /// Consulta situação do MDFe
        /// </summary>
        /// <param name="idManifestoEletronico"></param>
        public static string ConsultaSitMDFe(int idManifestoEletronico)
        {
            // Busca dados do Manifesto Eletronico
            var mdfe = ManifestoEletronicoDAO.Instance.ObterManifestoEletronicoPeloId(idManifestoEletronico);

            #region Monta XML

            XmlDocument xmlConsSitMDFe  = new XmlDocument();
            XmlNode     declarationNode = xmlConsSitMDFe.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlConsSitMDFe.AppendChild(declarationNode);

            XmlElement consSitMDFe = xmlConsSitMDFe.CreateElement("consSitMDFe");
            consSitMDFe.SetAttribute("xmlns", "http://www.portalfiscal.inf.br/mdfe");
            consSitMDFe.SetAttribute("versao", ConfigMDFe.VersaoConsulta);
            xmlConsSitMDFe.AppendChild(consSitMDFe);

            ManipulacaoXml.SetNode(xmlConsSitMDFe, consSitMDFe, "tpAmb", ((int)ConfigMDFe.TipoAmbiente).ToString());
            ManipulacaoXml.SetNode(xmlConsSitMDFe, consSitMDFe, "xServ", "CONSULTAR");
            ManipulacaoXml.SetNode(xmlConsSitMDFe, consSitMDFe, "chMDFe", mdfe.ChaveAcesso);

            #endregion

            #region Valida XML

            //try
            //{
            //    ValidaXML.Validar(xmlConsSitMDFe, ValidaXML.TipoArquivoXml.ConsultaSituacaoMDFe);
            //}
            //catch (Exception ex)
            //{
            //    throw new Exception("XML inconsistente." + ex.Message);
            //}

            #endregion

            // Salva o callback padrão do WebService
            System.Net.Security.RemoteCertificateValidationCallback callback = System.Net.ServicePointManager.ServerCertificateValidationCallback;

            XmlNode xmlRetorno = null;

            try
            {
                // Altera o callback de validação do WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
                {
                    // Verifica se a data do certificado é válida
                    DateTime beginDate   = DateTime.Parse(cert.GetEffectiveDateString());
                    DateTime endDate     = DateTime.Parse(cert.GetExpirationDateString());
                    bool     isDateValid = (DateTime.Now >= beginDate) && (DateTime.Now <= endDate);

                    // Retorna o resultado da função
                    return(isDateValid);
                };

                #region Envia o arquivo e recebe o retorno

                if (mdfe.TipoEmissao == Glass.Data.Model.TipoEmissao.Normal)
                {
                    if (ConfigMDFe.TipoAmbiente == ConfigMDFe.TipoAmbienteMDFe.Producao)
                    {
                        xmlRetorno = GetWebService.PSVRSMDFeConsulta(mdfe, null).mdfeConsultaMDF(xmlConsSitMDFe);
                    }
                    // TipoAmbienteMDFe.Homologacao
                    else
                    {
                        xmlRetorno = GetWebService.HSVRSMDFeConsulta(mdfe, null).mdfeConsultaMDF(xmlConsSitMDFe);
                    }
                }
                // TipoEmissao.Contingencia
                else
                {
                    if (ConfigMDFe.TipoAmbiente == ConfigMDFe.TipoAmbienteMDFe.Producao)
                    {
                        xmlRetorno = GetWebService.PSVRSMDFeConsulta(mdfe, null).mdfeConsultaMDF(xmlConsSitMDFe);
                    }
                    // TipoAmbienteMDFe.Homologacao
                    else
                    {
                        xmlRetorno = GetWebService.HSVRSMDFeConsulta(mdfe, null).mdfeConsultaMDF(xmlConsSitMDFe);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception(Glass.MensagemAlerta.FormatErrorMsg("Falha ao chamar WebService.", ex));
            }
            finally
            {
                // Restaura o callback padrão para o WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = callback;
            }

            // Executa ações de acordo com o retorno
            return(ManifestoEletronicoDAO.Instance.RetornoConsSitMDFe(idManifestoEletronico, xmlRetorno));
        }
 public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy) : base(innerStream, leaveInnerStreamOpen)
 {
 }
 public SslStream(System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback) : base(innerStream, leaveInnerStreamOpen)
 {
 }
Exemplo n.º 27
0
        /// <summary>
        /// Consulta situação do Lote de MDFe (método acionado pelo usuário)
        /// </summary>
        /// <param name="idManifestoEletronico"></param>
        /// <returns></returns>
        public static string ConsultaSitLoteMDFe(int idManifestoEletronico)
        {
            var mdfe      = ManifestoEletronicoDAO.Instance.ObterManifestoEletronicoPeloId(idManifestoEletronico);
            var protocolo = ProtocoloMDFeDAO.Instance.GetElement(idManifestoEletronico, (int)ProtocoloMDFe.TipoProtocoloEnum.Autorizacao);

            #region Monta XML de requisição de situação do lote

            if (protocolo == null || string.IsNullOrEmpty(protocolo.NumRecibo))
            {
                throw new Exception("O MDFe não foi emitido. Não há número de recibo.");
            }

            string strXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                            "<consReciMDFe xmlns=\"http://www.portalfiscal.inf.br/mdfe\" " +
                            "versao=\"" + ConfigMDFe.VersaoRecepcao + "\">" +
                            "<tpAmb>" + (int)ConfigMDFe.TipoAmbiente + "</tpAmb>" +
                            "<nRec>" + protocolo.NumRecibo.PadLeft(15, '0') + "</nRec></consReciMDFe>";

            XmlDocument xmlRetRecep = new XmlDocument();
            xmlRetRecep.LoadXml(strXml);

            #endregion

            #region Valida XML

            try
            {
                ValidaXML.Validar(xmlRetRecep, ValidaXML.TipoArquivoXml.ConsultaRecibo);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            #endregion

            // Guarda o status do lote
            var cStat   = 0;
            var xMotivo = string.Empty;

            XmlNode xmlRetorno = null;

            // Salva o callback padrão do WebService
            System.Net.Security.RemoteCertificateValidationCallback callback = System.Net.ServicePointManager.ServerCertificateValidationCallback;

            try
            {
                // Altera o callback de validação do WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
                {
                    // Verifica se a data do certificado é válida
                    DateTime beginDate   = DateTime.Parse(cert.GetEffectiveDateString());
                    DateTime endDate     = DateTime.Parse(cert.GetExpirationDateString());
                    bool     isDateValid = (DateTime.Now >= beginDate) && (DateTime.Now <= endDate);

                    // Retorna o resultado da função
                    return(isDateValid);
                };

                #region Envia o arquivo e recebe o retorno

                if (mdfe.TipoEmissao == Glass.Data.Model.TipoEmissao.Normal)
                {
                    if (ConfigMDFe.TipoAmbiente == ConfigMDFe.TipoAmbienteMDFe.Producao)
                    {
                        xmlRetorno = GetWebService.PSVRSMDFeRetornoRecepcao(mdfe, null).mdfeRetRecepcao(xmlRetRecep);
                    }
                    // TipoAmbienteMDFe.Homologacao
                    else
                    {
                        xmlRetorno = GetWebService.HSVRSMDFeRetornoRecepcao(mdfe, null).mdfeRetRecepcao(xmlRetRecep);
                    }
                }
                // TipoEmissao.Contingencia
                else
                {
                    if (ConfigMDFe.TipoAmbiente == ConfigMDFe.TipoAmbienteMDFe.Producao)
                    {
                        xmlRetorno = GetWebService.PSVRSMDFeRetornoRecepcao(mdfe, null).mdfeRetRecepcao(xmlRetRecep);
                    }
                    // TipoAmbienteMDFe.Homologacao
                    else
                    {
                        xmlRetorno = GetWebService.HSVRSMDFeRetornoRecepcao(mdfe, null).mdfeRetRecepcao(xmlRetRecep);
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception(Glass.MensagemAlerta.FormatErrorMsg("Falha ao chamar WebService.", ex));
            }
            finally
            {
                // Restaura o callback padrão para o WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = callback;
            }

            // Se o lote já tiver sido processado, sai do loop
            if (xmlRetorno != null) // Lote processado
            {
                cStat   = Conversoes.StrParaInt(xmlRetorno["cStat"].InnerXml);
                xMotivo = xmlRetorno["xMotivo"].InnerXml;
            }

            // Verifica o status do lote
            if (cStat == 104) // Lote processado
            {
                XmlNodeList protMDFeList = ((XmlElement)xmlRetorno).GetElementsByTagName("protMDFe");

                // Para cada protocolo de autorização de uso (inicialmente será só um, pois cada nota está sendo enviada em um lote distinto)
                foreach (XmlNode protMDFeNode in protMDFeList)
                {
                    return(ManifestoEletronicoDAO.Instance.RetornoEmissaoMDFe(idManifestoEletronico, protMDFeNode));
                }

                return("Lote processado");
            }
            else if (cStat == 105) // Lote em processamento
            {
                if (mdfe.Situacao != SituacaoEnum.ContingenciaOffline)
                {
                    ManifestoEletronicoDAO.Instance.AlteraSituacao(idManifestoEletronico, SituacaoEnum.ProcessoEmissao);
                }

                return("Este MDFe ainda está sendo processado pela SEFAZ, aguarde para realizar uma nova consulta.");
            }
            else if (cStat == 106) // Lote não encontrado
            {
                if (mdfe.Situacao != SituacaoEnum.ContingenciaOffline)
                {
                    ManifestoEletronicoDAO.Instance.AlteraSituacao(idManifestoEletronico, SituacaoEnum.FalhaEmitir);
                }

                LogMDFeDAO.Instance.NewLog(idManifestoEletronico, "Consulta", cStat, "Falha na emissão do MDFe. " + xMotivo);

                return("Falha na consulta. Não foi encontrado o lote de envio.");
            }
            else // Lote rejeitado
            {
                if (mdfe.Situacao != SituacaoEnum.ContingenciaOffline)
                {
                    ManifestoEletronicoDAO.Instance.AlteraSituacao(idManifestoEletronico, SituacaoEnum.FalhaEmitir);
                }

                LogMDFeDAO.Instance.NewLog(idManifestoEletronico, "Consulta", cStat, xMotivo);

                string msgErro = "Falha na consulta. ";

                if (cStat == 215 || cStat == 243 || cStat == 630)
                {
                    msgErro += "Mensagem de consulta inválida. ";
                }

                return(msgErro + cStat + " - " + CustomizaMensagemRejeicao(idManifestoEletronico, xMotivo));
            }
        }
Exemplo n.º 28
0
        private static string ConsultaLoteNFe(NotaFiscal nf)
        {
            #region Monta XML de requisição de situação do lote

            if (string.IsNullOrEmpty(nf.NumRecibo))
            {
                throw new Exception("A NFe não foi emitida. Não há número de recibo.");
            }

            var strXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                         "<consReciNFe xmlns=\"http://www.portalfiscal.inf.br/nfe\" " +
                         "versao=\"" + ConfigNFe.VersaoRetAutorizacao + "\">" +
                         "<tpAmb>" + (int)ConfigNFe.TipoAmbiente + "</tpAmb>" +
                         "<nRec>" + nf.NumRecibo.PadLeft(15, '0') + "</nRec></consReciNFe>";

            XmlDocument xmlRetRecep = new XmlDocument();
            xmlRetRecep.LoadXml(strXml);

            try
            {
                ValidaXML.Validar(xmlRetRecep, ValidaXML.TipoArquivoXml.RetRecepcao);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            #endregion

            var     status     = string.Empty;
            XmlNode xmlRetorno = null;
            System.Net.Security.RemoteCertificateValidationCallback callback = System.Net.ServicePointManager.ServerCertificateValidationCallback;

            try
            {
                // Altera o callback de validação do WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
                {
                    // Verifica se a data do certificado é válida
                    DateTime beginDate   = DateTime.Parse(cert.GetEffectiveDateString());
                    DateTime endDate     = DateTime.Parse(cert.GetExpirationDateString());
                    bool     isDateValid = (DateTime.Now >= beginDate) && (DateTime.Now <= endDate);

                    // Retorna o resultado da função
                    return(isDateValid);
                };

                // Envia o arquivo e recebe o retorno
                xmlRetorno = EnviaXML.ObterXmlRetornoAutorizacaoNFe(nf, xmlRetRecep);
            }
            catch (Exception ex)
            {
                LogNfDAO.Instance.NewLog(nf.IdNf, "Instaciar Webservice", 3, MensagemAlerta.FormatErrorMsg("Falha ao instanciar webservice.", ex));
                throw new Exception(Glass.MensagemAlerta.FormatErrorMsg("Falha ao chamar WebService.", ex));
            }
            finally
            {
                // Restaura o callback padrão para o WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = callback;
            }

            // Se o lote já tiver sido processado, sai do loop
            if (xmlRetorno != null) // Lote processado
            {
                status = xmlRetorno?["cStat"]?.InnerXml;
            }

            if (status == "104") // Lote processado
            {
                XmlNodeList protNFeList = ((XmlElement)xmlRetorno).GetElementsByTagName("protNFe");

                // Para cada protocolo de autorização de uso (inicialmente será só um, pois cada nota está sendo enviada em um lote distinto)
                foreach (XmlNode protNFeNode in protNFeList)
                {
                    NotaFiscalDAO.Instance.RetornoEmissaoNFe(protNFeNode?["infProt"]?["chNFe"]?.InnerXml, protNFeNode);

                    var statusNFe = protNFeNode?["infProt"]?["cStat"]?.InnerXml;

                    if (statusNFe == "100" || statusNFe == "150") // Autorizada para uso
                    {
                        return("NFe está autorizada para uso.");
                    }
                    else
                    {
                        return($"NFe rejeitada. Motivo: { protNFeNode?["infProt"]?["xMotivo"]?.InnerXml }");
                    }
                }

                return("Lote processado");
            }
            else if (status == "105") // Lote em processamento
            {
                NotaFiscalDAO.Instance.AlteraSituacao(nf.IdNf, NotaFiscal.SituacaoEnum.ProcessoEmissao);

                return("Esta NFe ainda está sendo processada pela SEFAZ, aguarde para realizar uma nova consulta.");
            }
            else if (status == "106") // Lote não encontrado
            {
                NotaFiscalDAO.Instance.AlteraSituacao(nf.IdNf, NotaFiscal.SituacaoEnum.FalhaEmitir);

                LogNfDAO.Instance.NewLog(nf.IdNf, "Consulta", 106, "Falha na emissão da NFe. Não foi encontrado o lote de envio.");

                return("Falha na consulta. Não foi encontrado o lote de envio.");
            }
            else // Lote rejeitado
            {
                NotaFiscalDAO.Instance.AlteraSituacao(nf.IdNf, NotaFiscal.SituacaoEnum.FalhaEmitir);

                LogNfDAO.Instance.NewLog(nf.IdNf, "Consulta", (xmlRetorno?["cStat"]?.InnerXml?.StrParaInt()).GetValueOrDefault(), xmlRetorno?["xMotivo"]?.InnerXml);

                var msgErro = "Falha na consulta. ";

                if (status == "215" || status == "516" || status == "517" || status == "545")
                {
                    msgErro += "Mensagem de consulta inválida. ";
                }
                else if (status == "225" || status == "565" || status == "567" || status == "568")
                {
                    msgErro += "Lote da NFe é inválido. ";
                }

                return($"{ msgErro }{ xmlRetorno?["cStat"]?.InnerXml } - { CustomizaMensagemRejeicao(nf.IdNf, xmlRetorno?["xMotivo"]?.InnerXml) }");
            }
        }
Exemplo n.º 29
0
        private static string ConsultaSitNFCe(NotaFiscal nf)
        {
            #region Monta XML

            XmlDocument xmlConsSitNFe   = new XmlDocument();
            XmlNode     declarationNode = xmlConsSitNFe.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlConsSitNFe.AppendChild(declarationNode);

            XmlElement consSitNFe = xmlConsSitNFe.CreateElement("consSitNFe");
            consSitNFe.SetAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");
            consSitNFe.SetAttribute("versao", ConfigNFe.VersaoConsulta);
            xmlConsSitNFe.AppendChild(consSitNFe);

            ManipulacaoXml.SetNode(xmlConsSitNFe, consSitNFe, "tpAmb", ((int)ConfigNFe.TipoAmbiente).ToString());
            ManipulacaoXml.SetNode(xmlConsSitNFe, consSitNFe, "xServ", "CONSULTAR");
            ManipulacaoXml.SetNode(xmlConsSitNFe, consSitNFe, "chNFe", nf.ChaveAcesso);

            #endregion

            // Salva o callback padrão do WebService
            System.Net.Security.RemoteCertificateValidationCallback callback = System.Net.ServicePointManager.ServerCertificateValidationCallback;

            XmlNode xmlRetorno = null;

            try
            {
                // Altera o callback de validação do WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
                {
                    // Verifica se a data do certificado é válida
                    DateTime beginDate   = DateTime.Parse(cert.GetEffectiveDateString());
                    DateTime endDate     = DateTime.Parse(cert.GetExpirationDateString());
                    bool     isDateValid = (DateTime.Now >= beginDate) && (DateTime.Now <= endDate);

                    // Retorna o resultado da função
                    return(isDateValid);
                };

                // Envia o arquivo e recebe o retorno.
                xmlRetorno = EnviaXML.ObterXmlConsultaProtocoloNFCe(nf, xmlConsSitNFe);
            }
            catch (Exception ex)
            {
                LogNfDAO.Instance.NewLog(nf.IdNf, "Instaciar Webservice", 3, MensagemAlerta.FormatErrorMsg("Falha ao instanciar webservice.", ex));
                throw new Exception(Glass.MensagemAlerta.FormatErrorMsg("Falha ao chamar WebService.", ex));
            }
            finally
            {
                // Restaura o callback padrão para o WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = callback;
            }

            if (xmlRetorno == null)
            {
                throw new Exception("Falha ao comunicar com webservice da SEFAZ.");
            }

            var codStatus = xmlRetorno?["cStat"]?.InnerXml;

            // Executa ações de acordo com o retorno dado
            NotaFiscalDAO.Instance.RetornoConsSitNFe(nf.IdNf, xmlRetorno);

            if (codStatus == "100" || codStatus == "150") // NFe Autorizada
            {
                return("NFe está autorizada para uso.");
            }
            else // NFe rejeitada
            {
                var msgErro = "Falha na consulta. ";

                if (codStatus == "215" || codStatus == "516" || codStatus == "517" || codStatus == "545")
                {
                    msgErro += "Mensagem de consulta inválida. ";
                }

                return($"{ msgErro }{ xmlRetorno?["cStat"]?.InnerXml } - { CustomizaMensagemRejeicao(nf.IdNf, xmlRetorno?["xMotivo"]?.InnerXml) }");
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Consulta o cadastro de contribuintes do ICMS da unidade federada.
        /// </summary>
        public static string ConsultaSitCadastroContribuinte(string uf, string cpfCnpj)
        {
            if (string.IsNullOrEmpty(uf) || string.IsNullOrEmpty(cpfCnpj))
            {
                return("Contribuinte não encontrado.");
            }

            #region Monta XML

            XmlDocument xmlConsCad = new XmlDocument();

            XmlNode declarationNode = xmlConsCad.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlConsCad.AppendChild(declarationNode);

            XmlElement consCad = xmlConsCad.CreateElement("ConsCad");
            consCad.SetAttribute("versao", ConfigNFe.VersaoConsCad);
            consCad.SetAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");
            xmlConsCad.AppendChild(consCad);

            XmlElement infCons = xmlConsCad.CreateElement("infCons");
            consCad.AppendChild(infCons);

            ManipulacaoXml.SetNode(xmlConsCad, infCons, "xServ", "CONS-CAD");
            ManipulacaoXml.SetNode(xmlConsCad, infCons, "UF", uf);

            cpfCnpj = Formatacoes.LimpaCpfCnpj(cpfCnpj);

            if (cpfCnpj.Length == 11)
            {
                ManipulacaoXml.SetNode(xmlConsCad, infCons, "CPF", cpfCnpj);
            }
            else
            {
                ManipulacaoXml.SetNode(xmlConsCad, infCons, "CNPJ", cpfCnpj);
            }

            #endregion

            // Salva o callback padrão do WebService
            System.Net.Security.RemoteCertificateValidationCallback callback = System.Net.ServicePointManager.ServerCertificateValidationCallback;

            XmlNode xmlRetorno = null;

            try
            {
                // Altera o callback de validação do WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
                {
                    // Verifica se a data do certificado é válida
                    DateTime beginDate   = DateTime.Parse(cert.GetEffectiveDateString());
                    DateTime endDate     = DateTime.Parse(cert.GetExpirationDateString());
                    bool     isDateValid = (DateTime.Now >= beginDate) && (DateTime.Now <= endDate);

                    // Retorna o resultado da função
                    return(isDateValid);
                };

                // Envia o arquivo e recebe o retorno.
                xmlRetorno = EnviaXML.ObterXmlConsultaCadastroContribuinte(uf, xmlConsCad);
            }
            catch (Exception ex)
            {
                throw new Exception(Glass.MensagemAlerta.FormatErrorMsg("Falha ao chamar WebService.", ex));
            }
            finally
            {
                // Restaura o callback padrão para o WebService
                System.Net.ServicePointManager.ServerCertificateValidationCallback = callback;
            }

            if (xmlRetorno == null)
            {
                return("Falha ao comunicar com webservice da SEFAZ.");
            }

            XmlDocument xmlDocRetorno = new XmlDocument();
            xmlDocRetorno.ImportNode(xmlRetorno, true);

            XmlNamespaceManager nMgr = new XmlNamespaceManager(xmlDocRetorno.NameTable);
            nMgr.AddNamespace("nfe", "http://www.portalfiscal.inf.br/nfe");

            XmlNode infoCons  = xmlRetorno.SelectSingleNode("//nfe:infCons", nMgr);
            var     codStatus = infoCons?["cStat"]?.InnerText;

            var retorno = string.Empty;
            if (codStatus == "111" || codStatus == "112")
            {
                retorno += "Consulta Situação do Contribuinte no Sintegra\n\n";
                retorno += "Situação: ";

                if (infoCons["infCad"]["cSit"].InnerText == "1")
                {
                    retorno += "Habilitado.";
                }
                else
                {
                    retorno += "Não Habilitado.";
                }
            }
            else
            {
                retorno += "Falha na Consulta Situação do Contribuinte no Sintegra\n\n";
                retorno += "Código: " + codStatus + "\n";
                retorno += infoCons?["xMotivo"]?.InnerText;
            }

            ClienteDAO.Instance.AtualizaUltimaConsultaSintegra(cpfCnpj);

            return(retorno);
        }
 public CustomHttpClient(System.Net.Security.RemoteCertificateValidationCallback serverCertificateValidationCallback) : base()
 {
     this._serverCertificateValidationCallback = serverCertificateValidationCallback;
 }
Exemplo n.º 32
0
 public HTTPClientHttpClient(ILogger logger, HTTPClientConfiguration configuration) : base(logger, configuration)
 {
     remoteCertificateValidationCallback = configuration.SSLTrustManager?.ServerCertificateValidationCallback;
 }