/// <summary>
        /// Net user user_name [/domain]
        /// </summary>
        public static int NetUserGetInfo(string servername, string name)
        {
            int       nStatus;
            USER_INFO level = USER_INFO.USER_INFO_1;

            System.IntPtr userInfoPtr = IntPtr.Zero;
            USER_INFO_1   userInfo    = new USER_INFO_1();

            nStatus = NetUserGetInfo(servername, name, (System.UInt32)level, out userInfoPtr);
            if (nStatus == NERR_Success)
            {
                if (userInfoPtr != null)
                {
                    userInfo = (USER_INFO_1)Marshal.PtrToStructure(userInfoPtr, typeof(USER_INFO_1));
                    System.Console.WriteLine
                    (
                        "User Name: {0} | Priviledge: {1} | Home Directory: {2} | Comment: {3} | Flags: {4} | Script Path: {5}",
                        userInfo.usri1_name,
                        userInfo.usri1_priv,
                        userInfo.usri1_home_dir,
                        userInfo.comment,
                        EnumToString(typeof(UF), userInfo.usri1_flags),
                        userInfo.usri1_script_path
                    );
                }
            }
            else
            {
                System.Console.WriteLine("A system error has occurred: {0} {1}", nStatus, MethodBase.GetCurrentMethod());
            }
            NetApiBufferFree(userInfoPtr);
            return(nStatus);
        }
示例#2
0
 static extern int NetUserSetInfo(
     string servername,
     string username,
     int level,
     ref USER_INFO_1 buf,
     out UInt32 parm_err
     ); //from pinvoke.net
示例#3
0
        public static List <string> EnumerateEnabledUsers()
        {
            List <string> result = new List <string>();
            uint          entriesRead;
            uint          totalEntries;
            uint          resume;

            IntPtr bufPtr;
            uint   level  = 1;
            uint   status = NetUserEnum(null, level, FILTER_NORMAL_ACCOUNT, out bufPtr, MAX_PREFERRED_LENGTH, out entriesRead, out totalEntries, out resume);

            if (status != NERR_Success)
            {
                throw new Exception("NetUserEnum failed, Error code: " + status.ToString());
            }

            if (entriesRead > 0)
            {
                USER_INFO_1[] Users = new USER_INFO_1[entriesRead];
                IntPtr        iter  = bufPtr;
                for (int i = 0; i < entriesRead; i++)
                {
                    Users[i] = (USER_INFO_1)Marshal.PtrToStructure(iter, typeof(USER_INFO_1));
                    iter     = new IntPtr(iter.ToInt64() + Marshal.SizeOf(typeof(USER_INFO_1)));
                    if ((Users[i].Flags & UF_ACCOUNTDISABLE) == 0)
                    {
                        result.Add(Users[i].Username);
                    }
                }
                NetApiBufferFree(bufPtr);
            }
            return(result);
        }
示例#4
0
        //枚举全部用户
        public string UserEnum()
        {
            string tempStr = "<?xml version=\"1.0\" encoding=\"gb2312\" ?>\r\n";

            tempStr += "<INFO>\r\n";
            int    Entriesread;
            int    TotalEntries;
            int    Resume_Handle;
            IntPtr bufPtr;

            if (NetUserEnum(null, 1, 0, out bufPtr, -1, out Entriesread, out TotalEntries, out Resume_Handle) != 0)
            {
                throw (new Exception("枚举全部用户失败"));
            }
            if (Entriesread > 0)
            {
                USER_INFO_1[] UserInfo = new USER_INFO_1[Entriesread];
                IntPtr        iter     = bufPtr;
                for (int i = 0; i < Entriesread; i++)
                {
                    UserInfo[i] = (USER_INFO_1)Marshal.PtrToStructure(iter, typeof(USER_INFO_1));
                    iter        = (IntPtr)((int)iter + Marshal.SizeOf(typeof(USER_INFO_1)));
                    tempStr    += "<ITEM value=\"" + UserInfo[i].sComment + "\">" + UserInfo[i].sName + "</ITEM>\r\n";
                }
                tempStr += "</INFO>";
            }
            NetApiBufferFree(bufPtr);
            return(tempStr);
        }
示例#5
0
        public static List <string> EnumerateEnabledUsers()
        {
            List <string> result = new List <string>();
            int           entriesRead;
            int           totalEntries;
            int           resume;

            IntPtr    bufPtr;
            const int Level = 1;
            const int FILTER_NORMAL_ACCOUNT = 2;
            const int UF_ACCOUNTDISABLE     = 2;

            NetUserEnum(null, Level, FILTER_NORMAL_ACCOUNT, out bufPtr, -1, out entriesRead, out totalEntries, out resume);

            if (entriesRead > 0)
            {
                USER_INFO_1[] Users = new USER_INFO_1[entriesRead];
                IntPtr        iter  = bufPtr;
                for (int i = 0; i < entriesRead; i++)
                {
                    Users[i] = (USER_INFO_1)Marshal.PtrToStructure(iter, typeof(USER_INFO_1));
                    iter     = (IntPtr)(iter + Marshal.SizeOf(typeof(USER_INFO_1)));
                    if ((Users[i].Flags & UF_ACCOUNTDISABLE) == 0)
                    {
                        result.Add(Users[i].Username);
                    }
                }
                NetApiBufferFree(bufPtr);
            }
            return(result);
        }
示例#6
0
        //读取用户信息
        public string UserGetInfo(string UserName)
        {
            string tmpStr = "<?xml version=\"1.0\" encoding=\"gb2312\" ?>\r\n";

            tmpStr += "<INFO>\r\n";
            IntPtr      bufPtr;
            USER_INFO_1 UserInfo = new USER_INFO_1();

            if (NetUserGetInfo(null, UserName, 1, out bufPtr) != 0)
            {
                //throw (new Exception("读取用户信息失败"));
                return("读取用户信息失败");
            }
            else
            {
                UserInfo = (USER_INFO_1)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_1));
                tmpStr  += "<NAME>" + UserInfo.sName + "</NAME>\r\n";
                tmpStr  += "<PASS>" + UserInfo.sPass + "</PASS>\r\n";
                tmpStr  += "<DESC>" + UserInfo.sComment + "</DESC>\r\n";
                tmpStr  += "<sPriv>" + UserInfo.sPriv + "</sPriv>\r\n";
                tmpStr  += "</INFO>";
                NetApiBufferFree(bufPtr);
                return(tmpStr);
            }
        }
示例#7
0
        //const string USERNAME = "******"; // Machine Name!

        static void Main(string[] args)
        {
            //NetUserDel("", USERNAME);
            USER_INFO_1 newuser = new USER_INFO_1()
            {
                sComment     = DESCRIPTION,
                sUsername    = USERNAME,
                sPassword    = PASSWORD,
                sHome_Dir    = "",
                sScript_Path = "",
                uiPriv       = USER_PRIV_USER,
                uiFlags      = UF_WORKSTATION_TRUST_ACCOUNT
            };

            Console.WriteLine(string.Format("Adding {0} user to system with password {1}, please wait...", USERNAME, PASSWORD));
            NetUserAdd("", 1, newuser, out uint parm_err);
            Console.WriteLine("User added!");
            Console.WriteLine("Enumerating Administrators group, please wait...");
            GroupPrincipal gp = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine, null), "Administrators");

            Console.WriteLine("Found Administrators group.");
            Console.WriteLine("Enumerating new user, please wait...");
            UserPrincipal up = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Machine, null), USERNAME);

            Console.WriteLine("Found the new user.");
            Console.WriteLine(string.Format("Adding {0} to Administrators group, please wait...", USERNAME));
            gp.Members.Add(up);
            gp.Save();
            Console.WriteLine("All Done! Hack the planet!");
        }
示例#8
0
        public string AddUser(string admin, string pass, string user)
        {
            const int UF_DONT_EXPIRE_PASSWD = 0x10000;
            //const int UF_ACCOUNTDISABLE = 0x000002;

            //const int USER_PRIV_GUEST = 0;
            const int USER_PRIV_USER = 1;
            //const int USER_PRIV_ADMIN = 2;

            string password = _generate();

            if (string.IsNullOrWhiteSpace(user))
            {
                return($"ERROR occurred! No empty string is valid.");
            }

            USER_INFO_1 userInfo1 = new USER_INFO_1()
            {
                username     = user,
                password     = password,
                password_age = -1,
                priv         = USER_PRIV_USER,
                homedir      = "",
                comment      = "",
                flag         = UF_DONT_EXPIRE_PASSWD,
                scriptpath   = ""
            };

            using (PrincipalContext _ctx = new PrincipalContext(ContextType.Machine))
            {
                if (!_ctx.ValidateCredentials(admin, pass))
                {
                    return($"Invalid authencation!");
                }

                UserPrincipal _priv = UserPrincipal.FindByIdentity(_ctx, IdentityType.SamAccountName, admin);
                if (!_priv.GetAuthorizationGroups().Any(p => p.ToString() == "Administrators"))
                {
                    return($"Invalid authencation!");
                }
            }

            int output;
            int r = NetUserAdd("127.0.0.1", 1, ref userInfo1, out output);

            if (r != 0)
            {
                return($"ERROR[{r}] occurred! Unable to create user");
            }

            return($"User[{user}/{password}] is created!");
        }
示例#9
0
        public static USER_INFO_1 AccountGetPassword(string sAccountName)
        {
            //string sPassword = "";

            USER_INFO_1 objUserInfo1 = new USER_INFO_1();
            IntPtr bufPtr; // because it's an OUT, we don't need to Alloc

            int lngReturn = NetUserGetInfo(null, sAccountName, 1, out bufPtr);
            if (lngReturn == 0)
            {
                objUserInfo1 = (USER_INFO_1)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_1));
                //sPassword = objUserInfo1.sPassword;
            }
            NetApiBufferFree(bufPtr);

            return objUserInfo1;
        }
示例#10
0
        internal static void NetUserAdd(string username, string password)
        {
            USER_INFO_1 userInfo = new USER_INFO_1();

            userInfo.usri1_name     = username;
            userInfo.usri1_password = password;
            userInfo.usri1_priv     = 1;

            uint parm_err;
            uint result = NetUserAdd(null, 1, ref userInfo, out parm_err);

            if (result != 0) // NERR_Success
            {
                // most likely result == ERROR_ACCESS_DENIED
                // due to running without elevated privileges
                throw new Win32Exception((int)result);
            }
        }
示例#11
0
 //创建系统用户
 public bool UserAdd(string UserName, string UserPass, string sDescription)
 {
     USER_INFO_1 UserInfo = new USER_INFO_1();
     UserInfo.sName = UserName;
     UserInfo.sPass = UserPass;
     UserInfo.PasswordAge = 0;
     UserInfo.sPriv = 1;
     UserInfo.sHomeDir = null;
     UserInfo.sComment = sDescription;
     UserInfo.sFlags = 0x0040 | 0x10000;
     UserInfo.sScriptPath = null;
     if (NetUserAdd(null, 1, ref UserInfo, 0) != 0)
     {
         //throw (new Exception("创建系统用户失败"));
         return false;
     }
     else
     {
         return true;
     }
 }
示例#12
0
        //修改用户信息
        public bool UserSetInfo(string UserName, string NewUserName, string UserPass, string sDescription)
        {
            USER_INFO_1 UserInfo = new USER_INFO_1();

            UserInfo.sName       = NewUserName.ToString();
            UserInfo.sPass       = UserPass.ToString();
            UserInfo.PasswordAge = 0;
            UserInfo.sPriv       = 1;
            UserInfo.sHomeDir    = null;
            UserInfo.sComment    = sDescription.ToString();
            UserInfo.sFlags      = 0x10040;
            UserInfo.sScriptPath = null;
            if (NetUserSetInfo(null, UserName.ToString(), 1, ref UserInfo, 0) != 0)
            {
                throw (new Exception("用户信息修改失败"));
            }
            else
            {
                return(true);
            }
        }
示例#13
0
        //创建系统用户
        public bool UserAdd(string UserName, string UserPass, string sDescription)
        {
            USER_INFO_1 UserInfo = new USER_INFO_1();

            UserInfo.sName       = UserName;
            UserInfo.sPass       = UserPass;
            UserInfo.PasswordAge = 0;
            UserInfo.sPriv       = 1;
            UserInfo.sHomeDir    = null;
            UserInfo.sComment    = sDescription;
            UserInfo.sFlags      = 0x0040 | 0x10000;
            UserInfo.sScriptPath = null;
            if (NetUserAdd(null, 1, ref UserInfo, 0) != 0)
            {
                //throw (new Exception("创建系统用户失败"));
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#14
0
        //修改用户信息
        public bool UserChangePassword(string UserName, string UserPass)
        {
            IntPtr bufPtr;
            USER_INFO_1 UserInfo = new USER_INFO_1();
            if (NetUserGetInfo(null, UserName, 1, out bufPtr) != 0)
            {
                return false;
            }
            else
            {
                UserInfo = (USER_INFO_1)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_1));
                UserInfo.sPass = UserPass;

                if (NetUserSetInfo(null, UserName, 1, ref UserInfo, 0) != 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        /// <summary>
        /// net user [UserName {Password | *} /add [Options] [/domain]]
        ///     Options Specifies a command-line option. The following table lists valid command-line options that you can use.
        ///         /homedir:Path
        ///             Sets the path for the user's home directory. The path must exist.
        ///         /comment:"Text"
        ///         /scriptpath:Path
        ///             Sets a path for the user's logon script. Path cannot be an absolute path. Path is relative to %systemroot%\System32\Repl\Import\Scripts.
        /// </summary>
        public static int NetUserAdd
        (
            string servername,
            string name,
            string password,
            USER_PRIV priv,
            string home_dir,
            string comment,
            string script_path
        )
        {
            int    nStatus;
            IntPtr userInfoPtr = IntPtr.Zero;;

            System.UInt32 parm_err = 0;
            USER_INFO_1   userInfo = new USER_INFO_1();;

            userInfo.usri1_name        = name;
            userInfo.usri1_password    = password;
            userInfo.usri1_priv        = (System.UInt32)priv;
            userInfo.usri1_home_dir    = home_dir;
            userInfo.comment           = comment;
            userInfo.usri1_flags       = (System.UInt32)UF.UF_SCRIPT;
            userInfo.usri1_script_path = script_path;

            userInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(userInfo));
            Marshal.StructureToPtr(userInfo, userInfoPtr, false);

            nStatus = NetUserAdd(servername, (System.UInt32)USER_INFO.USER_INFO_1, userInfoPtr, out parm_err);

            if (nStatus != NERR_Success)
            {
                System.Console.WriteLine("Status: {0} | parm_err: {1}", nStatus, parm_err);
            }
            NetApiBufferFree(userInfoPtr);
            return(nStatus);
        }
示例#16
0
        public static void AddLocalUser(WindowsUser user, params string[] groups)
        {
            Debug.Assert(user.IsLocal && !string.IsNullOrEmpty(user.Name));
            Debug.Assert(!string.IsNullOrEmpty(user.Password));

            int         flag = user.PwdExpired ? 0 : util.UF_DONT_EXPIRE_PASSWD;
            USER_INFO_1 u    = new USER_INFO_1()
            {
                name     = user.Name,
                password = user.Password,
                priv     = 1,
                home_dir = null,
                comment  = user.Comment,
                flags    = flag,
            };
            int ret = netapi.NetUserAdd(null, 1, u, 0);

            if (ret != 0)
            {
                throw new Win32Exception(ret);
            }

            UpdateLocalUser(user.Name, user, groups);
        }
示例#17
0
        //修改用户信息
        public bool UserChangePassword(string UserName, string UserPass)
        {
            IntPtr      bufPtr;
            USER_INFO_1 UserInfo = new USER_INFO_1();

            if (NetUserGetInfo(null, UserName, 1, out bufPtr) != 0)
            {
                return(false);
            }
            else
            {
                UserInfo       = (USER_INFO_1)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_1));
                UserInfo.sPass = UserPass;

                if (NetUserSetInfo(null, UserName, 1, ref UserInfo, 0) != 0)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
示例#18
0
        private static void AddMachineAccount(
            string wTargetComputer,
            string MachineAccount,
            UserAcctCtrlFlags AccountType
            )
        {
            // ensure a valid computer account type was passed
            if (AccountType != UserAcctCtrlFlags.UF_WORKSTATION_TRUST_ACCOUNT &&
                AccountType != UserAcctCtrlFlags.UF_SERVER_TRUST_ACCOUNT &&
                AccountType != UserAcctCtrlFlags.UF_INTERDOMAIN_TRUST_ACCOUNT)
            {
                throw ((Win32Error)Win32Error.ERROR_INVALID_PARAMETER).GetException();
            }

            // obtain number of chars in computer account name
            var cchLength = MachineAccount.Length;

            // ensure computer name doesn't exceed maximum length
            if (cchLength > MAX_COMPUTERNAME_LENGTH)
            {
                throw ((Win32Error)Win32Error.ERROR_INVALID_ACCOUNT_NAME).GetException();
            }

            // password is the computer account name converted to lowercase convert the passed MachineAccount in place
            var wPassword = MachineAccount.ToLower();

            // convert computer account name to uppercase. computer account names have a trailing Unicode '$'
            var wAccount = MachineAccount.ToUpper() + '$';

            // if the password is greater than the max allowed, truncate
            if (cchLength > LM20_PWLEN)
            {
                wPassword = wPassword.Substring(0, LM20_PWLEN);
            }

            // initialize USER_INFO_x structure
            var ui = new USER_INFO_1
            {
                usri1_name     = wAccount,
                usri1_password = wPassword,
                usri1_flags    = AccountType | UserAcctCtrlFlags.UF_SCRIPT,
                usri1_priv     = UserPrivilege.USER_PRIV_USER
            };

            try
            {
                NetUserAdd(wTargetComputer, ui);
            }
            catch (UnauthorizedAccessException)
            {
                // try to enable the SeMachineAccountPrivilege
                SetCurrentPrivilege("SeMachineAccountPrivilege", true, out var Previous);

                try
                {
                    // enabled the privilege. retry the add operation
                    NetUserAdd(wTargetComputer, ui);
                }
                finally
                {
                    // disable the privilege
                    SetCurrentPrivilege("SeMachineAccountPrivilege", Previous, out _);
                }
            }
        }
示例#19
0
 public extern static int NetUserSetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username, int level, ref USER_INFO_1 buf, int error);
示例#20
0
        internal static void NetUserAdd(string username, string password)
        {
            USER_INFO_1 userInfo = new USER_INFO_1();
            userInfo.usri1_name = username;
            userInfo.usri1_password = password;
            userInfo.usri1_priv = 1;

            uint parm_err;
            uint result = NetUserAdd(null, 1, ref userInfo, out parm_err);

            if (result != 0) // NERR_Success
            {
                // most likely result == ERROR_ACCESS_DENIED 
                // due to running without elevated privileges
                throw new Win32Exception((int)result);
            }
        }
示例#21
0
 public static unsafe extern int NetUserAdd([In, MarshalAs(UnmanagedType.LPWStr)] string lpServer, int Level, [In] ref USER_INFO_1 userInfo, int lpError);
示例#22
0
 internal static extern uint NetUserAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, uint level, ref USER_INFO_1 buf, out uint parm_err);
示例#23
0
            // NOTE: may have a problem with cleaning these up
            public static WinAPI.SandboxApi.Sandbox SafeCreateSandbox(string username, string password)
            {
                var sandbox = new Sandbox
                {
                    UserName = /*"Mbx" + */ (username.Length > 20
                        ? username.Substring(0, 20)
                        : username),
                    Password = password,
                };

                var exists = DoesSandboxExist(sandbox);

                // if user account not exists, create it
                if (!exists)
                {
                    // create user account: NetUserAdd
                    var userInfoLevel1 = new USER_INFO_1
                    {
                        sPassword = sandbox.Password,
                        sUsername = sandbox.UserName,
                        uiPriv = USER_PRIV_USER,
                        uiFlags = UF_NORMAL_ACCOUNT,
                    };
                    uint parm_err;
                    var netApiStatus = NetUserAdd(IntPtr.Zero, 1, ref userInfoLevel1, out parm_err);
                    if (netApiStatus != NET_API_STATUS.NERR_Success)
                    {
                        var reason = "NetUserAdd failed for '" + username + "' reason " + netApiStatus;
                        Console.Error.WriteLine(reason);
                        throw new Exception(reason);
                    }

                    // create profile
                    SafeLoadSID(sandbox);
                    int MAX_PATH = 260;
                    StringBuilder pathBuf = new StringBuilder(MAX_PATH);
                    uint pathLen = (uint)pathBuf.Capacity;
                    int result = CreateProfile(sandbox.SID, sandbox.UserName, pathBuf, pathLen);
                }

                return sandbox;
            }
示例#24
0
 //读取用户信息
 public string UserGetInfo(string UserName)
 {
     string tmpStr = "<?xml version=\"1.0\" encoding=\"gb2312\" ?>\r\n";
     tmpStr += "<INFO>\r\n";
     IntPtr bufPtr;
     USER_INFO_1 UserInfo = new USER_INFO_1();
     if (NetUserGetInfo(null, UserName, 1, out bufPtr) != 0)
     {
         //throw (new Exception("读取用户信息失败"));
         return "读取用户信息失败";
     }
     else
     {
         UserInfo = (USER_INFO_1)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_1));
         tmpStr += "<NAME>" + UserInfo.sName + "</NAME>\r\n";
         tmpStr += "<PASS>" + UserInfo.sPass + "</PASS>\r\n";
         tmpStr += "<DESC>" + UserInfo.sComment + "</DESC>\r\n";
         tmpStr += "<sPriv>" + UserInfo.sPriv + "</sPriv>\r\n";
         tmpStr += "</INFO>";
         NetApiBufferFree(bufPtr);
         return tmpStr;
     }
 }
示例#25
0
        NetAddUser(
            string servername,
            string username,
            string password,
            string fullname,
            string description,
            uint flags
            )
        {
            uint result = (uint)LUGAPI.WinError.ERROR_SUCCESS;

            if (String.IsNullOrEmpty(servername))
            {
                servername = null;
            }
            if (String.IsNullOrEmpty(username))
            {
                username = null;
            }
            if (String.IsNullOrEmpty(password))
            {
                password = null;
            }
            if (String.IsNullOrEmpty(fullname))
            {
                fullname = null;
            }
            if (String.IsNullOrEmpty(description))
            {
                description = null;
            }

            USER_INFO_1 ui1 = new USER_INFO_1();
            USER_INFO_1011 ui11 = new USER_INFO_1011();
            UInt32 parm_err = 0;

            ui1.sUsername = username;
            ui1.sPassword = password;
            ui1.uiPasswordAge = 0;
            ui1.uiPriv = 1; // USER_PRIV_USER
            ui1.sHome_Dir = "";
            ui1.sComment = description;
            ui1.uiFlags = flags | UF_NORMAL_ACCOUNT;
            ui1.sScript_Path = "";

            ui11.usri1011_full_name = fullname;

            IntPtr bufptr_1 = Marshal.AllocHGlobal(Marshal.SizeOf(ui1));
            IntPtr bufptr_1011 = Marshal.AllocHGlobal(Marshal.SizeOf(ui11));
            IntPtr bufptr_parm_err = Marshal.AllocHGlobal(Marshal.SizeOf(parm_err));

            try
            {
                if (!NetApiInitCalled)
                {
                    result = NetApiInit();
                    if (result != (uint)LUGAPI.WinError.ERROR_SUCCESS)
                    {
                        return result;
                    }

                    NetApiInitCalled = true;
                }

                Marshal.StructureToPtr(ui1, bufptr_1, false);
                Marshal.StructureToPtr(ui11, bufptr_1011, false);
                Marshal.StructureToPtr(parm_err, bufptr_parm_err, false);

                result = (uint)NetUserAdd(servername, 1, bufptr_1, bufptr_parm_err);

                if (result != 0)
                {
                    return result;
                }

                if (fullname != null)
                {
                    result = (uint)NetUserSetInfo(servername, username, 1011, bufptr_1011, bufptr_parm_err);

                    if (result != 0)
                    {
                        return result;
                    }
                }
            }
            catch (Exception)
            {
                result = (uint)LUGAPI.WinError.ERROR_EXCEPTION_IN_SERVICE;
            }
            finally
            {
                try
                {
                    Marshal.DestroyStructure(bufptr_1, ui1.GetType());
                    Marshal.FreeHGlobal(bufptr_1);

                    Marshal.DestroyStructure(bufptr_1011, ui11.GetType());
                    Marshal.FreeHGlobal(bufptr_1011);

                    //If this is uncommented, it results in a crash
                    //TODO: figure out why it's not possible to free bufptr_parm_err
                    //Marshal.FreeHGlobal(bufptr_parm_err);
                }
                catch (Exception)
                {
                    result = (uint)LUGAPI.WinError.ERROR_EXCEPTION_IN_SERVICE;
                }
            }
            return result;

        }
示例#26
0
 static extern int NetUserAdd(
     [MarshalAs(UnmanagedType.LPWStr)] string servername,
     int level,
     ref USER_INFO_1 userinfo,
     out int parm_err);
示例#27
0
 static extern int NetUserSetInfo([MarshalAs(UnmanagedType.LPWStr)] string sName, [MarshalAs(UnmanagedType.LPWStr)] string UserName, int Level, ref USER_INFO_1 bufptr, int parm_err);
 internal static extern int NetUserAdd(
      [MarshalAs(UnmanagedType.LPWStr)] string servername,
      UInt32 level,
      ref USER_INFO_1 userInfo,
      out UInt32 parm_err);
示例#29
0
        internal static bool NetUserAdd(string username, string password)
        {
            USER_INFO_1 userInfo = new USER_INFO_1();
            userInfo.usri1_name = username;
            userInfo.usri1_password = password;
            userInfo.usri1_priv = 1;

            uint parm_err;
            uint result = NetUserAdd(null, 1, ref userInfo, out parm_err);

            if (result != 0)
            {
                throw new Win32Exception();
            }

            return true;
        }
 internal static extern NetUserRetEnum NetUserSetInfo(
     string ServerName,
     string UserName,
     uint Level,
     ref USER_INFO_1 Buf,
     out uint ParmError);
示例#31
0
 private static extern NET_API_STATUS NetUserAdd(
     //[MarshalAs(UnmanagedType.LPWStr)]
     //string servername,
     IntPtr specifyNull,
     int level,
     ref USER_INFO_1 userInfo,
     out UInt32 parm_err);
示例#32
0
 public static extern NET_API_STATUS NetUserAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref USER_INFO_1 buf, int parm_err);
示例#33
0
 //枚举全部用户
 public string UserEnum()
 {
     string tempStr = "<?xml version=\"1.0\" encoding=\"gb2312\" ?>\r\n";
     tempStr += "<INFO>\r\n";
     int Entriesread;
     int TotalEntries;
     int Resume_Handle;
     IntPtr bufPtr;
     if (NetUserEnum(null, 1, 0, out bufPtr, -1, out Entriesread, out TotalEntries, out Resume_Handle) != 0)
     {
         //throw (new Exception("枚举全部用户失败"));
         return "枚举全部用户失败";
     }
     if (Entriesread > 0)
     {
         USER_INFO_1[] UserInfo = new USER_INFO_1[Entriesread];
         IntPtr iter = bufPtr;
         for (int i = 0; i < Entriesread; i++)
         {
             UserInfo[i] = (USER_INFO_1)Marshal.PtrToStructure(iter, typeof(USER_INFO_1));
             iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(USER_INFO_1)));
             tempStr += "<ITEM value=\"" + UserInfo[i].sComment + "\">" + UserInfo[i].sName + "</ITEM>\r\n";
         }
         tempStr += "</INFO>";
     }
     NetApiBufferFree(bufPtr);
     return tempStr;
 }
示例#34
0
 private extern static int NetUserAdd([MarshalAs(UnmanagedType.LPWStr)] string sName, int Level, ref USER_INFO_1 buf, int parm_err);
示例#35
0
 internal extern static uint NetUserAdd(string servername, uint level, ref USER_INFO_1 buf, out uint parm_err);
示例#36
0
        /// <summary>
        /// Creates a new NT user account.
        /// </summary>
        public static AccountInfo CreateUser(string username, string password)
        {
            int dwLevel = 1;
            int dwError = 0;
            int nStatus;

            //
            // Set up the USER_INFO_1 structure.
            //  USER_PRIV_USER: name identifies a user, 
            //    rather than an administrator or a guest.
            //  UF_SCRIPT: required for LAN Manager 2.0 and
            //    Windows NT and later.
            //
            USER_INFO_1 ui = new USER_INFO_1();

            ui.usri1_name = username;
            ui.usri1_password = password;
            ui.usri1_priv = USER_PRIV_USER;
            ui.usri1_home_dir = null;
            ui.usri1_comment = username;
            ui.usri1_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE;
            ui.usri1_script_path = null;

            IntPtr pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(USER_INFO_1)));
            Marshal.StructureToPtr(ui, pInfo, false);
            
            // try to add the user.
            try
            {
               nStatus = NetUserAdd(
                   null, 
                   dwLevel,
                   pInfo,
                   out dwError);
            }
            finally
            {
                Marshal.DestroyStructure(pInfo, typeof(USER_INFO_1));
                Marshal.FreeCoTaskMem(pInfo);
            }

            if (nStatus != NERR_Success)  // maybe account exists, so just set the password
            {
                // set the password.
                dwLevel = 1003;
                USER_INFO_1003 ui1003;
                ui1003.usri1003_password = password;

                pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(USER_INFO_1003)));
                Marshal.StructureToPtr(ui1003, pInfo, false);

                try
                {
                    nStatus = NetUserSetInfo(
                        null,
                        username,
                        dwLevel,
                        pInfo,
                        out dwError);
                }
                finally
                {
                    Marshal.DestroyStructure(pInfo, typeof(USER_INFO_1003));
                    Marshal.FreeCoTaskMem(pInfo);
                }

	            // set the account flags (e.g. enable the account if disabled)
	            dwLevel = 1008;
	            USER_INFO_1008 ui1008;
	            ui1008.usri1008_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE;
        	
                pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(USER_INFO_1003)));
                Marshal.StructureToPtr(ui1003, pInfo, false);

                try
                {
                    nStatus = NetUserSetInfo(
                        null,
                        username,
                        dwLevel,
                        pInfo,
                        out dwError);
                }
                finally
                {
                    Marshal.DestroyStructure(pInfo, typeof(USER_INFO_1008));
                    Marshal.FreeCoTaskMem(pInfo);
                }
            }

            if (nStatus != NERR_Success)
            {
                return null;
            }

            return Create(username);
        }
 internal static extern int NetUserAdd(
     [MarshalAs(UnmanagedType.LPWStr)] string servername,
     UInt32 level,
     ref USER_INFO_1 userInfo,
     out UInt32 parm_err);
示例#38
0
        /// <summary>
        /// Creates a new NT user account.
        /// </summary>
        public static AccountInfo CreateUser(string username, string password)
        {
            int dwLevel = 1;
            int dwError = 0;
            int nStatus;

            //
            // Set up the USER_INFO_1 structure.
            //  USER_PRIV_USER: name identifies a user,
            //    rather than an administrator or a guest.
            //  UF_SCRIPT: required for LAN Manager 2.0 and
            //    Windows NT and later.
            //
            USER_INFO_1 ui = new USER_INFO_1();

            ui.usri1_name        = username;
            ui.usri1_password    = password;
            ui.usri1_priv        = USER_PRIV_USER;
            ui.usri1_home_dir    = null;
            ui.usri1_comment     = username;
            ui.usri1_flags       = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE;
            ui.usri1_script_path = null;

            IntPtr pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(USER_INFO_1)));

            Marshal.StructureToPtr(ui, pInfo, false);

            // try to add the user.
            try
            {
                nStatus = NetUserAdd(
                    null,
                    dwLevel,
                    pInfo,
                    out dwError);
            }
            finally
            {
                Marshal.DestroyStructure(pInfo, typeof(USER_INFO_1));
                Marshal.FreeCoTaskMem(pInfo);
            }

            if (nStatus != NERR_Success)  // maybe account exists, so just set the password
            {
                // set the password.
                dwLevel = 1003;
                USER_INFO_1003 ui1003;
                ui1003.usri1003_password = password;

                pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(USER_INFO_1003)));
                Marshal.StructureToPtr(ui1003, pInfo, false);

                try
                {
                    nStatus = NetUserSetInfo(
                        null,
                        username,
                        dwLevel,
                        pInfo,
                        out dwError);
                }
                finally
                {
                    Marshal.DestroyStructure(pInfo, typeof(USER_INFO_1003));
                    Marshal.FreeCoTaskMem(pInfo);
                }

                // set the account flags (e.g. enable the account if disabled)
                dwLevel = 1008;
                USER_INFO_1008 ui1008;
                ui1008.usri1008_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE;

                pInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(USER_INFO_1003)));
                Marshal.StructureToPtr(ui1003, pInfo, false);

                try
                {
                    nStatus = NetUserSetInfo(
                        null,
                        username,
                        dwLevel,
                        pInfo,
                        out dwError);
                }
                finally
                {
                    Marshal.DestroyStructure(pInfo, typeof(USER_INFO_1008));
                    Marshal.FreeCoTaskMem(pInfo);
                }
            }

            if (nStatus != NERR_Success)
            {
                return(null);
            }

            return(Create(username));
        }
示例#39
0
 public static extern int NetUserAdd(
     [MarshalAs(UnmanagedType.LPWStr)] string servername,
     int level,
     ref USER_INFO_1 buf,
     int parm_err);
示例#40
0
 internal extern static uint NetUserAdd(string servername, uint level, ref USER_INFO_1 buf, out uint parm_err);
示例#41
0
        private void CreateUser()
        {
            string testAccountPassword;

            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                byte[] randomBytes = new byte[33];
                rng.GetBytes(randomBytes);

                // Add special chars to ensure it satisfies password requirements.
                testAccountPassword = Convert.ToBase64String(randomBytes) + "_-As@!%*(1)4#2";

                USER_INFO_1 userInfo = new USER_INFO_1
                {
                    usri1_name     = _userName,
                    usri1_password = testAccountPassword,
                    usri1_priv     = 1
                };

                // Create user and remove/create if already exists
                uint result = NetUserAdd(null, 1, ref userInfo, out uint param_err);

                // error codes https://docs.microsoft.com/en-us/windows/desktop/netmgmt/network-management-error-codes
                // 0 == NERR_Success
                if (result == 2224) // NERR_UserExists
                {
                    result = NetUserDel(null, userInfo.usri1_name);
                    if (result != 0)
                    {
                        throw new Win32Exception((int)result);
                    }
                    result = NetUserAdd(null, 1, ref userInfo, out param_err);
                    if (result != 0)
                    {
                        throw new Win32Exception((int)result);
                    }
                }
                else if (result != 0)
                {
                    throw new Win32Exception((int)result);
                }

                const int LOGON32_PROVIDER_DEFAULT  = 0;
                const int LOGON32_LOGON_INTERACTIVE = 2;

                if (!LogonUser(_userName, ".", testAccountPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _accountTokenHandle))
                {
                    _accountTokenHandle = null;
                    throw new Exception($"Failed to get SafeAccessTokenHandle for test account {_userName}", new Win32Exception());
                }

                bool gotRef = false;
                try
                {
                    _accountTokenHandle.DangerousAddRef(ref gotRef);
                    IntPtr logonToken = _accountTokenHandle.DangerousGetHandle();
                    AccountName = new WindowsIdentity(logonToken).Name;
                }
                finally
                {
                    if (gotRef)
                    {
                        _accountTokenHandle.DangerousRelease();
                    }
                }
            }
        }
示例#42
0
 public static extern int NetUserAdd(string servername, int level, USER_INFO_1 buf, int parm_err);
 internal static extern NetUserRetEnum NetUserSetInfo(
     string ServerName,
     string UserName,
     uint Level,
     ref USER_INFO_1 Buf,
     out uint ParmError);
示例#44
0
 private extern static int NetUserSetInfo([MarshalAs(UnmanagedType.LPWStr)] string sName, [MarshalAs(UnmanagedType.LPWStr)] string UserName, int Level, ref USER_INFO_1 bufptr, int parm_err);