示例#1
0
        public Bridge(TextBox edLog, Form Principal)
            : base(Consts.OFFLINE, edLog)
        {
            this.Principal = Principal;

            repProtocol = new RepProtocolTestSuite.RepProtocol(TerminalDados.IP);
        }
示例#2
0
        public Form1()
        {
            InitializeComponent();

            Text += " [v. " + Application.ProductVersion + "]";

            cbEmployeeGetFilter.Items.Clear();
            cbEmployeeGetFilter.Items.Add(RepProtocol.FiltroEmpregado.PIS);
            cbEmployeeGetFilter.Items.Add(RepProtocol.FiltroEmpregado.ID);
            cbEmployeeGetFilter.Items.Add(RepProtocol.FiltroEmpregado.CNTLS);
            cbEmployeeGetFilter.Items.Add(RepProtocol.FiltroEmpregado.KBD);
            cbEmployeeGetFilter.Items.Add(RepProtocol.FiltroEmpregado.BIO);

            cbGetRegsFilter.Items.Clear();
            cbGetRegsFilter.Items.Add(RepProtocol.FiltroRegistro.All);
            cbGetRegsFilter.Items.Add(RepProtocol.FiltroRegistro.Last24hs);
            cbGetRegsFilter.Items.Add(RepProtocol.FiltroRegistro.DateRange);
            cbGetRegsFilter.Items.Add(RepProtocol.FiltroRegistro.NsrRange);

            cbGetRegsFilter.SelectedIndex     = 0;
            cbEmployerType.SelectedIndex      = 0;
            cbEmployeeGetFilter.SelectedIndex = 0;

            this.log                     = new LogProtocol(this.lbLog, this.ipaddr.Text);
            this.repProtocol             = new RepProtocol(this.ipaddr.Text);
            bEmployerFillExample.Enabled = true;
            bEmployeeFillExample.Enabled = true;
            tcCommandGroups.Enabled      = true;
            gbAuth.Enabled               = true;

#if DEBUG
            ipaddr.Text     = "192.168.1.188";
            mtbAuthCpf.Text = "69604699610";
            tbAuthPwd.Text  = "1234";
#else
            ipaddr.Text     = "";
            mtbAuthCpf.Text = "";
            tbAuthPwd.Text  = "";
#endif
        }
示例#3
0
        public override bool Connect(int Terminal)
        {
            AssepontoRep.DBApp bd = new AssepontoRep.DBApp();

            repProtocol = new RepProtocolTestSuite.RepProtocol(TerminalDados.IP);

            //string Cpf = bd.getFieldValueString(String.Format("SELECT TRM_AUTENTICACAO_CPF FROM Terminais WHERE TRM_IND = {0}", Terminal));
            //string Senha = bd.getFieldValueString(String.Format("SELECT TRM_AUTENTICACAO_SENHA FROM Terminais WHERE TRM_IND = {0}", Terminal));
            //string Host = bd.getFieldValueString(String.Format("SELECT TRM_IP FROM Terminais WHERE TRM_IND = {0}", Terminal));

            string Cpf   = TerminalDados.OperadorCpf;
            string Senha = TerminalDados.OperadorSenha;
            string Host  = TerminalDados.IP;

            if (String.IsNullOrEmpty(Cpf))
            {
                throw new Exception("Informe o CPF nas propriedades do terminal");
            }

            if (String.IsNullOrEmpty(Senha))
            {
                throw new Exception("Informe a Senha nas propriedades do terminal");
            }

            try
            {
                if (!String.IsNullOrEmpty(Cpf) && !String.IsNullOrEmpty(Senha) && !String.IsNullOrEmpty(Host))
                {
                    repProtocol.SetHost(Host);
                    //RepProtocolTestSuite.RestServices rs = new RestServices();
                    repProtocol.SetAuth(Regex.Replace(Cpf, "[^0-9]", ""), Senha, RepProtocolTestSuite.Utils.HexStringToByteArray(TerminalDados.Pin));
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#4
0
        public string DoPostRequest(string uri, Dictionary <string, string> param, RepProtocol instance, RepProtocol.ErrorCodes[] notRetriableErrors = null, bool authenticate = true)
        {
            Exception e = new TimeoutException();

            for (int i = 0; i < Retries; i++)
            {
                try
                {
                    string rawParams    = "";
                    string bodyToDigest = "";
                    if (param != null)
                    {
                        foreach (KeyValuePair <string, string> kvp in param)
                        {
                            rawParams    += EscapeUrl(kvp.Key) + "=" + EscapeUrl(kvp.Value) + "&";
                            bodyToDigest += EscapeUrl(kvp.Value);
                        }
                        // NÃO descomentar a linha abaixo - o protocolo remoto depende do & no final para validar a assinatura corretamente!
                        //rawParams = rawParams.Substring(0, rawParams.Length - 1);
                    }
                    if (authenticate)
                    {
                        byte[] payloadHash  = SHA256.Create().ComputeHash(Program.Encoding.GetBytes(bodyToDigest));
                        byte[] passwordHash = SHA256.Create().ComputeHash(Program.Encoding.GetBytes(password));
                        byte[] sessionKey   = new byte[payloadHash.Length];

                        for (int j = 0; j < sessionKey.Length; j++)
                        {
                            sessionKey[j] = (byte)(masterKey[j] ^ passwordHash[j]);
                        }



                        // gerar digest criptografado de autenticação
                        Trace.WriteLine("**** AUTHENTICATED POST ****");
                        Trace.WriteLine("Post Data Str.:\n" + bodyToDigest);
                        Trace.WriteLine("Post Data Bin.:\n" + BitConverter.ToString(Program.Encoding.GetBytes(bodyToDigest)).Replace("-", ""));
                        Trace.WriteLine("Master key:\n" + BitConverter.ToString(masterKey).Replace("-", ""));
                        Trace.WriteLine("SHA256(password):\n" + BitConverter.ToString(passwordHash).Replace("-", ""));
                        Trace.WriteLine("Session key:\n" + BitConverter.ToString(sessionKey).Replace("-", ""));
                        Trace.WriteLine("SHA256(Post data):\n" + BitConverter.ToString(payloadHash).Replace("-", ""));

                        SymmetricAlgorithm aes = Aes.Create();
                        aes.Mode    = CipherMode.ECB;
                        aes.KeySize = 256;
                        aes.Padding = PaddingMode.None;
                        ICryptoTransform t  = aes.CreateEncryptor(sessionKey, null);
                        MemoryStream     ms = new MemoryStream();
                        CryptoStream     cs = new CryptoStream(ms, t, CryptoStreamMode.Write);
                        cs.Write(payloadHash, 0, payloadHash.Length);
                        cs.FlushFinalBlock();
                        byte[] encAuth = ms.ToArray();
                        cs.Close();
                        ms.Close();
                        string encAuthString = BitConverter.ToString(encAuth).Replace("-", "");
                        Trace.WriteLine("AES(SHA256(Post data), Session key):\n" + encAuthString);
                        rawParams += "AUT=" + cpf + ";" + encAuthString;
                    }
                    Trace.WriteLine("Post body:\n" + rawParams);
                    // fazer request
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                    req.Method      = "POST";
                    req.Timeout     = Timeout;
                    req.ContentType = "application/x-www-form-urlencoded";
                    StreamWriter sw = new StreamWriter(req.GetRequestStream(), Program.Encoding);
                    sw.Write(rawParams);
                    sw.Close();
                    HttpWebResponse resp         = (HttpWebResponse)req.GetResponse();
                    StreamReader    rsr          = new StreamReader(resp.GetResponseStream(), Program.Encoding);
                    string          responseBody = rsr.ReadToEnd();
                    rsr.Close();
                    resp.Close();
                    ThrowIfError(responseBody);
                    Trace.WriteLine("Response ok.");
                    return(responseBody);
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        Trace.WriteLine("Timeout. Retrying...");
                        e = ex;
                    }
                    else
                    {
                        Trace.WriteLine("HTTP error. Retrying...");
                        throw ex;
                    }
                }
                catch (RepProtocolException ex)
                {
                    if (notRetriableErrors != null && notRetriableErrors.Contains(ex.ErrorCode))
                    {
                        Trace.WriteLine("Not retriable error.");
                        i = Retries;
                    }
                    if (ex.ErrorCode == RepProtocol.ErrorCodes.MT_RES_ERROR_INVALID_HASH_ADDRESS)
                    {
                        Trace.WriteLine("Auth error. Do not retry.");
                        i = Retries;
                    }
                    e = ex;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Unknown error. Sleeping and retrying...");
                    System.Threading.Thread.Sleep(500);
                    e = ex;
                }
            }
            throw e;
        }
示例#5
0
        public string DoPostRequest(string uri, Dictionary <string, string> param, RepProtocol instance, RepProtocol.ErrorCodes[] notRetriableErrors = null, bool authenticate = true)
        {
            Exception e = new TimeoutException();

            for (int i = 0; i < Retries; i++)
            {
                try
                {
                    string rawParams    = "";
                    string bodyToDigest = "";
                    if (param != null)
                    {
                        foreach (KeyValuePair <string, string> kvp in param)
                        {
                            rawParams    += EscapeUrl(kvp.Key) + "=" + EscapeUrl(kvp.Value) + "&";
                            bodyToDigest += EscapeUrl(kvp.Value);
                        }
                        // NÃO descomentar a linha abaixo - o protocolo remoto depende do & no final para validar a assinatura corretamente!
                        //rawParams = rawParams.Substring(0, rawParams.Length - 1);
                    }
                    if (authenticate)
                    {
                        if (lastNfrChanged)
                        {
                            TimeSpan timeDiff = DateTime.Now - lastNsrTime;
                            if (timeDiff < NsrCooldown)
                            {
                                System.Threading.Thread.Sleep(NsrCooldown - timeDiff);
                            }
                            Trace.WriteLine("Getting MRP Status");
                            RepProtocol.MrpStatus mrpStatus = instance.GetMrpStatus();
                            nfrValue      = long.Parse(mrpStatus.NFR);
                            nfrLength     = mrpStatus.NFR.Length;
                            lastNsrValue  = long.Parse(mrpStatus.LastNSR);
                            lastNsrLength = mrpStatus.LastNSR.Length;
                            Trace.WriteLine("LastNfrChanged set to FALSE");
                        }
                        byte[] aesKey     = System.Security.Cryptography.SHA1.Create().ComputeHash(Utils.Encoding.GetBytes(bodyToDigest));
                        string authString =
                            "GERTEC\n" +
                            "MARQUE PONTO G4\n" +
                            "NFR:" + nfrValue.ToString().PadLeft(nfrLength, '0') + "\n" +
                            "NSR:" + lastNsrValue.ToString().PadLeft(lastNsrLength, '0') + "\n" +
                            "SENHA:" + password
                        ;
                        // gerar digest criptografado de autenticação
                        Trace.WriteLine("**** AUTHENTICATED POST ****");
                        Trace.WriteLine("Post Data Str.:\n" + bodyToDigest);
                        Trace.WriteLine("Post Data Bin.:\n" + BitConverter.ToString(Utils.Encoding.GetBytes(bodyToDigest)).Replace("-", ""));
                        Trace.WriteLine("Auth Data Str.:\n" + authString);
                        Trace.WriteLine("Auth Data Bin.:\n" + BitConverter.ToString(Utils.Encoding.GetBytes(authString)).Replace("-", ""));
                        List <byte> b;
                        b = new List <byte>(SHA1.Create().ComputeHash(Utils.Encoding.GetBytes(bodyToDigest)));
                        Trace.WriteLine("Post Data SHA1: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        b.RemoveRange(16, 4);
                        Trace.WriteLine("Post Data SHA1 16 MSB: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        byte[] rawParamsSha1Msb = b.ToArray();
                        b = new List <byte>(SHA1.Create().ComputeHash(Utils.Encoding.GetBytes(authString)));
                        Trace.WriteLine("Auth Data SHA1: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        b.RemoveRange(16, 4);
                        Trace.WriteLine("Auth Data SHA1 16 MSB: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        byte[]             authStringSha1Msb = b.ToArray();
                        SymmetricAlgorithm aes = Aes.Create();
                        aes.Mode    = CipherMode.ECB;
                        aes.KeySize = 128;
                        aes.Padding = PaddingMode.None;
                        ICryptoTransform t  = aes.CreateEncryptor(authStringSha1Msb, null);
                        MemoryStream     ms = new MemoryStream();
                        CryptoStream     cs = new CryptoStream(ms, t, CryptoStreamMode.Write);
                        cs.Write(rawParamsSha1Msb, 0, rawParamsSha1Msb.Length);
                        cs.FlushFinalBlock();
                        byte[] encAuth = ms.ToArray();
                        Trace.WriteLine("AES(Post Data SHA1 16 MSB, Auth Data SHA1 16 MSB): " + BitConverter.ToString(encAuth).Replace("-", ""));
                        cs.Close();
                        ms.Close();
                        string encAuthString = BitConverter.ToString(encAuth).Replace("-", "");
                        rawParams += "AUT=" + cpf + ";" + encAuthString;
                    }
                    Trace.WriteLine("Post body: " + rawParams);
                    // fazer request
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                    req.Method      = "POST";
                    req.Timeout     = Timeout;
                    req.ContentType = "application/x-www-form-urlencoded";
                    StreamWriter sw = new StreamWriter(req.GetRequestStream(), Utils.Encoding);
                    sw.Write(rawParams);
                    sw.Close();
                    HttpWebResponse resp         = (HttpWebResponse)req.GetResponse();
                    StreamReader    rsr          = new StreamReader(resp.GetResponseStream(), Utils.Encoding);
                    string          responseBody = rsr.ReadToEnd();
                    rsr.Close();
                    resp.Close();
                    lastNfrChanged = false;
                    ThrowIfError(responseBody);
                    lastNsrTime    = DateTime.Now;
                    lastNfrChanged = true;
                    Trace.WriteLine("Response ok. LastNfrChanged set to TRUE");
                    return(responseBody);
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        Trace.WriteLine("Timeout. Retrying...");
                        e = ex;
                    }
                    else
                    {
                        Trace.WriteLine("HTTP error. Retrying...");
                        throw ex;
                    }
                }
                catch (RepProtocolException ex)
                {
                    if (notRetriableErrors != null && notRetriableErrors.Contains(ex.ErrorCode))
                    {
                        Trace.WriteLine("Not retriable error.");
                        i = Retries;
                    }
                    if (ex.ErrorCode == RepProtocol.ErrorCodes.MT_RES_ERROR_INVALID_HASH_ADDRESS)
                    {
                        Trace.WriteLine("Auth error. Retrying...");
                    }
                    lastNfrChanged = true;
                    e = ex;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Unknown error. Sleeping and retrying...");
                    System.Threading.Thread.Sleep(500);
                    e = ex;
                }
            }
            throw e;
        }