Esempio n. 1
0
        public SHARE_INFO_1[] EnumNetShares(string Server)
        {
            List <SHARE_INFO_1> ShareInfos = new List <SHARE_INFO_1>();
            int           entriesread      = 0;
            int           totalentries     = 0;
            int           resume_handle    = 0;
            int           nStructSize      = Marshal.SizeOf(typeof(SHARE_INFO_1));
            IntPtr        bufPtr           = IntPtr.Zero;
            StringBuilder server           = new StringBuilder(Server);
            int           ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);

            if (ret == NERR_Success)
            {
                IntPtr currentPtr = bufPtr;
                for (int i = 0; i < entriesread; i++)
                {
                    SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                    ShareInfos.Add(shi1);
                    //Remember, 64-bit systems have 64-bit pointers. Using ToInt32 will cause an ArithmeticOverview exception.
                    //Use ToInt64 if you need to.
                    currentPtr = new IntPtr(currentPtr.ToInt32() + nStructSize);
                }
                NetApiBufferFree(bufPtr);
                return(ShareInfos.ToArray());
            }
            else
            {
                ShareInfos.Add(new SHARE_INFO_1("ERROR=" + ret.ToString(), 10, string.Empty));
                return(ShareInfos.ToArray());
            }
        }
Esempio n. 2
0
        public static string[] EnumShares(string serverName, string userName, string domainName, string password)
        {
            string[] shareList = null;

            using (new ImpersonationHelper(userName, domainName, password))
            {
                List <string> ShareInfos    = new List <string>();
                int           entriesread   = 0;
                int           totalentries  = 0;
                int           resume_handle = 0;
                IntPtr        bufPtr        = IntPtr.Zero;
                int           nStructSize   = Marshal.SizeOf(typeof(SHARE_INFO_1));
                StringBuilder server        = new StringBuilder(serverName);

                if (NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle)
                    == (int)NetError.NERR_Success)
                {
                    IntPtr currentPtr = bufPtr;

                    for (int i = 0; i < entriesread; i++)
                    {
                        SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                        ShareInfos.Add(shi1.shi1_netname);
                        currentPtr = new IntPtr(currentPtr.ToInt64() + nStructSize);
                    }

                    NetApiBufferFree(bufPtr);
                    shareList = ShareInfos.ToArray();
                }
            }

            return(shareList);
        }
Esempio n. 3
0
        public List <string> GetShares(List <string> targetedComputers)
        {
            List <string> filePathstoReview = new List <string>();

            foreach (string singleComp in targetedComputers)
            {
                IntPtr buffer;
                uint   entriesread;
                uint   totalentries;
                uint   resume_handle;

                if (NetShareEnum(singleComp, 1, out buffer, -1, out entriesread, out totalentries, out resume_handle) == 0)
                {
                    Int64     ptr     = buffer.ToInt64();
                    ArrayList alShare = new ArrayList();
                    for (int i = 0; i < entriesread; i++)
                    {
                        SHARE_INFO_1 shareInfo = (SHARE_INFO_1)Marshal.PtrToStructure(new IntPtr(ptr), typeof(SHARE_INFO_1));
                        if (shareInfo.shi1_type == 0) //Disk drive
                        {
                            alShare.Add(shareInfo.shi1_netname);
                        }
                        ptr += Marshal.SizeOf(shareInfo);
                    }
                    for (int i = 0; i < alShare.Count; i++)
                    {
                        filePathstoReview.Add("\\\\" + singleComp + "\\" + alShare[i].ToString());
                    }
                }
            }

            return(filePathstoReview);
        }
        private static string[] GetSharesUsingNetAPI(string server)
        {
            List <string> shareList     = new List <String>();
            int           entriesread   = 0;
            int           totalentries  = 0;
            IntPtr        resume_handle = IntPtr.Zero;
            int           nStructSize   = Marshal.SizeOf(typeof(SHARE_INFO_1));
            IntPtr        bufPtr        = IntPtr.Zero;
            int           ret           = NetShareEnum(server, 1, out bufPtr, MAX_PREFERRED_LENGTH, out entriesread, out totalentries, resume_handle);

            if (ret == NERR_Success)
            {
                int currentPtr = (int)bufPtr;
                for (int i = 0; i < entriesread; i++)
                {
                    SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure((IntPtr)currentPtr, typeof(SHARE_INFO_1));
                    if (shi1.shi1_type == STYPE_DISKTREE)
                    {
                        shareList.Add(shi1.shi1_netname);
                    }
                    currentPtr += nStructSize;
                }
            }
            NetApiBufferFree(bufPtr);
            string[] shares = new string[shareList.Count];
            shareList.CopyTo(shares);
            return(shares);
        }
Esempio n. 5
0
        private void bwShare_DoWork(object sender, DoWorkEventArgs e)
        {
            String pc = (String)e.Argument;

            IntPtr res = IntPtr.Zero;
            int    n = 0, m = 0;
            int    r = NetShareEnum(new StringBuilder("\\\\" + pc), 1, ref res, MAX_PREFERRED_LENGTH, ref n, ref m, IntPtr.Zero);

            if (r == 0)
            {
                try {
                    List <string> shares = new List <string>();
                    for (int x = 0; x < n; x++)
                    {
                        SHARE_INFO_1 share = (SHARE_INFO_1)Marshal.PtrToStructure(new IntPtr(res.ToInt64() + Marshal.SizeOf(typeof(SHARE_INFO_1)) * x), typeof(SHARE_INFO_1));
                        if (share.shi1_type == SHARE_TYPE.STYPE_DISKTREE)
                        {
                            shares.Add("\\\\" + pc + "\\" + share.shi1_netname);
                        }
                    }
                    e.Result = shares;
                }
                finally {
                    NetApiBufferFree(res);
                }
            }
        }
Esempio n. 6
0
        private void EnumNetShares(string Server)
        {
            if (!CheckServerAvailablity(Server, 445))
            {
                Logger.WriteLine(String.Format("[x] Cannot contact server {0} on port 445", Server));
                return;
            }
            Logger.WriteLine(String.Format("[*] Server {0} listening on port 445", Server));

            int           entriesread   = 0;
            int           totalentries  = 0;
            int           resume_handle = 0;
            int           nStructSize   = Marshal.SizeOf(typeof(SHARE_INFO_1));
            IntPtr        bufPtr        = IntPtr.Zero;
            StringBuilder server        = new StringBuilder(Server);
            int           ret           = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);

            if (ret == NERR_Success)
            {
                IntPtr currentPtr = bufPtr;
                for (int i = 0; i < entriesread; i++)
                {
                    SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                    Logger.WriteLine(String.Format("[*] Server: {0} ShareName: {1}, ShareType: {2}, Remark {3}", server, shi1.shi1_netname, shi1.shi1_type, shi1.shi1_remark));
                    currentPtr += nStructSize;
                }
                NetApiBufferFree(bufPtr);
            }
            else
            {
                Logger.WriteLine(String.Format("[x] Server: {0}, Error={1}", Server, ret.ToString()));
                return;
            }
        }
Esempio n. 7
0
 public static SHARE_INFO_1[] EnumNetShares(string Server)
 {
     List<SHARE_INFO_1> ShareInfos = new List<SHARE_INFO_1>();
     int entriesread = 0;
     int totalentries = 0;
     int resume_handle = 0;
     int nStructSize = Marshal.SizeOf(typeof(SHARE_INFO_1));
     IntPtr bufPtr = IntPtr.Zero;
     StringBuilder server = new StringBuilder(Server);
     int ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);
     if (ret == NERR_Success)
     {
         IntPtr currentPtr = bufPtr;
         for (int i = 0; i < entriesread; i++)
         {
             SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
             ShareInfos.Add(shi1);
             currentPtr += nStructSize;
         }
         NetApiBufferFree(bufPtr);
         return ShareInfos.ToArray();
     }
     else
     {
         ShareInfos.Add(new SHARE_INFO_1("ERROR=" + ret.ToString(), 10, string.Empty));
         return ShareInfos.ToArray();
     }
 }
Esempio n. 8
0
        private static List <ShareInfo> GetShareInfoNT(string serverName, IList <ShareType> shareTypes)
        {
            int              level = 2;
            int              entriesRead, totalEntries, nRet, hResume = 0;
            IntPtr           pBuffer       = IntPtr.Zero;
            List <ShareInfo> shareInfoList = new List <ShareInfo>();

            try
            {
                nRet = NetShareEnum(serverName, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume);

                if (nRet == ERROR_ACCESS_DENIED)
                {
                    //Need admin for level 2, drop to level 1
                    level = 1;
                    nRet  = NetShareEnum(serverName, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume);
                }

                if (nRet == NO_ERROR && entriesRead > 0)
                {
                    Type t      = (level == 2) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
                    int  offset = Marshal.SizeOf(t);

                    for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset)
                    {
                        IntPtr pItem = new IntPtr(lpItem);
                        if (level == 1)
                        {
                            SHARE_INFO_1 shareInfo = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
                            if (shareTypes.Contains(shareInfo.ShareType))
                            {
                                shareInfoList.Add(new ShareInfo(serverName, shareInfo.NetName, string.Empty, shareInfo.ShareType, shareInfo.Remark));
                            }
                        }
                        else
                        {
                            SHARE_INFO_2 shareInfo = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
                            if (shareTypes.Contains(shareInfo.ShareType))
                            {
                                shareInfoList.Add(new ShareInfo(serverName, shareInfo.NetName, shareInfo.Path, shareInfo.ShareType, shareInfo.Remark));
                            }
                        }
                    }
                }
            }
            finally
            {
                // Clean up buffer allocated by system
                if (IntPtr.Zero != pBuffer)
                {
                    NetApiBufferFree(pBuffer);
                }
            }
            return(shareInfoList);
        }
Esempio n. 9
0
 public override bool GetItemIsContainer(int index)
 {
     if (index == 0)
     {
         return(true);
     }
     else
     {
         SHARE_INFO_1 info = internal_list.Keys[index - 1];
         return((info.shi1_type == NetshareType.DISKTREE) || (info.shi1_type == NetshareType.SPECIAL));
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Enumerates the shares on Windows NT
        /// </summary>
        /// <param name="server">The server name</param>
        /// <param name="shares">The ShareCollection</param>
        protected static void EnumerateSharesNT(string server, ShareCollection shares)
        {
            int    level = 2;
            int    entriesRead, totalEntries, nRet, hResume = 0;
            IntPtr pBuffer = IntPtr.Zero;

            try
            {
                nRet = NetShareEnum(server, level, out pBuffer, -1,
                                    out entriesRead, out totalEntries, ref hResume);

                if (ERROR_ACCESS_DENIED == nRet)
                {
                    //Need admin for level 2, drop to level 1
                    level = 1;
                    nRet  = NetShareEnum(server, level, out pBuffer, -1,
                                         out entriesRead, out totalEntries, ref hResume);
                }

                if (NO_ERROR == nRet && entriesRead > 0)
                {
                    Type t      = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
                    int  offset = Marshal.SizeOf(t);

                    IntPtr pItem = pBuffer;

                    for (long i = 0; i < entriesRead; i++)
                    {
                        if (1 == level)
                        {
                            SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
                            shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                        }
                        else
                        {
                            SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
                            shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                        }

                        pItem = IntPtr.Add(pItem, offset);
                    }
                }
            }
            finally
            {
                // Clean up buffer allocated by system
                if (IntPtr.Zero != pBuffer)
                {
                    NetApiBufferFree(pBuffer);
                }
            }
        }
Esempio n. 11
0
        public override string GetItemDisplaySummaryInfo(int index)
        {
            string ret = string.Empty;

            if (index != 0)
            {
                SHARE_INFO_1 info = internal_list.Keys[index - 1];
                ret = string.Format
                          ("{0} {1}",
                          info.shi1_type.ToString(),
                          info.shi1_remark);
            }
            return(ret);
        }
Esempio n. 12
0
        public static List <string> GetSharedPrinter(string Server)
        {
            List <string> lstString = new List <string>();

            SHARE_INFO_1[] shareInfo = EnumNetShares(Server);

            for (int i = 0; i < shareInfo.Length; i++)
            {
                SHARE_INFO_1 info = shareInfo[i];
                if (info.shi1_type == Convert.ToInt32(SHARE_TYPE.STYPE_PRINTQ))
                {
                    lstString.Add(info.shi1_netname);
                }
            }

            return(lstString);
        }
Esempio n. 13
0
        public static string[] EnumShares(string serverName, string userName, string domainName, string password)
        {
            string[] shareList = null;

            try
            {
                using (new ImpersonationHelper(userName, domainName, password))
                {
                    List <string> ShareInfos    = new List <string>();
                    int           entriesread   = 0;
                    int           totalentries  = 0;
                    int           resume_handle = 0;
                    IntPtr        bufPtr        = IntPtr.Zero;
                    int           nStructSize   = Marshal.SizeOf(typeof(SHARE_INFO_1));
                    StringBuilder server        = new StringBuilder(serverName);

                    if (NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle)
                        == (int)NetError.NERR_Success)
                    {
                        IntPtr currentPtr = bufPtr;

                        for (int i = 0; i < entriesread; i++)
                        {
                            SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                            ShareInfos.Add(shi1.shi1_netname);
                            currentPtr = new IntPtr(currentPtr.ToInt64() + nStructSize);
                        }

                        NetApiBufferFree(bufPtr);
                        shareList = ShareInfos.ToArray();
                    }
                }
            }
            catch (ImersonationFailureException ex)
            {
                throw new ApplicationException(string.Format("Failed to impersontate user {0}/{1} when enumerate share on server {2}", domainName, userName, serverName), ex);
            }
            catch
            {
                throw new ApplicationException(string.Format("Failed to enumerate share on server {0}", serverName));
            }

            return(shareList);
        }
Esempio n. 14
0
        public static Share GetNetShareInfo(string serverName, string netName)
        {
            IntPtr ptr = IntPtr.Zero;

            int errCode = NetShareGetInfo(serverName, netName, 1, ref ptr);

            if (errCode == NO_ERROR)
            {
                SHARE_INFO_1 shareInfo = (SHARE_INFO_1)
                                         Marshal.PtrToStructure(ptr, typeof(SHARE_INFO_1));
                Share sh = new Share(@"\\" + serverName, shareInfo.NetName, "", shareInfo.ShareType, shareInfo.Remark);
                NetApiBufferFree(ptr);
                return(sh);
            }
            else
            {
                throw new Exception(FormatMessage(errCode));
            }
        }
Esempio n. 15
0
        protected static void EnumerateSharesNT(string server, ShareCollection shares)
        {
            int    level = 2;
            int    entriesRead, totalEntries, nRet, hResume = 0;
            IntPtr pBuffer = IntPtr.Zero;

            try
            {
                nRet = NetShareEnum(server, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume);
                if (ERROR_ACCESS_DENIED == nRet)
                {
                    level = 1;
                    nRet  = NetShareEnum(server, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume);
                }
                if (NO_ERROR == nRet && entriesRead > 0)
                {
                    Type t      = (2 == level)?typeof(SHARE_INFO_2):typeof(SHARE_INFO_1);
                    int  offset = Marshal.SizeOf(t);
                    for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset)
                    {
                        IntPtr pItem = new IntPtr(lpItem);
                        if (1 == level)
                        {
                            SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
                            shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                        }
                        else
                        {
                            SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
                            shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                        }
                    }
                }
            }
            finally
            {
                if (IntPtr.Zero != pBuffer)
                {
                    NetApiBufferFree(pBuffer);
                }
            }
        }
        /// <summary>
        /// Gets list of the shared folders on a given network computer. Only
        /// non special folders are returned.
        /// </summary>
        /// <param name="in_network_computer">Network computer name</param>
        /// <returns>List of the shared folders</returns>
        public static List <string> GetSharedFolders(string in_network_computer)
        {
            List <SHARE_INFO_1> ShareInfos = new List <SHARE_INFO_1>();
            int    entriesread             = 0;
            int    totalentries            = 0;
            int    resume_handle           = 0;
            int    nStructSize             = Marshal.SizeOf(typeof(SHARE_INFO_1));
            IntPtr bufPtr = IntPtr.Zero;

            StringBuilder server = new StringBuilder(in_network_computer);

            int ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);

            if (ret == NERR_Success)
            {
                IntPtr currentPtr = bufPtr;
                for (int i = 0; i < entriesread; i++)
                {
                    SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                    ShareInfos.Add(shi1);
                    currentPtr = new IntPtr(currentPtr.ToInt32() + nStructSize);
                }
                NetApiBufferFree(bufPtr);

                // convert to string array (add only non special folders)
                List <string> retval = new List <string>();
                foreach (SHARE_INFO_1 info in ShareInfos)
                {
                    if (info.shi1_type == (uint)SHARE_TYPE.STYPE_DISKTREE)
                    {
                        retval.Add(info.shi1_netname);
                    }
                }

                return(retval);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 17
0
        //nb. share info 1 not 502/3 due to privilege issues :-(
        public SHARE_INFO_1[] EnumNetShares(string Server)
        {
            List <SHARE_INFO_1> ShareInfos = new List <SHARE_INFO_1>();
            int           entriesread      = 0;
            int           totalentries     = 0;
            int           resume_handle    = 0;
            int           nStructSize      = Marshal.SizeOf(typeof(SHARE_INFO_1));
            IntPtr        bufPtr           = IntPtr.Zero;
            StringBuilder server           = new StringBuilder(Server);

            int ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);

            if (ret == NERR_Success)
            {
                IntPtr currentPtr = bufPtr;
                for (int i = 0; i < entriesread; i++)
                {
                    if (MainWindow._cancellationToken.IsCancellationRequested == true)
                    {
                        throw new OperationCanceledException();
                    }
                    SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                    ShareInfos.Add(shi1);


                    currentPtr = new IntPtr(currentPtr.ToInt32() + nStructSize);
                }
                NetApiBufferFree(bufPtr);
                return(ShareInfos.ToArray());
            }
            else
            {
                //ShareInfos.Add(new SHARE_INFO_1("ERROR=" + ret.ToString(), 10, string.Empty));
                //return ShareInfos.ToArray();
                return(null);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// 检查IP的共享文件夹
        /// </summary>
        /// <param name="Server">IP地址</param>
        /// <returns>共享文件夹目录</returns>
        static private ArrayList EnumNetShares(string Server)
        {
            // List<SHARE_INFO_1> ShareInfos = new List<SHARE_INFO_1>();
            ArrayList     shareinfo     = new ArrayList();
            int           entriesread   = 0;
            int           totalentries  = 0;
            int           resume_handle = 0;
            int           nStructSize   = Marshal.SizeOf(typeof(SHARE_INFO_1));
            IntPtr        bufPtr        = IntPtr.Zero;
            StringBuilder server        = new StringBuilder(Server);
            //使用NetShareEnum获取远程文件夹共享内容
            int ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);

            if (ret == NERR_Success)
            {
                IntPtr currentPtr = bufPtr;
                for (int i = 0; i < entriesread; i++)
                {
                    SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                    if (shi1.shi1_type == 0)//Disk drive类型
                    {
                        shareinfo.Add(shi1.shi1_netname);
                    }

                    //64位系统需要调用64位指针, 使用 ToInt32 会出错,使用ToInt64
                    currentPtr = new IntPtr(currentPtr.ToInt64() + nStructSize);
                }
                NetApiBufferFree(bufPtr);

                return(shareinfo);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 19
0
        protected void SetUp()
        {
            var info = new SHARE_INFO_1();

            m_Share = new ShareInfo(info);
        }
Esempio n. 20
0
 public ShareInfo(SHARE_INFO_1 info)
 {
     m_Info = info;
 }
Esempio n. 21
0
 public ShareInfo()
 {
     m_Info = new SHARE_INFO_1();
 }
Esempio n. 22
0
        /// <summary>
        /// Enumerates the shares on Windows NT
        /// </summary>
        /// <param name="server">The server name</param>
        /// <param name="shares">The ShareCollection</param>
        protected static void EnumerateSharesNT(string server, ShareCollection shares)
        {
            int    level = 2;
            int    entriesRead, totalEntries, nRet, hResume = 0;
            IntPtr pBuffer = IntPtr.Zero;

            try
            {
                nRet = NetShareEnum(server, level, out pBuffer, -1,
                                    out entriesRead, out totalEntries, ref hResume);

                if (ERROR_ACCESS_DENIED == nRet)
                {
                    //Need admin for level 2, drop to level 1
                    level = 1;
                    nRet  = NetShareEnum(server, level, out pBuffer, -1,
                                         out entriesRead, out totalEntries, ref hResume);
                }

                if (NO_ERROR == nRet && entriesRead > 0)
                {
                    Type t      = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
                    int  offset = Marshal.SizeOf(t);

                    for (int i = 0, lpItem = pBuffer.ToInt32(); i < entriesRead; i++, lpItem += offset)
                    {
                        IntPtr pItem = new IntPtr(lpItem);
                        if (1 == level)
                        {
                            SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
                            if (si.ShareType == ShareType.Special && si.NetName.Length == 2)
                            {
                            }
                            else
                            {
                                shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
                                //Console.WriteLine(trim(si.NetName) + " no path         " + si.ShareType + "\t" + si.Remark);
                            }
                        }
                        else
                        {
                            SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
                            if (si.ShareType == ShareType.Special && si.NetName.Length == 2 && si.Path.Length == 3)
                            {
                            }
                            else
                            {
                                shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
                                //Console.Write(trim(si.NetName) + " " + trim(si.Path) + " " + si.ShareType + "\t" + si.Remark + "\n");
                            }
                        }
                    }
                }
            }
            finally
            {
                // Clean up buffer allocated by system
                if (IntPtr.Zero != pBuffer)
                {
                    NetApiBufferFree(pBuffer);
                }
            }
        }
Esempio n. 23
0
        public void SetUp()
        {
            var info = new SHARE_INFO_1();

            m_Share = new SharePanelItem(null, new ShareInfo(info));
        }
Esempio n. 24
0
 internal ShareInfo1(SHARE_INFO_1 shi1)
 {
     NetName = shi1.shi1_netname;
     Type    = (ShareTypes)shi1.shi1_type;
     Remark  = shi1.shi1_remark;
 }
Esempio n. 25
0
        static void Main(string[] args)
        {
            bool verboseDebug = Array.Exists(args, match => match.ToLower() == "-verbose");

            ThreadPool.SetMaxThreads(max_threadpool, max_threadpool);

            // ShowWindow(GetConsoleWindow(), 0);
            if (args.Length >= 2)
            {
                string option = args[0].ToLower();
                string domain = args[1];

                if (option == "passwordbruteforce")
                {
                    Console.WriteLine("Starting password brute force");
                    string query      = "";
                    string properties = "samaccountname";
                    string filter     = "";

                    try
                    {
                        filter = "(samaccountname=*" + args[3] + "*)";
                    }
                    catch
                    {
                        filter = "";
                    }

                    try
                    {
                        query = "(&(objectClass=user)" + filter + ")";
                        List <string> users = LdapQuery(domain, query, properties, false, true);
                        Console.WriteLine("Bruteforcing {0} accounts", users.Count);
                        foreach (string u in users)
                        {
                            Task t = Task.Run(() =>
                            {
                                using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
                                {
                                    if (verboseDebug)
                                    {
                                        Console.WriteLine("Password brute force against {0}\\{1}", domain, u);
                                    }
                                    // validate the credentials
                                    if (pc.ValidateCredentials(u, args[2]))
                                    {
                                        Console.WriteLine("[SUCCESS] {0}\\{1} password is {2}", domain, u, args[2]);
                                    }
                                }
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: PasswordBruteForce catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpallusers")
                {
                    string query      = "";
                    string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath,managedby,managedobjects";
                    try
                    {
                        query = "(&(objectClass=user))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpAllUsers catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumplocalgroup")
                {
                    string query        = "";
                    string properties   = "name";
                    string computername = "";

                    try
                    {
                        computername = "(name=*" + args[2] + "*)";
                    }
                    catch
                    {
                        computername = "";
                    }

                    try
                    {
                        query = "(&(objectClass=computer)" + computername + ")";
                        List <string> computers = LdapQuery(domain, query, properties, false, true);
                        Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count));
                        foreach (string c in computers)
                        {
                            Task t = Task.Run(() =>
                            {
                                DumpLocalAdminGroups(c);
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpLocalGroup catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpremotesession")
                {
                    string query        = "";
                    string properties   = "name";
                    string computername = "";
                    try
                    {
                        try
                        {
                            computername = args[2];
                            DumpRemoteSession(computername);
                        }
                        catch
                        {
                            query = "(&(objectClass=computer))";
                            List <string> computers = LdapQuery(domain, query, properties, false, true);
                            Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count));
                            foreach (string c in computers)
                            {
                                Task t = Task.Run(() =>
                                {
                                    DumpRemoteSession(c);
                                });
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpRemoteSession catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumplocaladmin")
                {
                    string query        = "";
                    string properties   = "name";
                    string computername = "";

                    try
                    {
                        computername = "(name=*" + args[2] + "*)";
                    }
                    catch
                    {
                        computername = "";
                    }

                    try
                    {
                        query = "(&(objectClass=computer)" + computername + ")";
                        List <string> computers = LdapQuery(domain, query, properties, false, true);
                        Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count));
                        foreach (string c in computers)
                        {
                            Console.WriteLine("\nComputer {0}\n------------------------", c);
                            DumpLocalAdminMembers(c, "Administrators");
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpLocalAdmin catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumplapspassword")
                {
                    string query        = "";
                    string properties   = "name,ms-mcs-AdmPwd";
                    string computername = "";

                    try
                    {
                        computername = "(name=*" + args[2] + "*)";
                    }
                    catch
                    {
                        computername = "";
                    }

                    try
                    {
                        query = "(&(objectClass=user)" + computername + ")";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: CheckAdmin catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "checkadmin")
                {
                    string query        = "";
                    string properties   = "name";
                    string computername = "";

                    try
                    {
                        computername = "(name=*" + args[2] + "*)";
                    }
                    catch
                    {
                        computername = "";
                    }

                    try
                    {
                        query = "(&(objectClass=computer)" + computername + ")";
                        List <string> computers = LdapQuery(domain, query, properties, false, true);
                        Console.WriteLine(String.Format("Querying {0} computer(s).", computers.Count));
                        foreach (string c in computers)
                        {
                            Task t = Task.Run(() =>
                            {
                                CheckLocalAdminRight(c);
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: CheckAdmin catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumptrust")
                {
                    Console.WriteLine("Domain Trust\n----------------------");
                    Domain currentDomain = Domain.GetCurrentDomain();
                    foreach (TrustRelationshipInformation d in currentDomain.GetAllTrustRelationships())
                    {
                        Console.WriteLine(String.Format("{0} <- ({1}){2} -> {3}", d.SourceName, d.TrustType, d.TrustDirection, d.TargetName));
                    }

                    Console.WriteLine("\nForest Trust\n----------------------");
                    Forest forest = Forest.GetCurrentForest();
                    foreach (TrustRelationshipInformation f in forest.GetAllTrustRelationships())
                    {
                        Console.WriteLine(String.Format("{0} <- ({1}){2} -> {3}", f.SourceName, f.TrustType, f.TrustDirection, f.TargetName));
                    }
                }
                else if (option == "dumpuser")
                {
                    string query      = "";
                    string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath,managedby,managedobjects";
                    try
                    {
                        query = "(&(objectClass=user)(samaccountname=*" + args[2] + "*))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpUser required a user argument");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpusersemail")
                {
                    string query      = "";
                    string properties = "name,samaccountname,mail";
                    try
                    {
                        query = "(&(objectClass=user))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpUsersEmail catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpuserpassword")
                {
                    string query      = "";
                    string properties = "name,samaccountname,userpassword";
                    try
                    {
                        query = "(&(objectClass=user))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpUserPassword catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpallcomputers")
                {
                    string query      = "";
                    string properties = "name,displayname,operatingsystem,description,adspath,objectcategory,serviceprincipalname,distinguishedname,cn,lastlogon,managedby,managedobjects";
                    try
                    {
                        query = "(&(objectClass=computer))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpAllComputers catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpcomputer")
                {
                    string query      = "";
                    string properties = "name,displayname,operatingsystem,description,adspath,objectcategory,serviceprincipalname,distinguishedname,cn,lastlogon,managedby,managedobjects";
                    try
                    {
                        query = "(&(objectClass=computer)(name=*" + args[2] + "))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpComputer required a computer name argument");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpallgroups")
                {
                    string query      = "";
                    string properties = "name,adspath,distinguishedname,member,memberof";
                    try
                    {
                        query = "(&(objectClass=group))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpAllGroups required a computer name argument");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumpgroup")
                {
                    string query      = "";
                    string properties = "name,adspath,distinguishedname,member,memberof";
                    try
                    {
                        query = "(&(objectClass=group)(name=*" + args[2] + "))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpGroup required a group name argument");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumppasswordpolicy")
                {
                    string query      = "";
                    string properties = "name,distinguishedName,msDS-MinimumPasswordLength,msDS-PasswordHistoryLength,msDS-PasswordComplexityEnabled,msDS-PasswordReversibleEncryptionEnabled,msDS-LockoutThreshold,msDS-PasswordSettingsPrecedence";
                    try
                    {
                        query = "(&(objectClass=msDS-PasswordSettings))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpPasswordPolicy catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "dumppwdlastset")
                {
                    // Based on https://www.trustedsec.com/blog/targeted-active-directory-host-enumeration/
                    string query      = "";
                    string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath";
                    var    date       = DateTime.Today.AddDays(-(DateTime.Today.Day + 90));
                    long   dateUtc    = date.ToFileTimeUtc();
                    try
                    {
                        query = "(&(objectCategory=computer)(pwdlastset>=" + dateUtc.ToString() + ")(operatingSystem=*windows*))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpPasswordPolicy catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "checkmanaged")
                {
                    /*
                     */
                    if (ListFilesSearchForManaged("\\\\" + domain + "\\SYSVOL", verboseDebug))
                    {
                        string query      = "";
                        string properties = "managedobjects,samaccountname";
                        Console.WriteLine("Users that have a managedobjects attribute");
                        try
                        {
                            query = "(&(objectClass=user))";
                            LdapQuery(domain, query, properties, false);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("ERROR: checkmanaged on users catched an unexpected exception");
                            ShowDebug(e, verboseDebug);
                        }
                        Console.WriteLine("Computers that have a managedby attribute");
                        properties = "managedby,name";
                        try
                        {
                            query = "(&(objectClass=computer))";
                            LdapQuery(domain, query, properties, false);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("ERROR: checkmanaged on computers catched an unexpected exception");
                            ShowDebug(e, verboseDebug);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Managedby GPO not found");
                    }
                }
                else if (option == "dumplastlogon")
                {
                    // Based on https://www.trustedsec.com/blog/targeted-active-directory-host-enumeration/
                    string query      = "";
                    string properties = "name,givenname,displayname,samaccountname,adspath,distinguishedname,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,streetaddress,co,title,department,description,comment,badpwdcount,objectcategory,userpassword,scriptpath";
                    var    date       = DateTime.Today.AddDays(-(DateTime.Today.Day + 90));
                    long   dateUtc    = date.ToFileTimeUtc();
                    try
                    {
                        query = "(&(objectCategory=computer)(lastLogon>=" + dateUtc.ToString() + ")(operatingSystem=*windows*))";
                        LdapQuery(domain, query, properties);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR: DumpPasswordPolicy catched an unexpected exception");
                        ShowDebug(e, verboseDebug);
                    }
                }
                else if (option == "getshare")
                {
                    string hostname = args[1];
                    string username = "";
                    string password = "";

                    if (args.Length > 2)
                    {
                        username = args[2].Split('\\')[1];
                        domain   = args[2].Split('\\')[0];
                        password = args[3];
                        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
                        const int LOGON32_PROVIDER_DEFAULT      = 0;
                        IntPtr    phToken = IntPtr.Zero;

                        bool bResult = false;
                        if (username != null)
                        {
                            bResult = LogonUser(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref phToken);
                            if (!bResult)
                            {
                                Console.WriteLine("Error: " + GetLastError());
                            }
                        }
                        bResult = ImpersonateLoggedOnUser(phToken);
                        if (!bResult)
                        {
                            Console.WriteLine("Error: " + GetLastError());
                        }
                    }

                    int entriesread   = 0;
                    int totalentries  = 0;
                    int resume_handle = 0;

                    int    structSize = Marshal.SizeOf(typeof(SHARE_INFO_1));
                    IntPtr bufPtr     = IntPtr.Zero;

                    int ret = NetShareEnum(hostname, 1, ref bufPtr, 0xFFFFFFFF, ref entriesread, ref totalentries, ref resume_handle);

                    if (ret == 0)
                    {
                        IntPtr currentPtr = bufPtr;

                        for (int i = 0; i < entriesread; i++)
                        {
                            SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
                            Console.WriteLine("\\\\{0}\\{1}", hostname, shi1);
                            currentPtr += structSize;
                        }
                    }
                }
                else if (option == "getservice")
                {
                    string hostname = args[1];
                    string username = "";
                    string password = "";

                    if (args.Length > 2)
                    {
                        username = args[2].Split('\\')[1];
                        domain   = args[2].Split('\\')[0];
                        password = args[3];
                        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
                        const int LOGON32_PROVIDER_DEFAULT      = 0;
                        IntPtr    phToken = IntPtr.Zero;

                        bool bResult = false;
                        if (username != null)
                        {
                            bResult = LogonUser(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref phToken);
                            if (!bResult)
                            {
                                Console.WriteLine("Error: " + GetLastError());
                            }
                        }
                        bResult = ImpersonateLoggedOnUser(phToken);
                        if (!bResult)
                        {
                            Console.WriteLine("Error: " + GetLastError());
                        }
                    }

                    ServiceController[] services = ServiceController.GetServices(hostname);

                    foreach (ServiceController service in services)
                    {
                        Console.WriteLine("{0}:{1}", service.ServiceName, service.Status);
                    }
                }
                else
                {
                    Console.WriteLine("Invalid argument: {0} not found", option);
                }
            }
            else
            {
                if (args.Length == 1)
                {
                    if (args[0] == "set")
                    {
                        foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                        {
                            Console.WriteLine("{0}={1}", de.Key, de.Value);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("ERROR: missing arguments");
                    Console.WriteLine("Usage: {0} options domain [arguments]", System.Reflection.Assembly.GetExecutingAssembly().Location);
                }
            }
        }
Esempio n. 26
0
        public static SHARE_INFO_1[] GetShareInfos_1(string server_name)
        {
            List <SHARE_INFO_1> ret_list = new List <SHARE_INFO_1>();
            IntPtr net_buffer            = IntPtr.Zero;
            int    entries_readed        = 0;
            int    entries_total         = 0;
            uint   resume_handle         = 0;
            int    res      = 0;
            int    res_free = 0;

            do
            {
                if ((server_name == null) || (server_name == string.Empty))
                {
                    res = WinApiNET.NetShareEnum
                              (IntPtr.Zero,
                              NET_INFO_LEVEL.LEVEL_1,
                              ref net_buffer,
                              WinApiNET.MAX_PREFERRED_LENGTH,
                              ref entries_readed,
                              ref entries_total,
                              ref resume_handle);
                }
                else
                {
                    res = WinApiNET.NetShareEnum
                              (server_name,
                              NET_INFO_LEVEL.LEVEL_1,
                              ref net_buffer,
                              WinApiNET.MAX_PREFERRED_LENGTH,
                              ref entries_readed,
                              ref entries_total,
                              ref resume_handle);
                }
                //check result
                if (res == WinApiNET.NERR_Success)
                {
                    //success, add to result list
                    ret_list.AddRange(SHARE_INFO_1.FromBuffer(net_buffer, entries_readed));
                    //free buffer
                    res_free = WinApiNET.NetApiBufferFree(net_buffer);
                    if (res_free != WinApiNET.NERR_Success)
                    {
                        throw new Win32Exception(res_free);
                    }
                    //break cycle
                    break;
                }
                if (res == WinApiNET.ERROR_MORE_DATA)
                {
                    //success, but more data available
                    ret_list.AddRange(SHARE_INFO_1.FromBuffer(net_buffer, entries_readed));
                    //free buffer
                    res_free = WinApiNET.NetApiBufferFree(net_buffer);
                    if (res_free != WinApiNET.NERR_Success)
                    {
                        throw new Win32Exception(res_free);
                    }
                    //continue cycle
                    continue;
                }
                //now res is error code
                Win32Exception win_ex = new Win32Exception(res);
                throw win_ex;
            } while (true);
            return(ret_list.ToArray());
        }