Beispiel #1
0
        public static X509Certificate GenerateLicense(CertificateAuthority ca, Uri installCode, Boolean isServerKey, UInt32 numLic, Boolean isTemp, DateTime?tempDate)
        {
            String installKey = null;
            Uri    license    = null;

            System.Reflection.Assembly asm = null;
            FileInfo p12File = null;

            try
            {
                String[] iParts = installCode.AbsolutePath.Trim("/".ToCharArray()).Split("/".ToCharArray());

                IAMVersion version = IAMVersion.v100;
                switch (iParts[0].ToLower())
                {
                case "v1":
                case "v100":
                    version = IAMVersion.v100;
                    break;

                default:
                    throw new Exception("Install code version unrecognized");
                    break;
                }

                installKey = String.Join("/", iParts, 1, iParts.Length - 1);

                //Em caso de licença com data de expiração, adiciona 20 horas no tempo para evitar problemas com fuso
                tempDate += TimeSpan.FromHours(20);

                license = new Uri("license://safeid/" + version.ToString() + "/" + GeraKey(installKey, isServerKey, numLic, isTemp, tempDate, version));

                try
                {
                    CertificateAuthority.subjectAltName alt = new CertificateAuthority.subjectAltName();
                    alt.Uri.Add(installCode);
                    alt.Uri.Add(license);

                    String pkcs12Cert = ca.SignCert("SafeID IAM License", false, alt, false, (isTemp && tempDate.HasValue ? tempDate.Value : DateTime.Now + TimeSpan.FromDays(36500)));

                    return(CATools.GetX509CertFromPKCS12(Convert.FromBase64String(pkcs12Cert), ca.SignedPassword));
                }
                finally
                {
                    try
                    {
                        File.Delete(p12File.FullName);
                        File.Delete(p12File.FullName.Replace(p12File.Extension, ".cer"));
                    }
                    catch { }

                    p12File = null;
                    asm     = null;
                }
            }
            finally
            {
                installKey = null;
            }
        }
Beispiel #2
0
        public void GetDBConfig(SqlConnection conn, Int64 enterpriseId, String proxyName)
        {
            DataTable dt = null;

            this.Connection = conn;

            GetDBCertConfig(conn, enterpriseId, proxyName);

            if (this.fqdn == null) //Não encontrou o proxy
            {
                return;
            }

            //Plugins ativos
            plugins = new List <PluginConfig>();

            dt = ExecuteDataTable("select * from vw_proxy_plugin with(nolock) where proxy_id = " + proxyID + " and enterprise_id = " + enterpriseId);
            if ((dt != null) || (dt.Rows.Count > 0))
            {
                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(this.fqdn));
                OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(this.client_cert), certPass);

                foreach (DataRow dr in dt.Rows)
                {
                    PluginConfig newItem = new PluginConfig(cert, conn, dr["scheme"].ToString(), (Int64)dr["plugin_id"], (Int64)dr["resource_plugin_id"]);

                    plugins.Add(newItem);
                }
            }
        }
Beispiel #3
0
        private void SaveToSend(JsonGeneric data, String prefix)
        {
            if ((data.data == null) || (data.data.Count == 0))
            {
                return;
            }

            Byte[] jData = data.ToJsonBytes();

            using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.server_cert)), jData))
            {
                DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(basePath, "Out"));
                if (!dirTo.Exists)
                {
                    dirTo.Create();
                }

                FileInfo f = new FileInfo(Path.Combine(dirTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff") + "-" + prefix) + ".iamdat");

                File.WriteAllBytes(f.FullName, cApi.ToBytes());

                TextLog.Log("PluginStarter", "File to send created " + f.Name + " (" + data.data.Count + ")");

                data.data.Clear();
            }
        }
Beispiel #4
0
        public EnterpriseKeyConfig(SqlConnection conn, Int64 enterpriseId, SqlTransaction transaction)
        {
            this.enterpriseId = enterpriseId;
            base.Connection   = conn;

            DataTable dt = ExecuteDataTable("select fqdn, server_cert, server_pkcs12_cert from enterprise with(nolock) where id = " + this.enterpriseId, transaction);

            if ((dt == null) || (dt.Rows.Count == 0)) //Não encontrou a empresa
            {
                throw new Exception("Enterprise '" + enterpriseId + "' not found");
            }

            System.Security.Cryptography.SHA1Managed sha = new System.Security.Cryptography.SHA1Managed();
            Byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(dt.Rows[0]["fqdn"].ToString()));
            String key  = BitConverter.ToString(hash).Replace("-", "");

            this.ServerCertString   = dt.Rows[0]["server_cert"].ToString();
            this.ServerPKCS12String = dt.Rows[0]["server_pkcs12_cert"].ToString();

            this.ServerCert       = CATools.LoadCert(Convert.FromBase64String(this.ServerCertString));
            this.ServerPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(this.ServerPKCS12String), key);

            //Atualiza o certificado em arquivo (apenas para visualização do usuário)
            try
            {
                System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2));
                FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "eCerts\\" + dt.Rows[0]["fqdn"].ToString() + ".cer"));
                if (certFile.Exists)
                {
                    certFile.Delete();
                }

                if (!certFile.Directory.Exists)
                {
                    certFile.Directory.Create();
                }

                File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(this.ServerCertString));
            }
            catch { }

            /*
             * }
             * else
             * {
             *  //Cria
             *
             *  this.BuildCert();
             *
             *  DbParameterCollection par = new DbParameterCollection();
             *  par.Add("@server_cert", typeof(String), this.ServerCertString.Length).Value = this.ServerCertString;
             *  par.Add("@server_pkcs12_cert", typeof(String), this.ServerPKCS12String.Length).Value = this.ServerPKCS12String;
             *
             *  ExecuteSQL(conn, "insert into server_cert (server_cert, server_pkcs12_cert) values (@server_cert, @server_pkcs12_cert)", par, CommandType.Text);
             *
             * }
             */
        }
Beispiel #5
0
        private void SaveToSend(Int64 enterpriseId, DirectoryInfo saveTo, ProxyConfig config, List <PluginConnectorBaseDeployPackage> packages)
        {
            if ((packages == null) || (packages.Count == 0))
            {
                return;
            }

            Byte[] jData    = Encoding.UTF8.GetBytes(SafeTrend.Json.JSON.Serialize <List <PluginConnectorBaseDeployPackage> >(packages));
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));

            using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), jData))
            {
                if (!saveTo.Exists)
                {
                    saveTo.Create();
                }

                FileInfo f = new FileInfo(Path.Combine(saveTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff")) + ".iamdat");

                File.WriteAllBytes(f.FullName, cApi.ToBytes());



                foreach (PluginConnectorBaseDeployPackage pkg in packages)
                {
                    try
                    {
                        //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, 0, 0, pkg.entityId, pkg.identityId, "Saving package ID: " + pkg.pkgId, SafeTrend.Json.JSON.Serialize<PluginConnectorBaseDeployPackage>(pkg));

                        String tpkg = SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(pkg);

                        DbParameterCollection par = new DbParameterCollection();
                        par.Add("@entity_id", typeof(Int64)).Value = pkg.entityId;
                        par.Add("@date", typeof(DateTime)).Value   = DateTime.Now;
                        par.Add("@flow", typeof(String)).Value     = "deploy";
                        par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId;
                        par.Add("@filename", typeof(String), f.FullName.Length).Value  = f.FullName;
                        par.Add("@package", typeof(String), tpkg.Length).Value         = tpkg;

                        Int64 trackId = db.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null);

                        tpkg = null;

                        db.AddPackageTrack(trackId, "deploy", "Package generated");
                    }
                    catch { }
                }


#if DEBUG
                db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, 0, enterpriseId, 0, 0, 0, 0, 0, "File to send created " + f.Name + " (" + packages.Count + ")");
#endif
            }
        }
Beispiel #6
0
        public void SaveToSend(String sufix)
        {
            if ((logRecords1.data != null) && (logRecords1.data.Count > 0))
            {
                Byte[] jData = logRecords1.ToJsonBytes();

                using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(this.serverCert)), jData))
                {
                    DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(this.basePath, "Out"));
                    if (!dirTo.Exists)
                    {
                        dirTo.Create();
                    }

                    FileInfo f = new FileInfo(Path.Combine(dirTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff") + "-" + sufix) + ".iamdat");

                    File.WriteAllBytes(f.FullName, cApi.ToBytes());

#if debug
                    TextLog.Log("PluginStarter", "File to send created " + f.Name + " (" + logRecords.data.Count + ")");
#endif
                    logRecords1.data.Clear();
                }
            }

            if ((logRecords2.data != null) && (logRecords2.data.Count > 0))
            {
                Byte[] jData = logRecords2.ToJsonBytes();

                using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(this.serverCert)), jData))
                {
                    DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(this.basePath, "Out"));
                    if (!dirTo.Exists)
                    {
                        dirTo.Create();
                    }

                    FileInfo f = new FileInfo(Path.Combine(dirTo.FullName, DateTime.Now.ToString("yyyyMMddHHmss-ffffff") + "-pl-" + sufix) + ".iamdat");

                    File.WriteAllBytes(f.FullName, cApi.ToBytes());

#if debug
                    TextLog.Log("PluginStarter", "File to send created " + f.Name + " (" + logRecords.data.Count + ")");
#endif
                    logRecords2.data.Clear();
                }
            }
        }
Beispiel #7
0
        public ServerKey2(SqlConnection conn, String hostname, SqlTransaction transaction)
            : base(conn)
        {
            DataTable dt = ExecuteDataTable("select server_cert, server_pkcs12_cert from server_cert with(nolock)", transaction);

            this.hostname = hostname;

            if ((dt != null) && (dt.Rows.Count > 0)) //Existe certificado, então lê
            {
                this.ServerCertString   = dt.Rows[0]["server_cert"].ToString();
                this.ServerPKCS12String = dt.Rows[0]["server_pkcs12_cert"].ToString();

                this.ServerCert       = CATools.LoadCert(Convert.FromBase64String(this.ServerCertString));
                this.ServerPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(this.ServerPKCS12String), "w0):X,\\Q4^NoIO,):Z!.");

                this.ServerInstallationKey = GetInstallationCode(this.ServerPKCS12Cert);

                //Atualiza o certificado em arquivo (apenas para visualização do usuário)
                try
                {
                    System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2));
                    FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "server.cer"));
                    if (certFile.Exists)
                    {
                        certFile.Delete();
                    }

                    File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(this.ServerCertString));
                }
                catch { }
            }
            else
            {
                //Cria

                this.BuildCert();

                DbParameterCollection par = new DbParameterCollection();
                par.Add("@server_cert", typeof(String), this.ServerCertString.Length).Value          = this.ServerCertString;
                par.Add("@server_pkcs12_cert", typeof(String), this.ServerPKCS12String.Length).Value = this.ServerPKCS12String;

                ExecuteNonQuery("insert into server_cert (server_cert, server_pkcs12_cert) values (@server_cert, @server_pkcs12_cert)", CommandType.Text, par);
            }
        }
Beispiel #8
0
        private List <PluginConnectorBaseDeployPackage> LoadFile(FileInfo file)
        {
            Byte[] fData    = File.ReadAllBytes(file.FullName);
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));

            try
            {
                using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), fData))
                {
                    List <PluginConnectorBaseDeployPackage> data = null;
                    data = JSON.Deserialize <List <PluginConnectorBaseDeployPackage> >(Encoding.UTF8.GetString(cApi.clearData));
                    return(data);
                }
            }
            finally
            {
                certPass = null;
                fData    = new Byte[0];
            }
        }
Beispiel #9
0
        private void BuildCert()
        {
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2));
            FileInfo p12File = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "server" + DateTime.Now.ToString("yyyyMMddHHmss") + ".pfx"));

            try
            {
                CertificateAuthority.subjectAltName alt = new CertificateAuthority.subjectAltName();
                if ((this.ServerInstallationKey == null))
                {
                    this.NewInstallationKey();
                }

                alt.Uri.Add(ServerInstallationKey);

                ca = new CertificateAuthority("123456", "w0):X,\\Q4^NoIO,):Z!.");
                ca.LoadOrCreateCA(p12File.FullName, this.hostname, alt);

                Byte[] certData = File.ReadAllBytes(p12File.FullName);

                this.ServerCert         = CATools.GetX509CertFromPKCS12(certData, "w0):X,\\Q4^NoIO,):Z!.");
                this.ServerCertString   = CATools.X509ToBase64(this.ServerCert);
                this.ServerPKCS12String = Convert.ToBase64String(certData);
                this.ServerPKCS12Cert   = CATools.LoadCert(certData, "w0):X,\\Q4^NoIO,):Z!.");
            }
            finally
            {
                try
                {
                    File.Delete(p12File.FullName);
                    File.Delete(p12File.FullName.Replace(p12File.Extension, ".cer"));
                }
                catch { }

                p12File = null;
                asm     = null;
            }
        }
Beispiel #10
0
        public Byte[] ToBytes()
        {
            Byte[] jData = new Byte[0];

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List <PluginConnectorBaseFetchPackage>));

            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, this.fetch_packages);
                ms.Flush();
                jData = ms.ToArray();
            }

            Byte[] retData  = new Byte[0];
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(fqdn));

            using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(client_cert), certPass), jData))
            {
                retData = cApi.ToBytes();
            }

            return(retData);
        }
Beispiel #11
0
        private void BuildCert(SqlConnection conn, SqlTransaction trans)
        {
            base.Connection = conn;

            DataTable dt = ExecuteDataTable("select fqdn, name from enterprise with(nolock) where id = " + this.enterpriseId, trans);

            if ((dt == null) || (dt.Rows.Count == 0)) //Não encontrou a empresa
            {
                throw new Exception("Enterprise '" + enterpriseId + "' not found");
            }


            System.Security.Cryptography.SHA1Managed sha = new System.Security.Cryptography.SHA1Managed();
            Byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(dt.Rows[0]["fqdn"].ToString()));
            String key  = BitConverter.ToString(hash).Replace("-", "");


            EnterpriseKey keys = new EnterpriseKey(new Uri("//" + dt.Rows[0]["fqdn"].ToString()), dt.Rows[0]["name"].ToString());

            keys.BuildCerts();

            try
            {
                this.ServerPKCS12String = keys.ServerPKCS12Cert;

                Byte[] certData = Convert.FromBase64String(this.ServerPKCS12String);
                this.ServerCert       = CATools.GetX509CertFromPKCS12(certData, key);
                this.ServerCertString = CATools.X509ToBase64(this.ServerCert);
                this.ServerPKCS12Cert = CATools.LoadCert(certData, key);

                this.ClientPKCS12String = keys.ClientPKCS12Cert;
                this.ClientPKCS12Cert   = CATools.LoadCert(Convert.FromBase64String(this.ClientPKCS12String), key);
            }
            finally
            {
            }
        }
Beispiel #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

            try
            {
                JSONRequest req = JSON.GetRequest(Request.InputStream);
                using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyConfig config = new ProxyConfig();
                    config.GetDBConfig(db.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        try
                        {
                            Byte[] bData = Convert.FromBase64String(req.data);
                            List <Dictionary <String, Object> > proccessData = new List <Dictionary <string, object> >();


                            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                            using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), bData))
                                proccessData = SafeTrend.Json.JSON.Deserialize <List <Dictionary <String, Object> > >(Encoding.UTF8.GetString(cApi.clearData));

                            foreach (Dictionary <String, Object> p in proccessData)
                            {
                                if (p.ContainsKey("fetch_id"))
                                {
                                    String jData = SafeTrend.Json.JSON.Serialize2(p);

                                    Int64 fetch_id = 0;

                                    try
                                    {
                                        fetch_id = Int64.Parse(p["fetch_id"].ToString());
                                    }
                                    catch { }

                                    if (fetch_id > 0)
                                    {
                                        DbParameterCollection par = new DbParameterCollection();
                                        par.Add("@fetch_id", typeof(Int64)).Value   = fetch_id;
                                        par.Add("@json_data", typeof(String)).Value = jData;
                                        par.Add("@success", typeof(Boolean)).Value  = (p.ContainsKey("result") && (p["result"] is Boolean) && (Boolean)p["result"]);

                                        db.ExecuteNonQuery("update resource_plugin_fetch set response_date = getdate(), [success] = @success, json_data = @json_data WHERE id = @fetch_id", System.Data.CommandType.Text, par);
                                    }
                                }
                            }

                            ReturnHolder.Controls.Add(new LiteralControl("{ \"response\":\"success\" }"));
                        }
                        catch
                        {
                            ReturnHolder.Controls.Add(new LiteralControl("{ \"response\":\"error\" }"));
                        }
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex, this);
                throw ex;
            }
        }
Beispiel #13
0
        private void InboundTimer(Object state)
        {
            TextLog.Log("Server", "Starting inbound timer");
            try
            {
                DirectoryInfo inDir = new DirectoryInfo(Path.Combine(basePath, "In"));
                if (!inDir.Exists)
                {
                    TextLog.Log("Server", "\t0 files to process");
                    return;
                }

                FileInfo[] files = inDir.GetFiles("*.iamreq");
                TextLog.Log("Server", "\t" + files.Length + " files to process");


                MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();

                foreach (FileInfo f in files)
                {
                    JSONRequest req = null;
                    try
                    {
                        using (FileStream fs = f.OpenRead())
                            req = JSON.GetRequest(fs);

                        if ((req.host == null) || (req.host == ""))
                        {
                            TextLog.Log("Server", "Paramter 'host' is empty on  " + f.Name);
                            continue;
                        }

                        if ((req.enterpriseid == null) || (req.enterpriseid == ""))
                        {
                            TextLog.Log("Server", "Paramter 'enterpriseid' is empty on  " + f.Name);
                            continue;
                        }

                        try
                        {
                            Int64 tst = Int64.Parse(req.enterpriseid);
                        }
                        catch {
                            if ((req.enterpriseid == null) || (req.enterpriseid == ""))
                            {
                                TextLog.Log("Server", "Paramter 'enterpriseid' is not Int64  " + f.Name);
                                continue;
                            }
                        }

                        ProxyConfig config = new ProxyConfig(true);
                        config.GetDBCertConfig(db.conn, Int64.Parse(req.enterpriseid), req.host);

                        if (config.fqdn != null) //Encontrou o proxy
                        {
                            JsonGeneric jData = new JsonGeneric();
                            try
                            {
                                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                                using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), Convert.FromBase64String(req.data)))
                                    jData.FromJsonBytes(cApi.clearData);
                            }
                            catch (Exception ex)
                            {
                                jData = null;
                                TextLog.Log("Server", "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message);
                            }

                            if (jData == null)
                            {
                                continue;
                            }

                            Int32 contextCol = jData.GetKeyIndex("context");

                            Int32 uriCol        = jData.GetKeyIndex("uri");
                            Int32 importidCol   = jData.GetKeyIndex("importid");
                            Int32 registryidCol = jData.GetKeyIndex("registryid");
                            Int32 datanameCol   = jData.GetKeyIndex("dataname");
                            Int32 datavalueCol  = jData.GetKeyIndex("datavalue");
                            Int32 datatypeCol   = jData.GetKeyIndex("datatype");

                            if (uriCol == -1)
                            {
                                TextLog.Log("Server", "Erro on find column 'uri' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                                continue;
                            }


                            if (importidCol == -1)
                            {
                                TextLog.Log("Server", "Erro on find column 'importid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                                continue;
                            }


                            if (registryidCol == -1)
                            {
                                TextLog.Log("Server", "Erro on find column 'registryid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                                continue;
                            }


                            if (datanameCol == -1)
                            {
                                TextLog.Log("Server", "Erro on find column 'dataname' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                                continue;
                            }


                            if (datavalueCol == -1)
                            {
                                TextLog.Log("Server", "Erro on find column 'datavalue' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                                continue;
                            }


                            if (datatypeCol == -1)
                            {
                                TextLog.Log("Server", "Erro on find column 'datatype' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                                continue;
                            }

                            DateTime date = DateTime.Now;


                            //Realiza a importação no modelo BulkInsert por melhor desempenho do banco
                            DataTable dtBulk = new DataTable();
                            dtBulk.Columns.Add(new DataColumn("date", typeof(DateTime)));
                            dtBulk.Columns.Add(new DataColumn("plugin_uri", typeof(String)));
                            dtBulk.Columns.Add(new DataColumn("context_id", typeof(Int64)));
                            dtBulk.Columns.Add(new DataColumn("import_id", typeof(String)));
                            dtBulk.Columns.Add(new DataColumn("registry_id", typeof(String)));
                            dtBulk.Columns.Add(new DataColumn("data_name", typeof(String)));
                            dtBulk.Columns.Add(new DataColumn("data_value", typeof(String)));
                            dtBulk.Columns.Add(new DataColumn("data_type", typeof(String)));

                            foreach (String[] dr in jData.data)
                            {
                                dtBulk.Rows.Add(new Object[] { date, dr[uriCol], Int64.Parse(dr[contextCol]), dr[importidCol], dr[registryidCol], dr[datanameCol], dr[datavalueCol], dr[datatypeCol] });
                            }

                            db.BulkCopy(dtBulk, "collector_imports");

                            TextLog.Log("Server", "Imported " + dtBulk.Rows.Count + " registers for enterprise " + req.enterpriseid + " and proxy " + req.host);

                            dtBulk.Dispose();
                            dtBulk = null;

                            jData = null;

                            f.Delete();
                        }
                        else
                        {
                            TextLog.Log("Server", "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host);
                        }
                        config = null;
                    }
                    finally
                    {
                        req = null;
                    }
                }
                db.closeDB();
            }
            catch (Exception ex)
            {
                TextLog.Log("Server", "Error on inbound timer " + ex.Message);
            }
            finally
            {
                TextLog.Log("Server", "Finishing inbound timer");
            }
        }
Beispiel #14
0
        public void RenewCert(SqlConnection conn)
        {
            base.Connection = conn;

            DataTable dt = ExecuteDataTable("select server_cert, server_pkcs12_cert from server_cert with(nolock)");

            if ((dt != null) && (dt.Rows.Count > 0)) //Existe certificado, então lê
            {
                //Resgata o certificado do banco
                X509Certificate atualServerPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(dt.Rows[0]["server_pkcs12_cert"].ToString()), "w0):X,\\Q4^NoIO,):Z!.");

                //Primeiramente atualiza todas as senhas atuais para a senha usando o certificado da empresa
                SqlTransaction trans = null;

                /*
                 * conn.BeginTransaction();
                 * try
                 * {
                 *  //Criptografa a senha de todas as entidades
                 *  DataTable dtEnterprise = ExecuteDataTable("select * from enterprise with(nolock)", trans);
                 *  if (dtEnterprise == null)
                 *      throw new Exception("Erro on enterprise SQL");
                 *
                 *  foreach (DataRow drEnt in dtEnterprise.Rows)
                 *  {
                 *      Console.WriteLine("Enterprise " + drEnt["id"]);
                 *
                 *      using (EnterpriseKeyConfig ek = new EnterpriseKeyConfig(conn, (Int64)drEnt["id"], trans))
                 *      {
                 *
                 *          DataTable dtEnt = ExecuteDataTable("select e.id, e.login, e.password from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where c.enterprise_id = " + drEnt["id"], trans);
                 *          if (dtEnt == null)
                 *              throw new Exception("Erro on SQL");
                 *
                 *          foreach (DataRow dr in dtEnt.Rows)
                 *          {
                 *              Console.Write("\t[SK] Entity " + dr["id"] + ": ");
                 *
                 *              CryptApi decryptApi = null;
                 *              try
                 *              {
                 *
                 *                  try
                 *                  {
                 *                      //Tenta decriptografia com certificado da empresa
                 *                      decryptApi = CryptApi.ParsePackage(ek.ServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()));
                 *
                 *                      //Processo OK, a senha ja está usando o certificado da empresa
                 *                      Console.WriteLine("OK");
                 *                      continue;
                 *
                 *                  }
                 *                  catch
                 *                  {
                 *
                 *                      //Tenta decriptografia com o certificado geral do servidor
                 *                      //Se conseguir atualiza a senha para o certificado da empresa
                 *                      decryptApi = CryptApi.ParsePackage(atualServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString()));
                 *                  }
                 *
                 *                  using (CryptApi ecryptApi = new CryptApi(ek.ServerCert, decryptApi.clearData))
                 *                  {
                 *
                 *                      DbParameterCollection pPar = new DbParameterCollection();
                 *                      String b64 = Convert.ToBase64String(ecryptApi.ToBytes());
                 *                      pPar.Add("@password", typeof(String), b64.Length).Value = b64;
                 *
                 *                      Exception ex1 = null;
                 *                      for (Int32 count = 1; count <= 3; count++)
                 *                      {
                 *                          try
                 *                          {
                 *                              ExecuteNonQuery("update entity set password = @password where id = " + dr["id"], CommandType.Text, pPar, trans);
                 *                              ex1 = null;
                 *                              break;
                 *                          }
                 *                          catch (Exception ex)
                 *                          {
                 *                              ex1 = ex;
                 *                              if (ex.Message.ToLower().IndexOf("timeout") != -1)
                 *                              {
                 *                                  System.Threading.Thread.Sleep(1000 * count);
                 *                              }
                 *                          }
                 *                      }
                 *
                 *                      if (ex1 != null)
                 *                          throw ex1;
                 *
                 *                      Log(drEnt["id"].ToString(), dr["id"].ToString(), dr["login"].ToString(), Encoding.UTF8.GetString(decryptApi.clearData));
                 *                      Console.WriteLine("OK, Updated");
                 *                  }
                 *
                 *              }
                 *              catch (Exception ex)
                 *              {
                 *                  Console.WriteLine("Err");
                 *                  throw ex;
                 *              }
                 *              finally
                 *              {
                 *                  if (decryptApi != null) decryptApi.Dispose();
                 *              }
                 *
                 *          }
                 *
                 *      }
                 *
                 *      Console.WriteLine("");
                 *  }
                 *
                 *  //Se tudo estiver OK, realiza o commit dos dados
                 *  trans.Commit();
                 *  Console.WriteLine("Commit");
                 * }
                 * catch (Exception ex)
                 * {
                 *  Console.WriteLine("Rollback");
                 *  if (trans != null) trans.Rollback();
                 *  throw ex;
                 * }*/

                //Atualiza o certificado global do servidor
                //e gera novo certificado da empresa e atualiza o mesmo
                trans = conn.BeginTransaction();
                Console.WriteLine("Update Global Server Certificate");
                try
                {
                    //Se a chave de instalaçõe é nula
                    if (this.ServerInstallationKey == null)
                    {
                        this.ServerInstallationKey = GetInstallationCode(atualServerPKCS12Cert);
                    }

                    //Cria o novo certificado, e a chave se não existir ainda
                    this.BuildCert();

                    //Exclui o certificado atual do banco
                    ExecuteNonQuery("delete from server_cert", CommandType.Text, null, trans);

                    //Salva o novo certificado
                    DbParameterCollection par = new DbParameterCollection();
                    par.Add("@server_cert", typeof(String), this.ServerCertString.Length).Value          = this.ServerCertString;
                    par.Add("@server_pkcs12_cert", typeof(String), this.ServerPKCS12String.Length).Value = this.ServerPKCS12String;

                    ExecuteNonQuery("insert into server_cert (server_cert, server_pkcs12_cert) values (@server_cert, @server_pkcs12_cert)", CommandType.Text, par, trans);


                    Console.WriteLine("Commit");
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Rollback");
                    trans.Rollback();
                    throw ex;
                }

                try
                {
                    //Criptografa a senha de todas as entidades

                    DataTable dtEnterprise = ExecuteDataTable("select * from enterprise with(nolock)", trans);
                    if (dtEnterprise == null)
                    {
                        throw new Exception("Erro on enterprise SQL");
                    }

                    foreach (DataRow drEnt in dtEnterprise.Rows)
                    {
                        Console.WriteLine("Enterprise " + drEnt["id"]);

                        using (EnterpriseKeyConfig ek = new EnterpriseKeyConfig(conn, (Int64)drEnt["id"], trans))
                            ek.RenewCert(conn);

                        Console.WriteLine("");
                    }

                    try
                    {
                        System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2));
                        FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "server.cer"));
                        if (certFile.Exists)
                        {
                            certFile.Delete();
                        }

                        File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(this.ServerCertString));
                    }
                    catch { }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else //Não foi encontrado certificado no banco, erro
            {
                //Como ao instanciar esta classe a verificação e criação do certificado ja foi realizada, não deve acontecer esse erro
                throw new Exception("Erro on find server certificate");
            }
        }
Beispiel #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

            try
            {
                JSONRequest req = JSON.GetRequest(Request.InputStream);

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        DirectoryInfo inDir = null;

                        using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                            inDir = new DirectoryInfo(c.GetItem("inboundFiles"));

                        if (!inDir.Exists)
                        {
                            inDir.Create();
                        }

                        req.enterpriseid = ((EnterpriseData)Page.Session["enterprise_data"]).Id.ToString();

                        String filename = config.proxy_name + "-" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".iamreq";


                        if (String.IsNullOrEmpty(req.filename))
                        {
                            req.filename = "Empty";
                        }

                        StringBuilder trackData = new StringBuilder();
                        trackData.AppendLine("Proxy: " + req.host);
                        trackData.AppendLine("Enterprise ID: " + req.enterpriseid);
                        trackData.AppendLine("Proxy filename: " + req.filename);
                        trackData.AppendLine("Saved filename: " + filename);

                        UserLogLevel level = UserLogLevel.Info;

                        trackData.AppendLine("");
                        trackData.AppendLine("Checking package...");

                        if (String.IsNullOrEmpty(req.data))
                        {
                            throw new Exception("Request data is empty");
                        }

                        Byte[] rData = Convert.FromBase64String(req.data);

                        if (!String.IsNullOrEmpty(req.sha1hash))
                        {
                            if (!CATools.SHA1CheckHash(rData, req.sha1hash))
                            {
                                throw new Exception("SHA1 Checksum is not equal");
                            }
                        }

                        String type = "";
                        try
                        {
                            JsonGeneric jData = new JsonGeneric();
                            try
                            {
                                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                                if (String.IsNullOrEmpty(config.server_pkcs12_cert))
                                {
                                    throw new Exception("Server PKCS12 from proxy config is empty");
                                }

                                using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), rData))
                                    jData.FromJsonBytes(cApi.clearData);
                            }
                            catch (Exception ex)
                            {
                                jData = null;
                                trackData.AppendLine("Error decrypting package data for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message);

#if DEBUG
                                trackData.AppendLine(ex.StackTrace);
#endif
                            }

                            if (jData != null)
                            {
#if DEBUG
                                trackData.AppendLine("");
                                trackData.AppendLine("Request data:");
                                trackData.AppendLine(jData.ToJsonString());

                                trackData.AppendLine("");
#endif

                                type = jData.function;

                                trackData.AppendLine("Type: " + type);
                                trackData.AppendLine("Data array length: " + (jData.data == null ? "0" : jData.data.Count.ToString()));

                                if (type.ToLower() == "processimportv2")
                                {
                                    Int32 d = 1;
                                    foreach (String[] dr in jData.data)
                                    {
                                        try
                                        {
                                            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
                                            Int32 pkgCol            = jData.GetKeyIndex("package");

                                            if (resourcePluginCol == -1)
                                            {
                                                trackData.AppendLine("[Package data " + d + "] Erro finding column 'resource_plugin'");
                                            }

                                            if (pkgCol == -1)
                                            {
                                                trackData.AppendLine("[Package data " + d + "] Erro finding column 'package'");
                                            }

                                            if ((resourcePluginCol != -1) && (pkgCol != -1))
                                            {
                                                PluginConnectorBaseImportPackageUser pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageUser>(dr[pkgCol]);
                                                trackData.AppendLine("[Package data " + d + "] Import id: " + pkg.importId);
                                                trackData.AppendLine("[Package data " + d + "] Package id: " + pkg.pkgId);

                                                Int64 trackId = 0;
                                                try
                                                {
                                                    String tpkg = JSON.Serialize2(pkg);

                                                    DbParameterCollection par = new DbParameterCollection();
                                                    par.Add("@entity_id", typeof(Int64)).Value = 0;
                                                    par.Add("@date", typeof(DateTime)).Value   = pkg.GetBuildDate();
                                                    par.Add("@flow", typeof(String)).Value     = "inbound";
                                                    par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId;
                                                    par.Add("@filename", typeof(String)).Value             = req.filename;
                                                    par.Add("@package", typeof(String), tpkg.Length).Value = tpkg;

                                                    trackId = database.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null);

                                                    trackData.AppendLine("[Package data " + d + "] Package track id: " + trackId);

                                                    tpkg = null;

                                                    if (trackId > 0)
                                                    {
                                                        database.AddPackageTrack(trackId, "ProxyAPI", "Package received from proxy and saved at " + filename);
                                                    }
                                                }
                                                catch (Exception ex3) {
                                                    trackData.AppendLine("[Package data " + d + "] Erro generating package track: " + ex3.Message);
                                                }


                                                pkg.Dispose();
                                                pkg = null;
                                            }
                                        }
                                        catch (Exception ex2)
                                        {
                                            trackData.AppendLine("[Package data " + d + "] Erro parsing package data " + ex2.Message);
                                        }
                                        d++;
                                    }
                                }
                            }
                        }
                        catch (Exception ex1) {
                            trackData.AppendLine("Erro parsing package " + ex1.Message);
                            level = UserLogLevel.Error;
                        }

                        database.AddUserLog(LogKey.API_Log, DateTime.Now, "ProxyAPI", level, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "File received from proxy " + req.host + (String.IsNullOrEmpty(type) ? "" : " (" + type + ")"), trackData.ToString());


                        File.WriteAllBytes(Path.Combine(inDir.FullName, filename), Encoding.UTF8.GetBytes(JSON.Serialize <JSONRequest>(req)));

                        ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Request received and proxy finded (" + (req.data != null ? req.data.Length.ToString() : "0") + ")")));
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }
Beispiel #16
0
        static void ExecuteConnector(Boolean deployOnly)
        {
            List <Int64> resource = new List <Int64>();

            //Separa os contextos
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));

            OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass);
            foreach (PluginConfig p in config.plugins)
            {
                if (p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower())
                {
                    JsonGeneric pgConf = new JsonGeneric();
                    try
                    {
                        using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters)))
                            pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData));
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Decrypt error1 " + ex.Message);
                    }
                    finally
                    {
                        pgConf = null;
                    }

                    if (!resource.Contains(p.resource))
                    {
                        resource.Add(p.resource);
                    }
                }
            }


            foreach (Int64 r in resource)
            {
                Dictionary <String, Object> connectorConf = new Dictionary <String, Object>();
                Dictionary <String, String> mapping       = new Dictionary <String, String>();

                Boolean enableDeploy = false;

                try
                {
                    foreach (PluginConfig p in config.plugins)
                    {
                        if ((p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) && (p.resource == r))
                        {
                            mapping      = p.mappingDataTypeDic;
                            enableDeploy = p.enable_deploy;

                            JsonGeneric pgConf = new JsonGeneric();
                            try
                            {
                                if (cert == null)
                                {
                                    throw new Exception("Certificate is null");
                                }

                                using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters)))
                                    pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData));
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Decrypt error: " + ex.Message);
                            }

                            if ((pgConf.data == null) || (pgConf.data.Count == 0))
                            {
                                continue;
                            }

                            Int32 kCol = pgConf.GetKeyIndex("key");
                            Int32 vCol = pgConf.GetKeyIndex("value");

                            if (!String.IsNullOrWhiteSpace(p.mail_domain))
                            {
                                connectorConf.Add("iam_mail_domain", p.mail_domain);
                            }

                            foreach (String[] d1 in pgConf.data)
                            {
                                if (!connectorConf.ContainsKey(d1[kCol]))
                                {
                                    connectorConf.Add(d1[kCol], d1[vCol].ToString());
                                }
                            }
                        }
                    }

                    //Deploy ocorre antes da importação
                    //Para que na importação ja apareça os registros que foram publicados pelo deploy
                    try
                    {
                        if (enableDeploy)
                        {
                            ProcessDeploy(r, connectorConf, mapping);
                        }
                        else
                        {
                            TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Deploy disabled");

                            //Exclui os arquivos
                            System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(plugin.GetType());
                            DirectoryInfo dirFrom          = new DirectoryInfo(Path.Combine(basePath, "In\\" + Path.GetFileNameWithoutExtension(asm.Location) + "\\" + resource));
                            if (dirFrom.Exists)
                            {
                                foreach (FileInfo f in dirFrom.GetFiles("*.iamdat"))
                                {
                                    f.Delete();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on deploy: " + ex.Message);
                    }


                    if (!deployOnly)
                    {
                        try
                        {
                            //O import não é desabilitado, pois ele é necessário para relatório de consistência
                            //o Engine não utilizará ele para adicionar novas entidades
                            ProcessImport(r, connectorConf, mapping);
                        }
                        catch (Exception ex)
                        {
                            TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on import: " + ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on parse config: " + ex.Message);
                }
                finally
                {
                    connectorConf.Clear();
                    connectorConf = null;

                    mapping.Clear();
                    mapping = null;
                }
            }

            cert     = null;
            certPass = null;
        }
Beispiel #17
0
        public void RenewCert(SqlConnection conn, SqlTransaction transaction)
        {
            SqlTransaction trans = transaction;

            base.Connection = conn;

            if (trans == null)
            {
                trans = conn.BeginTransaction();
            }

            DataTable dt = ExecuteDataTable("select fqdn, server_cert, server_pkcs12_cert, client_pkcs12_cert from enterprise with(nolock) where id = " + this.enterpriseId, trans);

            if ((dt == null) || (dt.Rows.Count == 0)) //Não encontrou a empresa
            {
                throw new Exception("Enterprise '" + enterpriseId + "' not found");
            }

            System.Security.Cryptography.SHA1Managed sha = new System.Security.Cryptography.SHA1Managed();
            Byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(dt.Rows[0]["fqdn"].ToString()));
            String key  = BitConverter.ToString(hash).Replace("-", "");

            //Resgata o certificado do banco
            X509Certificate atualServerPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(dt.Rows[0]["server_pkcs12_cert"].ToString()), key);
            X509Certificate atualClientPKCS12Cert = CATools.LoadCert(Convert.FromBase64String(dt.Rows[0]["client_pkcs12_cert"].ToString()), key);

            //Se tudo OK, inicia o processo

            try
            {
                //Cria o novo certificado, e a chave se não existir ainda
                this.BuildCert(conn, trans);

                //Exclui o certificado atual do banco
                //ExecuteSQL(conn, "delete from server_cert", null, CommandType.Text, trans);

                //Salva o novo certificado
                DbParameterCollection par = new DbParameterCollection();
                par.Add("@enterprise_id", typeof(Int64)).Value       = this.enterpriseId;
                par.Add("@server_cert", typeof(String)).Value        = this.ServerCertString;
                par.Add("@server_pkcs12_cert", typeof(String)).Value = this.ServerPKCS12String;
                par.Add("@client_pkcs12_cert", typeof(String)).Value = this.ClientPKCS12String;

                ExecuteNonQuery("update enterprise set server_cert = @server_cert, server_pkcs12_cert = @server_pkcs12_cert, client_pkcs12_cert = @client_pkcs12_cert where id = @enterprise_id", CommandType.Text, par, trans);

                //Criptografa a senha de todas as entidades
                DataTable dtEnt = ExecuteDataTable("select e.id, e.login, e.password from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id inner join enterprise e1 with(nolock) on e1.id = c.enterprise_id where e1.id = " + this.enterpriseId, trans);
                if (dtEnt == null)
                {
                    throw new Exception("Erro on SQL");
                }

                foreach (DataRow dr in dtEnt.Rows)
                {
                    Console.Write("[EK] Entity " + dr["id"] + ": ");

                    try
                    {
                        using (CryptApi decryptApi = CryptApi.ParsePackage(atualServerPKCS12Cert, Convert.FromBase64String(dr["password"].ToString())))
                            using (CryptApi ecryptApi = new CryptApi(this.ServerCert, decryptApi.clearData))
                            {
                                DbParameterCollection pPar = new DbParameterCollection();
                                String b64 = Convert.ToBase64String(ecryptApi.ToBytes());
                                pPar.Add("@password", typeof(String), b64.Length).Value = b64;

                                Exception ex1 = null;
                                for (Int32 count = 1; count <= 3; count++)
                                {
                                    try
                                    {
                                        ExecuteNonQuery("update entity set password = @password where id = " + dr["id"], CommandType.Text, pPar, trans);
                                        ex1 = null;
                                        break;
                                    }
                                    catch (Exception ex)
                                    {
                                        ex1 = ex;
                                        if (ex.Message.ToLower().IndexOf("timeout") != -1)
                                        {
                                            System.Threading.Thread.Sleep(1000 * count);
                                        }
                                    }
                                }

                                if (ex1 != null)
                                {
                                    throw ex1;
                                }

                                Log(this.enterpriseId.ToString(), dr["id"].ToString(), dr["login"].ToString(), Encoding.UTF8.GetString(decryptApi.clearData));
                                Console.WriteLine("OK");
                            }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Err");
                        throw ex;
                    }
                }

                try
                {
                    System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(ServerKey2));
                    FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "eCerts\\" + dt.Rows[0]["fqdn"].ToString() + ".cer"));
                    if (certFile.Exists)
                    {
                        certFile.Delete();
                    }


                    if (!certFile.Directory.Exists)
                    {
                        certFile.Directory.Create();
                    }

                    File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(this.ServerCertString));
                }
                catch { }

                //Se tudo estiver OK, realiza o commit dos dados
                Console.WriteLine("Commit");

                if (transaction == null)
                {
                    trans.Commit();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Rollback");
                if (transaction == null)
                {
                    trans.Rollback();
                }
                throw ex;
            }
        }
Beispiel #18
0
        public static IAMKeyData ExtractFromCert(String base64CertData)
        {
            X509Certificate cert        = null;
            Uri             installCode = null;
            Uri             license     = null;
            String          key         = null;
            String          installKey  = null;

            try
            {
                try
                {
                    cert = CATools.LoadCert(Convert.FromBase64String(base64CertData));
                }
                catch (Exception ex)
                {
                    throw new Exception("Erro on load certificate: " + ex.Message);
                }

                installCode = GetDataCode(cert, "installkey");

                if (installCode == null)
                {
                    throw new Exception("Install code not found in certificate");
                }

                license = GetDataCode(cert, "license");

                if (license == null)
                {
                    throw new Exception("License not found in certificate");
                }

                String[] parts  = license.AbsolutePath.Trim("/".ToCharArray()).Split("/".ToCharArray());
                String[] iParts = installCode.AbsolutePath.Trim("/".ToCharArray()).Split("/".ToCharArray());

                IAMVersion version = IAMVersion.v100;
                switch (parts[0].ToLower())
                {
                case "v100":
                    version = IAMVersion.v100;
                    break;

                default:
                    throw new Exception("License version unrecognized");
                    break;
                }


                key        = String.Join("/", parts, 1, parts.Length - 1);
                installKey = String.Join("/", iParts, 1, iParts.Length - 1);

                return(CheckKey(installKey, version, key));
            }
            finally
            {
                cert        = null;
                installCode = null;
                license     = null;
                key         = null;
                installKey  = null;
            }
        }
Beispiel #19
0
        private void ProcQueue(FileInfo f, Object oStarter)
        {
            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();
                db.Timeout = 900;
                Boolean rebuildIndex = false;

                String type = "";

                type = "";
                JSONRequest req = null;
                try
                {
                    using (FileStream fs = f.OpenRead())
                        req = JSON.GetRequest(fs);

                    if ((req.host == null) || (req.host == ""))
                    {
                        db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'host' is empty on  " + f.Name);
                        return;
                    }

                    if ((req.enterpriseid == null) || (req.enterpriseid == ""))
                    {
                        db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is empty on  " + f.Name);
                        return;
                    }

                    try
                    {
                        Int64 tst = Int64.Parse(req.enterpriseid);
                    }
                    catch
                    {
                        if ((req.enterpriseid == null) || (req.enterpriseid == ""))
                        {
                            db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is not Int64  " + f.Name);
                            return;
                        }
                    }

                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBCertConfig(db.Connection, Int64.Parse(req.enterpriseid), req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        JsonGeneric jData = new JsonGeneric();
                        try
                        {
                            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                            using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), Convert.FromBase64String(req.data)))
                                jData.FromJsonBytes(cApi.clearData);
                        }
                        catch (Exception ex)
                        {
                            jData = null;
                            db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message);
                        }

                        if (jData == null)
                        {
                            return;
                        }

                        type = jData.function.ToLower();

                        switch (type)
                        {
                        case "processimport-disabled":
                            rebuildIndex = true;
                            //ImportRegisters(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "processimportv2":
                            rebuildIndex = true;
                            last_status  = "Executando importação de registros";
                            ImportRegistersV2(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "processstructimport":
                            last_status = "Executando importação de registros de estrutura";
                            ImportRegistersStruct(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "notify":
                            last_status = "Executando importação de notificações";
                            ImportNotify(config, jData, f, req, db);

                            f.Delete();
                            break;

                        case "deleted":
                            last_status = "Executando importação de exclusões";
                            ImportDelete(config, jData, f, req, db);
                            f.Delete();
                            break;

                        case "logrecords":
                            last_status = "Executando importação de logs";
                            ImportLogs(config, jData, f, req, db);
                            f.Delete();
                            //f.MoveTo(f.FullName + ".imported");
                            break;

                        case "packagetrack":
                            last_status = "Executando importação de track dos pacotes";
                            ImportPackageTrack(config, jData, f, req, db);
                            f.Delete();
                            //f.MoveTo(f.FullName + ".imported");
                            break;

                        default:
                            db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Invalid jData function '" + jData.function + "'");
                            break;
                        }
                    }
                    else
                    {
                        db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host);
                    }
                    config = null;
                }
                catch (Exception ex)
                {
                    TextLog.Log("Inbound", "Erro on process file '" + f.Name + "' (" + type + "): " + ex.Message);
                    db.AddUserLog(LogKey.Import, null, "Inbound", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Erro processing file '" + f.Name + "' (" + type + "): " + ex.Message);
                }
                finally
                {
                    last_status = "";
                    req         = null;

                    filesProcessed++;
                }

                /*
                 * if (rebuildIndex)
                 * {
                 *  db.Timeout = 900;
                 *  last_status = "Reindexando registros";
                 *  db.ExecuteNonQuery("sp_reindex_imports", CommandType.StoredProcedure, null);
                 * }*/
            }
            catch (Exception ex)
            {
                TextLog.Log("Inbound", "Error importing file (" + f.Name + ")" + ex.Message);
            }
            finally
            {
                if (db != null)
                {
                    db.closeDB();
                }
            }
        }
Beispiel #20
0
        private void ExecuteConnector(Boolean deployOnly)
        {
            List <Int64> resource_plugin = new List <Int64>();

            //Separa os contextos
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));

            OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass);

            try
            {
                foreach (PluginConfig p in config.plugins)
                {
                    if (p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower())
                    {
                        JsonGeneric pgConf = new JsonGeneric();
                        try
                        {
                            using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters)))
                                pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData));
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Decrypt error1 " + ex.Message);
                        }
                        finally
                        {
                            pgConf = null;
                        }

                        if (!resource_plugin.Contains(p.resource_plugin))
                        {
                            resource_plugin.Add(p.resource_plugin);
                        }
                    }
                }


                foreach (Int64 rp in resource_plugin)
                {
                    DebugLog("{" + plugin.GetPluginId().AbsoluteUri + "} Resource plugin " + rp);

                    Dictionary <String, Object> connectorConf = new Dictionary <String, Object>();
                    List <PluginConnectorBaseDeployPackageMapping> mapping = new List <PluginConnectorBaseDeployPackageMapping>();

                    Boolean enableDeploy = false;

                    Int64 r = 0;

                    try
                    {
                        foreach (PluginConfig p in config.plugins)
                        {
                            if ((p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower()) && (p.resource_plugin == rp))
                            {
                                r = p.resource;

                                Dictionary <String, String> tmp = new Dictionary <string, string>();
                                foreach (PluginConfigMapping m in p.mapping)
                                {
                                    mapping.Add(new PluginConnectorBaseDeployPackageMapping(m.data_name, m.data_type, m.is_id, m.is_unique_property, m.is_password, m.is_login, m.is_name));
                                }

                                enableDeploy = p.enable_deploy;

                                JsonGeneric pgConf = new JsonGeneric();
                                try
                                {
                                    if (cert == null)
                                    {
                                        throw new Exception("Certificate is null");
                                    }

                                    using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters)))
                                        pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData));
                                }
                                catch (Exception ex)
                                {
                                    throw new Exception("Decrypt error: " + ex.Message);
                                }

                                if ((pgConf.data == null) || (pgConf.data.Count == 0))
                                {
                                    continue;
                                }

                                Int32 kCol = pgConf.GetKeyIndex("key");
                                Int32 vCol = pgConf.GetKeyIndex("value");

                                if (!String.IsNullOrWhiteSpace(p.mail_domain))
                                {
                                    PluginBase.FillConfig(plugin, ref connectorConf, "iam_mail_domain", p.mail_domain);
                                }
                                //connectorConf.Add("iam_mail_domain", p.mail_domain);

                                foreach (String[] d1 in pgConf.data)
                                {
                                    PluginBase.FillConfig(plugin, ref connectorConf, d1[kCol], d1[vCol].ToString());
                                }

                                /*
                                 * if (!connectorConf.ContainsKey(d1[kCol]))
                                 *  connectorConf.Add(d1[kCol], d1[vCol].ToString());*/
                            }
                        }

                        //Deploy ocorre antes da importação
                        //Para que na importação ja apareça os registros que foram publicados pelo deploy
                        try
                        {
                            System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(plugin.GetType());
                            DirectoryInfo dirFrom          = new DirectoryInfo(Path.Combine(basePath, "In\\" + Path.GetFileNameWithoutExtension(asm.Location) + "\\rp" + rp));

                            DebugLog("{" + plugin.GetPluginId().AbsoluteUri + "} RP =" + rp + ", r = " + r + " => path " + dirFrom.FullName + ", exists? " + dirFrom.Exists);

                            if (enableDeploy)
                            {
                                //Verifica se há algo para processar
                                if (dirFrom.Exists)
                                {
                                    ProcessDeploy(r, rp, connectorConf, mapping);
                                }
                            }
                            else
                            {
                                TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Deploy disabled");

                                //Exclui os arquivos
                                if (dirFrom.Exists)
                                {
                                    foreach (FileInfo f in dirFrom.GetFiles("*.iamdat"))
                                    {
                                        f.Delete();
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on deploy: " + ex.Message);
                        }


                        if (!deployOnly)
                        {
                            try
                            {
                                //O import não é desabilitado, pois ele é necessário para relatório de consistência
                                //o Engine não utilizará ele para adicionar novas entidades
                                ProcessImport(r, rp, connectorConf, mapping);
                            }
                            catch (Exception ex)
                            {
                                TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on import: " + ex.Message);
                            }
                        }

                        executionCount++;
                        if (executionCount > 50)
                        {
                            executionCount = 0;
                            TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Cleaning up proccess");
                            System.Diagnostics.Process.GetCurrentProcess().Kill();
                        }
                    }
                    catch (Exception ex)
                    {
                        TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on parse config: " + ex.Message);
                    }
                    finally
                    {
                        connectorConf.Clear();
                        connectorConf = null;

                        mapping.Clear();
                        mapping = null;
                    }
                }
            }
            finally
            {
                cert     = null;
                certPass = null;
            }
        }
Beispiel #21
0
        private void StartAgents()
        {
            List <Int64> resource = new List <Int64>();

            //Separa os contextos
            String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));

            OpenSSL.X509.X509Certificate cert = CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass);

            try
            {
                foreach (PluginConfig p in config.plugins)
                {
                    if (p.uri.ToLower() == plugin.GetPluginId().AbsoluteUri.ToLower())
                    {
                        Dictionary <String, Object> connectorConf = new Dictionary <String, Object>();

                        JsonGeneric pgConf = new JsonGeneric();
                        try
                        {
                            if (cert == null)
                            {
                                throw new Exception("Certificate is null");
                            }

                            using (CryptApi cApi = CryptApi.ParsePackage(cert, Convert.FromBase64String(p.parameters)))
                                pgConf.FromJsonString(Encoding.UTF8.GetString(cApi.clearData));
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Decrypt error: " + ex.Message);
                        }

                        if ((pgConf.data == null) || (pgConf.data.Count == 0))
                        {
                            continue;
                        }

                        Int32 kCol = pgConf.GetKeyIndex("key");
                        Int32 vCol = pgConf.GetKeyIndex("value");

                        foreach (String[] d1 in pgConf.data)
                        {
                            PluginBase.FillConfig(plugin, ref connectorConf, d1[kCol], d1[vCol].ToString());
                        }

                        /*if (!connectorConf.ContainsKey(d1[kCol]))
                         *  connectorConf.Add(d1[kCol], d1[vCol].ToString());*/
                        try
                        {
                            StartAgents(connectorConf);
                        }
                        catch (Exception ex)
                        {
                            TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on start agent: " + ex.Message);
                        }
                        finally
                        {
                            connectorConf.Clear();
                            connectorConf = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TextLog.Log("PluginStarter", "{" + plugin.GetPluginId().AbsoluteUri + "} Error on parse config: " + ex.Message);
            }

            cert     = null;
            certPass = null;
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            CertificateAuthority ca = new CertificateAuthority("123456", "RQ`EI'F9f+{;9}7![ooa");

            ca.LoadOrCreateCA("license-cert.pfx", "SafeID IAM License Server");

            Uri installKey = null;

            try
            {
                installKey = new Uri(args[0]);
            }
            catch {
                Console.WriteLine("Erro ao realizar o tratamento da chave de instalação");
                Use();
            }

            uint qty = 0;

            try
            {
                qty = uint.Parse(args[1]);
            }
            catch
            {
                Console.WriteLine("Erro ao realizar o tratamento da chave de instalação");
                Use();
            }

            DateTime?date = null;
            Boolean  temp = false;

            if (args.Length > 2)
            {
                try
                {
                    date = DateTime.Parse(args[2]);
                    temp = true;
                }
                catch
                {
                    Console.WriteLine("Erro ao realizar o tratamento da chave de instalação");
                    Use();
                }
            }


            X509Certificate key = IAMKey.GenerateLicense(ca, installKey, true, qty, temp, date);

            String sKey = CATools.X509ToBase64(key);

            try
            {
                IAMKeyData k = IAMKey.ExtractFromCert(sKey);
                Console.WriteLine("Licen\x00e7a gerada com sucesso");
            }
            catch (Exception ex) {
                Console.WriteLine("Falha na checagem de consistência: " + ex.Message);
                return;
            }


            using (FileStream stream = System.IO.File.Open(DateTime.Now.ToString("yyyyMMddHHmmss") + ".cer", FileMode.Create))
                using (BinaryWriter writer = new BinaryWriter(stream))
                    writer.Write(Convert.FromBase64String(sKey));



            using (FileStream stream = System.IO.File.Open(DateTime.Now.ToString("yyyyMMddHHmmss") + ".cer.txt", FileMode.Create))
                using (BinaryWriter writer = new BinaryWriter(stream))
                    writer.Write(Encoding.UTF8.GetBytes(sKey));
        }
Beispiel #23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Request.InputStream.Position = 0;

                JSONRequest req = JSON.GetRequest(Request.InputStream);

                JsonGeneric data = new JsonGeneric();
                data.FromJsonString(req.data);

                if (data.data.Count == 0)
                {
                    return;
                }

                using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyConfig config = new ProxyConfig();
                    config.GetDBConfig(db.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (config.fqdn == null) //Não encontrou o proxy
                    {
                        return;
                    }

                    String uri = Tools.Tool.TrataInjection(data.data[0][data.GetKeyIndex("uri")]);

                    DataTable dt = db.Select("select * from plugin where uri = '" + uri + "'");

                    if ((dt == null) || (dt.Rows.Count == 0))
                    {
                        return;
                    }

                    DirectoryInfo pluginsDir = null;

                    using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                        pluginsDir = new DirectoryInfo(c.GetItem("pluginFolder"));

                    if (pluginsDir == null)
                    {
                        throw new Exception("Parâmtro 'pluginFolder' não encontrado");
                    }

                    if (pluginsDir.Exists)
                    {
                        FileInfo f = new FileInfo(Path.Combine(pluginsDir.FullName, dt.Rows[0]["assembly"].ToString()));

                        if (f.Exists)
                        {
                            Byte[] fData    = File.ReadAllBytes(f.FullName);
                            String fileHash = CATools.SHA1Checksum(fData);

                            Int32 ci = data.GetKeyIndex("checksum");
                            if ((ci != -1) && (data.data[0][ci] == fileHash))
                            {
                                ReturnHolder.Controls.Add(new LiteralControl("{ \"name\":\"" + f.Name + "\", \"status\":\"updated\"}"));
                            }
                            else
                            {
                                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                                using (CryptApi cApi = new CryptApi(CATools.LoadCert(Convert.FromBase64String(config.client_cert), certPass), fData))
                                    ReturnHolder.Controls.Add(new LiteralControl("{ \"name\":\"" + f.Name + "\", \"status\":\"outdated\", \"date\":\"" + f.LastWriteTimeUtc.ToString("yyyy-MM-dd HH:mm:ss") + "\", \"content\":\"" + Convert.ToBase64String(cApi.ToBytes()) + "\"}"));
                            }

                            fData = new Byte[0];
                        }
                    }

                    /*
                     * ProxyConfig config = new ProxyConfig();
                     * config.GetDBConfig(IAMDatabase.GetWebConnection(), ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);
                     *
                     * if (config.fqdn != null)
                     * {
                     *  ReturnHolder.Controls.Add(new LiteralControl(config.ToJsonString()));
                     * }*/
                }
            }
            catch (Exception ex)
            {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }