Esempio n. 1
0
        private void ImportRegistersStruct(ProxyConfig config, JsonGeneric jData, FileInfo f, JSONRequest req, IAMDatabase db)
        {
            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
            Int32 pkgCol            = jData.GetKeyIndex("package");


            if (resourcePluginCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportStruct] Erro on find column 'resource_plugin' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            if (pkgCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportStruct] Erro on find column 'package' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }

            //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("file_name", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("resource_plugin", typeof(Int64)));
            dtBulk.Columns.Add(new DataColumn("import_id", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("package_id", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("package", typeof(String)));

            foreach (String[] dr in jData.data)
            {
                PluginConnectorBaseImportPackageStruct pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageStruct>(dr[pkgCol]);
                dtBulk.Rows.Add(new Object[] { DateTime.Now, f.Name, dr[resourcePluginCol], pkg.importId, pkg.pkgId, JSON.Serialize2(pkg) });
            }

            db.BulkCopy(dtBulk, "collector_imports_struct");

            //Atualiza os registros importados deste arquivo para liberar o processamento
            //Isso avisa o sistema que estes registros estão livres para processamento
            db.ExecuteNonQuery("update collector_imports_struct set status = 'F' where [file_name] = '" + f.Name + "'", CommandType.Text, null);

#if DEBUG
            TextLog.Log("Inbound", "\t[ImportStruct] Imported " + dtBulk.Rows.Count + " registers for enterprise " + req.enterpriseid + " and proxy " + req.host);
#endif

            dtBulk.Dispose();
            dtBulk = null;

            jData = null;
        }
Esempio n. 2
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            List <String> prop = new List <String>();

            String ldapServer = config["ldap_server"].ToString();
            String username   = config["username"].ToString();
            String password   = config["password"].ToString();
            String ou_base    = (config.ContainsKey("ou_base") ? config["ou_base"].ToString() : "");
            String _dnBase    = "";

            LDAP ldap = new LDAP(ldapServer, username, password, _dnBase);

            LDAP.DebugLog reg = new LDAP.DebugLog(delegate(String text)
            {
#if DEBUG
                //Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "LDAP log: " + text, "");
#endif
            });

            ldap.Log += reg;

            try
            {
                ldap.Bind();
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, "Error on connect to ActiveDirectory: " + ex.Message);
                Log2(this, PluginLogType.Error, 0, 0, "Error on connect to ActiveDirectory: " + ex.Message, "");
                ldap = null;
                return;
            }

            DirectoryEntry entry = null;
            try
            {
                //Caso haja o ou_base, buscar/criar a OU para listar os usuários
                if (!String.IsNullOrWhiteSpace(ou_base))
                {
                    entry = ldap.AddContainerTree(ou_base);
                }
            }
            catch { }

            //Realiza a busca de todas as OUs e grupos
            if (ImportPackageStruct != null)
            {
                PluginConnectorBaseImportPackageStruct structPackage = new PluginConnectorBaseImportPackageStruct(importId);

                try
                {
                    if (entry == null)
                    {
                        entry = ldap.DirectoryEntryRoot;
                    }

                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.SearchScope = SearchScope.Subtree;
                    search.Filter      = "(objectCategory=group)";
                    search.PropertiesToLoad.Add("distinguishedName");
                    search.PropertiesToLoad.Add("name");

                    SearchResultCollection result = search.FindAll();

                    if (result != null)
                    {
                        foreach (SearchResult sr in result)
                        {
                            try
                            {
                                structPackage.AddGroup(sr.Properties["name"][0].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, PluginLogType.Error, "Erro ao listar o grupo (" + sr.Path + "): " + ex.Message);
                            }
                            finally
                            {
                            }
                        }
                    }

                    search.Dispose();
                }
                catch (Exception ex)
                {
                    Log(this, PluginLogType.Error, ex.Message);
                }


                try
                {
                    if (entry == null)
                    {
                        entry = ldap.DirectoryEntryRoot;
                    }

                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.SearchScope = SearchScope.Subtree;
                    search.Filter      = "(objectClass=organizationalUnit)";
                    search.PropertiesToLoad.Add("distinguishedName");
                    search.PropertiesToLoad.Add("name");

                    SearchResultCollection result = search.FindAll();

                    if (result != null)
                    {
                        foreach (SearchResult sr in result)
                        {
                            try
                            {
                                /*
                                 * String dn = sr.Properties["distinguishedName"][0].ToString();
                                 * //String name = sr.Properties["name"][0].ToString();
                                 * String[] ou = dn.Replace(entry.Properties["distinguishedName"][0].ToString(), "").Replace(",", "").Replace("OU=", "\\").Trim(" ,".ToCharArray()).Split("\\".ToCharArray());
                                 *
                                 * Array.Reverse(ou);
                                 *
                                 * String path = "\\" + String.Join("\\", ou);*/

                                structPackage.AddContainer(DNToPath(sr.Properties["distinguishedName"][0].ToString(), entry));
                            }
                            catch (Exception ex)
                            {
                                Log(this, PluginLogType.Error, "Erro ao listar a OU (" + sr.Path + "): " + ex.Message);
                            }
                            finally
                            {
                            }
                        }
                    }

                    search.Dispose();
                }
                catch (Exception ex)
                {
                    Log(this, PluginLogType.Error, ex.Message);
                }

                //Envia o pacote da estrutura
                ImportPackageStruct(structPackage);
            }

            //Realiza a busca dos usuários
            try
            {
                //DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer, username, password, AuthenticationTypes.Secure);
                if (entry == null)
                {
                    entry = ldap.DirectoryEntryRoot;
                }

                DirectorySearcher search = new DirectorySearcher(entry);
                search.SearchScope = SearchScope.Subtree;
                //search.Filter = "(&(objectClass=user)(sAMAccountName=helvio.junior))";
                search.Filter = "(samAccountType=805306368)";
                search.PropertiesToLoad.Add("useraccountcontrol");
                search.PropertiesToLoad.Add("distinguishedName");
                search.PropertiesToLoad.Add("company");
                search.PropertiesToLoad.Add("department");
                search.PropertiesToLoad.Add("memberOf");

                foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping)
                {
                    if (!search.PropertiesToLoad.Contains(m.dataName))
                    {
                        search.PropertiesToLoad.Add(m.dataName);
                    }
                }

                /*
                 * search.PropertiesToLoad.Add("displayName");
                 * search.PropertiesToLoad.Add("mail");
                 * search.PropertiesToLoad.Add("sAMAccountName");
                 * search.PropertiesToLoad.Add("objectClass");
                 * search.PropertiesToLoad.Add("distinguishedName");
                 * search.PropertiesToLoad.Add("lastLogonTimestamp");
                 * search.PropertiesToLoad.Add("whenCreated");
                 *
                 * search.PropertiesToLoad.Add("lockoutTime");
                 * search.PropertiesToLoad.Add("proxyAddresses");
                 * search.PropertiesToLoad.Add("mailNickname");
                 * search.PropertiesToLoad.Add("telephoneNumber");
                 * search.PropertiesToLoad.Add("userPrincipalName");
                 * search.PropertiesToLoad.Add("memberOf");*/

                SearchResultCollection result = search.FindAll();

                if (result != null)
                {
                    foreach (SearchResult sr in result)
                    {
                        PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);

                        try
                        {
                            using (DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + sr.Properties["distinguishedName"][0].ToString(), username, password))
                            {
                                entry1.AuthenticationType = AuthenticationTypes.Secure;
                                String ou = entry1.Parent.Path;
                                ou = ou.Replace("LDAP://" + ldapServer + "/", "");

                                package.container = DNToPath(ou, entry);

                                if (fieldMapping.Exists(f => (f.dataName == "organizationslUnit")) || fieldMapping.Exists(f => (f.dataName == "organizationslunit")))
                                {
                                    package.AddProperty("organizationslUnit", ou, "string");
                                }
                            }


                            foreach (String p in sr.Properties.PropertyNames)
                            {
                                //Separa os itens que mecessita algum tratamento
                                switch (p.ToLower())
                                {
                                case "lastlogon":
                                case "whencreated":
                                case "lockouttime":
                                    try
                                    {
                                        Int64    tmp  = Int64.Parse(sr.Properties[p][0].ToString());
                                        DateTime tmp2 = DateTime.FromFileTime(tmp);

                                        if (tmp2.Year > 1970)    //Se a data for inferior nem envia
                                        {
                                            package.AddProperty(p, tmp2.ToString("o"), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "datetime"));
                                        }
                                    }
                                    catch (Exception ex)
                                    { }
                                    break;

                                case "useraccountcontrol":
                                    foreach (Object p1 in sr.Properties[p])
                                    {
                                        UserAccountControl ctrl = (UserAccountControl)p1;

                                        foreach (UserAccountControl c in Enum.GetValues(typeof(UserAccountControl)))
                                        {
                                            //Verifica se está utilizando
                                            if ((ctrl & c) == c)
                                            {
                                                package.AddProperty(p, c.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                            }
                                        }
                                    }

                                    break;

                                case "memberof":
                                    foreach (Object p1 in sr.Properties[p])
                                    {
                                        //Trata o grupo
                                        try
                                        {
                                            using (DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + p1.ToString(), username, password))
                                            {
                                                entry1.AuthenticationType = AuthenticationTypes.Secure;
                                                package.AddGroup(entry1.Properties["name"][0].ToString());
                                            }
                                        }
                                        catch { }


                                        if (fieldMapping.Exists(m => (m.dataName == "memberOf")))
                                        {
                                            package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                        }
                                    }

                                    break;

                                default:
                                    foreach (Object p1 in sr.Properties[p])
                                    {
                                        package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                    }
                                    break;
                                }
                            }

                            ImportPackageUser(package);
                        }
                        catch (Exception ex)
                        {
                            Log(this, PluginLogType.Error, "Erro ao importar o registro (" + sr.Path + "): " + ex.Message);
                        }
                        finally
                        {
                            package.Dispose();
                            package = null;
                        }
                    }
                }

                search.Dispose();
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, ex.Message);
            }
        }