Exemplo n.º 1
0
        public static bool IsNullOrEmpty(CredentialEntry ce)
        {
            if (ce == null ||
                String.IsNullOrEmpty(ce.Domain) ||
                String.IsNullOrEmpty(ce.Password) ||
                String.IsNullOrEmpty(ce.UserName))
            {
                return(true);
            }

            return(false);
        }
 /// <summary>
 ///
 /// </summary>
 public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
 {
     try
     {
         this.dirnode = dirnode;
         SetControlStatus();
     }
     catch (Exception e)
     {
         Logger.LogException("UserMultiEditPage.SetData", e);
     }
 }
Exemplo n.º 3
0
        public LwioCopy(CredentialEntry creds, string localPath, string remotePath)
        {
            string sRealm=string.Empty;

            Logger.Log(String.Format(
                "domain={0}, user={1}, localPath={2}, remotePath={3}",
                creds.Domain,
                creds.UserName,
                localPath,
                remotePath),
                Logger.LWIOCopy);

            if (!Configurations.SSOFailed)
            {
                string UserID = DetermineUserID();

                sCredsPath = string.Format("/tmp/krb5cc_{0}", UserID);

                Environment.SetEnvironmentVariable("KRB5CCNAME", sCredsPath.Trim());
            }
            else
            {
                //int ret = Krb5CredsCache.BuildCredsContext(creds.UserName,
                //                                           creds.Password,
                //                                           creds.Domain,
                //                                           out CrdesCache);
                uint ret = Krb5CredsCache.Krb5GetDomainPrincipalRealm(creds.Domain, out sRealm);
                if (ret != 0)
                {
                    Logger.Log("Krb5CredsCache.Krb5GetDomainPrincipalRealm failed" + ret.ToString());
                }
                sUserUPN = string.Concat(creds.UserName.ToLower(), "@", String.IsNullOrEmpty(sRealm) ? creds.Domain.ToUpper() : sRealm.ToUpper());
            }

            this.cCreds = creds;

            if (!String.IsNullOrEmpty(this.cCreds.UserName) && this.cCreds.UserName.IndexOf(@"\") >= 0)
            {
                int ibackwhack = this.cCreds.UserName.LastIndexOf(@"\");
                this.cCreds.UserName = this.cCreds.UserName.Substring(ibackwhack + 1);
            }

            this.localPath = localPath;
            this.remotePath = remotePath;
        }
Exemplo n.º 4
0
        public CredentialEntry Clone()
        {
            string resultMachineName = null;


            if (!String.IsNullOrEmpty(this.MachineName))
            {
                resultMachineName = (string)this.MachineName.Clone();
            }


            CredentialEntry result = new CredentialEntry(this.Invalidated, this.DefaultCreds, resultMachineName);

            result.Domain   = (this.Domain == null) ? null : (string)this.Domain.Clone();
            result.Password = (this.Password == null) ? null : (string)this.Password.Clone();
            result.UserName = (this.UserName == null) ? null : (string)this.UserName.Clone();



            return(result);
        }
        public void SetData(CredentialEntry ce, string sharename, object shareinfo)
        {
            try
            {
                if (shareinfo != null)
                {
                    string[] Shareinfo = shareinfo as string[];
                    if (Shareinfo != null)
                    {
                        this.textBoxSharename.Text = Shareinfo[1];
                        this.textBoxPath.Text = Shareinfo[2];
                        this.textBoxComment.Text = Shareinfo[3];
                        if (Shareinfo[5] == "-1")
                        {
                            radioButtonMaxAllowed.Checked = true;
                            radioButtonAllowedNum.Checked = false;
                        }
                        else
                        {
                            radioButtonAllowedNum.Checked = true;
                            radioButtonMaxAllowed.Checked = false;
                            numericUpDown.Enabled = true;

                            this.numericUpDown.ValueChanged -= new System.EventHandler(this.numericUpDown_ValueChanged);
                            numericUpDown.Value = Convert.ToDecimal(Shareinfo[5]);
                            this.numericUpDown.ValueChanged += new System.EventHandler(this.numericUpDown_ValueChanged);
                        }
                    }
                }

                this.ParentContainer.DataChanged = false;
                this.ParentContainer.btnApply.Enabled = false;
            }
            catch (Exception e)
            {
                container.ShowError(e.Message);
            }
        }
Exemplo n.º 6
0
    public void SetData(CredentialEntry ce, string servername, string username)
    {
        
        _servername = servername;
        _username = username;
        
        this.lbUser.Text = String.Format(this.lbUser.Text, username);

        try
        {
            LUGAPI.LUGInfo userInfo;

            if (LUGAPI.NetGetUserInfo(_servername, _username, out userInfo) == 0)
            {
                GetUserInfoDelegate(userInfo);
            }
        }
        catch (Exception e)
        {
            Logger.LogException("EditUserPage.SetData", e);
        }
        
    }
Exemplo n.º 7
0
        public static void DeleteSession(CredentialEntry ce, string sServer, string sSessionMachine, string sSessionUser)
        {
            sServer = Canon(sServer);

            try
            {
                int nRet = NetSessionDel(sServer, sSessionMachine, sSessionUser);

                Logger.Log(String.Format(
                               "{0}(sServer={1}, sSessionMachine={2}, sSessionUser={3}): nRet={4}",
                               "Session.DeleteSession(): NetSessionDel",
                               sServer, sSessionMachine, sSessionUser, nRet), Logger.netAPILogLevel);

                if (nRet != 0)
                {
                    throw new AuthSessionException(ErrorCodes.WIN32String(nRet), null);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Session.DeleteSession", ex);
            }
        }
Exemplo n.º 8
0
 public static Process RunAddDriverWizard(CredentialEntry ce, string sServer)
 {
     Session.EnsureNullSession(sServer, ce);
     return ProcessUtil.Exec(Environment.SystemDirectory, "rundll32.exe", @"printui.dll,PrintUIEntry /c\\" + sServer + " /id");
     
 }
Exemplo n.º 9
0
 public static Process ShowManageUI(CredentialEntry ce, string sServer, string sShare)
 {
     Session.EnsureNullSession(sServer, ce);
     return ProcessUtil.Exec(Environment.SystemDirectory, "rundll32.exe", string.Format(@"printui.dll,PrintUIEntry /o /n ""\\{0}\{1}""", sServer, sShare));
 }
Exemplo n.º 10
0
        /// <summary>
        /// Queries and fills the ldap message for the selected group
        /// Gets the attribute list from AD for group schema attribute.
        /// search for the attributes description, cn or name and displays them in a controls
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="name"></param>
        /// <param name="dirnode"></param>
        public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
        {
            try
            {
                this.dirnode = dirnode;
                this.plugin = dirnode.Plugin as ADUCPlugin;
                DirectoryContext dirContext = dirnode.LdapContext;
                Logonname = "";
                PreLogonname = "";

                //first obtain the current userAccountControl value
                DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));
                int userCtrlInt = Convert.ToInt32(de.Properties["userAccountControl"].Value.ToString());
                long pwdLastSet = Convert.ToInt64(de.Properties["pwdLastSet"].Value.ToString());
                sUserWorkStations = de.Properties["userWorkstations"].Value as string;

                if (de.Properties["userPrincipalName"].Value != null)
                {
                    Logonname = de.Properties["userPrincipalName"].Value as string;
                    Logonname = Logonname.IndexOf('@') >= 0 ? Logonname.Substring(0, Logonname.IndexOf('@')) : Logonname;
                    txtlogon.Text = Logonname;
                }

                txtpreLogonname.Text = de.Properties["sAMAccountName"].Value as string;
                PreLogonname = txtpreLogonname.Text.Trim();

                txtDomian.Text = dirContext.DomainName.Substring(0, dirContext.DomainName.IndexOf('.')).ToUpper() + @"\";
                cbDomain.Items.Add(string.Concat("@", dirContext.DomainName.ToUpper()));
                cbDomain.SelectedIndex = 0;

                double accountExpires = Convert.ToInt64(de.Properties["accountExpires"].Value);

                if (accountExpires == 9223372036854775807)
                    rbNever.Checked = true;
                else
                {
                    rbEndOf.Checked = true;
                    ConvertFromUnixTimestamp(accountExpires);
                }
                try
                {
                    string userCtrlBinStr = UserGroupUtils.DecimalToBase(userCtrlInt, 2);

                    if (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 10] == '1')
                    {
                        bMustChangePwd = true;
                    }
                    if (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 2] == '1')
                    {
                        bAcountDisable = true;
                    }
                    if (userCtrlBinStr.Length >= 17 && userCtrlBinStr[userCtrlBinStr.Length - 17] == '1')
                    {
                        bNeverExpiresPwd = true;
                        bMustChangePwd = false;
                    }
                    if (userCtrlBinStr.Length >= 10 && userCtrlBinStr[userCtrlBinStr.Length - 7] == '1'
                        && pwdLastSet != 0)
                    {
                        bUserCannotChange = true;
                    }
                    if (userCtrlBinStr.Length >= 8 && userCtrlBinStr[userCtrlBinStr.Length - 8] == '1')
                    {
                        bStorePwd = true;
                    }
                    if (userCtrlBinStr.Length >= 19 && userCtrlBinStr[userCtrlBinStr.Length - 19] == '1')
                    {
                        bSmartCardRequired = true;
                    }
                    if (userCtrlBinStr.Length >= 21 && userCtrlBinStr[userCtrlBinStr.Length - 21] == '1')
                    {
                        bAccSensitive = true;
                    }
                    if (userCtrlBinStr.Length >= 22 && userCtrlBinStr[userCtrlBinStr.Length - 22] == '1')
                    {
                        bUseDESDescription = true;
                    }
                    if (userCtrlBinStr.Length >= 23 && userCtrlBinStr[userCtrlBinStr.Length - 23] == '1')
                    {
                        bNotKrbAuthentication = true;
                    }
                }
                catch
                {
                }

                FillUserOptions();

                dateTimePicker.Enabled = rbEndOf.Checked;

                this.ParentContainer.DataChanged = false;
                this.ParentContainer.btnApply.Enabled = false;
            }
            catch (Exception e)
            {
                Logger.LogException("UserAccountPage.SetData", e);
            }
        }
Exemplo n.º 11
0
        public static Dictionary <int, string[]> EnumSessions(CredentialEntry ce, string sServer)
        {
            int    entriesread   = 0;
            int    totalentries  = 0;
            int    hResumeHandle = 0;
            IntPtr lpBuf         = IntPtr.Zero;

            Dictionary <int, string[]> SessionList = new Dictionary <int, string[]>();

            if (!EnsureNullSession(sServer, ce))
            {
                return(null);
            }

            try
            {
                int nRet = NetSessionEnum(sServer,
                                          null,
                                          null,
                                          1,
                                          out lpBuf,
                                          -1,
                                          ref entriesread,
                                          ref totalentries,
                                          ref hResumeHandle);

                Logger.Log(String.Format("{0}: nRet={1}, entriesread={2}, totalentries={3}",
                                         "Session.EnumSessions(): NetSessionEnum()",
                                         nRet, entriesread, totalentries), Logger.netAPILogLevel);

                if (nRet != 0)
                {
                    throw new AuthSessionException(ErrorCodes.WIN32String(nRet), null);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException("Session.EnumSessions", ex);
                return(null);
            }

            // iterate through the entries
            IntPtr lpTemp = lpBuf;

            for (int i = 0; i < entriesread; i++)
            {
                SESSION_INFO_1 s1 = (SESSION_INFO_1)Marshal.PtrToStructure(lpTemp, typeof(SESSION_INFO_1));

                bool   bIsGuest = (s1.sesi1_user_flags & SESS_GUEST) == SESS_GUEST;
                string IsGuest  = "";
                if (bIsGuest)
                {
                    IsGuest = "Yes";
                }
                else
                {
                    IsGuest = "No";
                }

                string[] sSessionInfo = { s1.sesi1_username, s1.sesi1_cname, s1.sesi1_num_opens.ToString(), TimeSpan.FromSeconds((double)s1.sesi1_time).ToString(), TimeSpan.FromSeconds((double)s1.sesi1_idle_time).ToString(), IsGuest };

                SessionList.Add(i, sSessionInfo);

                lpTemp = (IntPtr)((int)lpTemp + Marshal.SizeOf(s1));
            }
            NetApiBufferFree(lpBuf);

            return(SessionList);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Queries and fills the ldap message for the selected computer
        /// Gets the attribute list from AD for computer schema attribute.
        /// search for the attributes dNSHostName, cn or name and displays them in a controls
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="name"></param>
        /// <param name="dirnode"></param>
        public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
        {
            try
            {
                this.dirnode = dirnode;
                int ret = -1;
                List<LdapEntry> ldapEntries = null;

                ret = dirnode.LdapContext.ListChildEntriesSynchronous
                (dirnode.DistinguishedName,
                LdapAPI.LDAPSCOPE.BASE,
                "(objectClass=*)",
                null,
                false,
                out ldapEntries);

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

                LdapEntry ldapNextEntry = ldapEntries[0];

                string[] attrsList = ldapNextEntry.GetAttributeNames();

                if (attrsList != null)
                {
                    foreach (string attr in attrsList)
                    {
                        string sValue = "";

                        LdapValue[] attrValues = ldapNextEntry.GetAttributeValues(attr, dirnode.LdapContext);

                        if (attrValues != null && attrValues.Length > 0)
                        {
                            foreach (LdapValue value in attrValues)
                            {
                                sValue = sValue + "," + value.stringData;
                            }
                        }

                        if (sValue.StartsWith(","))
                        {
                            sValue = sValue.Substring(1);
                        }

                        sValue = sValue.Substring(0, sValue.Length);

                        if (string.Compare(sValue, "") == 0)
                        {
                            sValue = "<Not Set>";
                        }

                        if (string.Compare(attr, "operatingSystem") == 0)
                        {
                            txtName.Text = sValue;
                            operatingSystem = txtName.Text.Trim();
                        }

                        if (string.Compare(attr, "operatingSystemServicePack") == 0)
                        {
                            txtServicePack.Text = sValue;
                            operatingSystemServicePack = txtServicePack.Text.Trim();
                        }

                        if (string.Compare(attr, "operatingSystemVersion") == 0)
                        {
                            txtVersion.Text = sValue;
                            operatingSystemVersion = txtVersion.Text.Trim();
                        }
                    }
                }
                this.ParentContainer.DataChanged = false;
                UpdateApplyButton();
            }
            catch (Exception e)
            {
                container.ShowError(e.Message);
            }
        }
Exemplo n.º 13
0
        public CredentialEntry Clone()
        {

            string resultMachineName = null;


            if (!String.IsNullOrEmpty(this.MachineName))
            {
                resultMachineName = (string)this.MachineName.Clone();
            }


            CredentialEntry result = new CredentialEntry(this.Invalidated, this.DefaultCreds, resultMachineName);

            result.Domain = (this.Domain == null) ? null : (string) this.Domain.Clone();
            result.Password = (this.Password == null) ? null : (string)this.Password.Clone();
            result.UserName = (this.UserName == null) ? null : (string)this.UserName.Clone();



            return result;
        }
Exemplo n.º 14
0
        public static Process RunAddAShareWizard(CredentialEntry ce, string sHostname)
        {
            Process proc;
            try
            {
                Session.EnsureNullSession(sHostname, ce);
                proc = ProcessUtil.Exec(Environment.SystemDirectory, "shrpubw.exe", "/s " + sHostname);
            }
            catch (Exception ex)
            {
                Logger.LogException("SharesAPI.RunAddAShareWizard()", ex);
                proc = null;
            }

            return proc;
        }
Exemplo n.º 15
0
    /// <summary>
    /// Gets all groups for the selected user AD Object is member of
    /// Add groups to the Member Of page listview
    /// </summary>
    /// <param name="ce"></param>
    /// <param name="servername"></param>
    /// <param name="name"></param>
    /// <param name="dirnode"></param>
    public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
    {
        _servername = servername;
        _dirnode = dirnode;

        try
        {
            string[] groupDns = UserGroupUtils.GetGroupsforUser(dirnode);

            MemoflistView.Items.Clear();
            //show a list of group names in the member of page
            Logger.Log("user member of contains: ");
            if (groupDns != null && groupDns.Length > 0)
            {
                //populate the data in usermemberOf page using groupDns
                foreach (string groupDn in groupDns)
                {
                    Logger.Log("group: " + groupDn);
                    //CN=Domain Users,CN=Users,DC=qadom,DC=centeris,DC=com
                    // split the groupDns
                    string[] slvItem = UserGroupUtils.splitDn(groupDn);
                    string sLDAPPath = string.Format("LDAP://{0}/{1}", _dirnode.LdapContext.DomainName, groupDn);
                    DirectoryEntry entry = new DirectoryEntry(sLDAPPath, _dirnode.LdapContext.UserName, _dirnode.LdapContext.Password);
                    if (entry == null)
                    {
                        return;
                    }
                    ListViewItem lvItem = new ListViewItem(slvItem);
                    lvItem.ImageIndex = MemOfPages.GetIndexForADObject(entry);
                    MemoflistView.Items.Add(lvItem);
                    lvItem.Tag = groupDn;

                    if (!slvItem[0].Equals("Domain Users", StringComparison.InvariantCultureIgnoreCase))
                    {
                        MemofDnList.Add(groupDn);
                    }
                }
                //settings primary group to user
                sPrimayGroup = UserGroupUtils.GetPrimaryGroup(_dirnode);
                string[] Items = UserGroupUtils.splitDn(sPrimayGroup);
                if (!string.IsNullOrEmpty(Items[0]))
                {
                    DomainUserlabel.Text = Items[0];
                }

                if (MemoflistView.Items.Count > 0)
                {
                    MemoflistView.Items[0].Selected = true;
                }
            }
        }
        catch (Exception ex)
        {
            Logger.LogException("UserMemberOfPage.SetData", ex);
        }
    }
Exemplo n.º 16
0
        public static void CloseFile(IntPtr handle_b, CredentialEntry ce, string sHostname, int nFileId)
        {
            // establish null session
            Session.EnsureNullSession(sHostname, ce);

            try
            {
                int nret = -1;

                Logger.Log(String.Format("NetFileClose(sHostname={1}) called",
                   sHostname), Logger.FileShareManagerLogLevel);

                if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
                {
                    nret = NetFileClose(sHostname, nFileId);
                }
                else
                {
                    nret = NetFileClose(handle_b, sHostname, nFileId);
                }

                Logger.Log(String.Format(
                      "NetFileClose(); result={0}",
                      nret));
            }
            catch (Win32Exception we)
            {
                throw new LikewiseAPIException(we);
            }
        }
Exemplo n.º 17
0
        public static void AddShare(IntPtr handle_b, CredentialEntry ce, string sHostname, string sShareName)
        {
            // establish null session
            //Session.EnsureNullSession(sHostname, ce);

            try
            {
                int nret = -1;
                IntPtr pBuf = IntPtr.Zero;
                int param_err = 0;

                Logger.Log(String.Format("NetShareAdd(sHostname={0} ,sShareName={1}) called",
                   sHostname, sShareName), Logger.FileShareManagerLogLevel);

                if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
                {
                    nret = NetShareAdd(
                                        handle_b,
                                        sHostname,
                                        0,
                                        ref pBuf,
                                        ref param_err
                                      );
                }
                else
                {
                    nret = NetShareDel(handle_b, sHostname, sShareName, 0);
                }

                Logger.Log(String.Format(
                      "NetShareDel(); result={0}",
                      nret));
            }
            catch (Win32Exception we)
            {
                throw new LikewiseAPIException(we);
            }
        }
Exemplo n.º 18
0
        public static Dictionary<int, string[]> EnumFiles(IntPtr pHandle, CredentialEntry ce, string sHostname)
        {
            // establish null session
            //if (!Session.EnsureNullSession(sHostname, ce))
            //{
            //    return null;
            //}

            try
            {
                Dictionary<int, string[]> UserList = new Dictionary<int, string[]>();

                IntPtr pBuf = IntPtr.Zero;
                int cRead = 0;
                int cTotal = 0;
                int hResume = 0;
                int maxlen = -1;
                int nret = -1;

                Logger.Log(String.Format("NetFileEnum(handle_b={0:x}, sHostname={1}) called",
                   pHandle.ToInt32(), sHostname), Logger.FileShareManagerLogLevel);

                if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
                {
                    nret = NetFileEnum(sHostname,
                                       null,
                                       null,
                                       3,
                                       ref pBuf,
                                       maxlen,
                                       ref cRead,
                                       ref cTotal,
                                       ref hResume);
                }
                else
                {
                    nret = NetFileEnum(pHandle,
                                           sHostname,
                                           null,
                                           null,
                                           3,
                                           ref pBuf,
                                           maxlen,
                                           ref cRead,
                                           ref cTotal,
                                           ref hResume);
                }

                Logger.Log(String.Format(
                       "NetFileEnum(); result={0}, pBuf={1}, cRead={2}, cTotal={3}, hResume={4}",
                   nret, pBuf, cRead, cTotal, hResume));

                // now, iterate through the data in pBuf
                IntPtr pCur = pBuf;
                for (int i = 0; i < cRead; i++)
                {
                    // marshal the entry into
                    FILE_INFO_3 fi3 = (FILE_INFO_3)Marshal.PtrToStructure(pCur, typeof(FILE_INFO_3));

                    // create a row
                    // set the mode
                    int iMode = fi3.fi3_permission;
                    string sMode = "";
                    if ((iMode & PERM_FILE_READ) == PERM_FILE_READ)
                        sMode = "Read";
                    if ((iMode & PERM_FILE_WRITE) == PERM_FILE_WRITE)
                    {
                        if (sMode.Length > 0)
                            sMode += "+Write";
                        else
                            sMode = "Write";
                    }
                    if ((iMode & PERM_FILE_CREATE) == PERM_FILE_CREATE)
                    {
                        if (sMode.Length > 0)
                            sMode += "+Create";
                        else
                            sMode = "Create";
                    }
                    string[] sFileInfo = { fi3.fi3_pathname, fi3.fi3_username, fi3.fi3_num_locks.ToString(), sMode, fi3.fi3_id.ToString() };

                    UserList.Add(i, sFileInfo);


                    // advance to the next entry
                    pCur = (IntPtr)((int)pCur + Marshal.SizeOf(fi3));
                }
                if (pBuf != IntPtr.Zero)
                {
                    // free the data
                    if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
                    {
                        NetApiBufferFree(pBuf);
                    }
                    else
                    {
                        SrvSvcFreeMemory(pBuf);
                    }
                }

                // all done
                return UserList;

            }
            catch (Win32Exception we)
            {
                throw new LikewiseAPIException(we);
            }
        }
Exemplo n.º 19
0
        public static Dictionary<int, string[]> EnumShares(IntPtr handle_b, CredentialEntry ce, string sHostname)
        {
            //// establish null session
            //if(!Session.EnsureNullSession(sHostname, ce))
            //{
            //    return null;
            //}

            try
            {
                Dictionary<int, string[]> ShareList = new Dictionary<int, string[]>();

                IntPtr pBuf = IntPtr.Zero;
                int cRead = 0;
                int cTotal = 0;
                int hResume = 0;
                int maxlen = -1;
                int nret = -1;

                if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
                {
                    Logger.Log(String.Format("NetShareEnum(sHostname={0}) called",
                    sHostname), Logger.FileShareManagerLogLevel);

                    nret = NetShareEnum(sHostname,
                                                2,
                                                ref pBuf,
                                                maxlen,
                                                ref cRead,
                                                ref cTotal,
                                                ref hResume);
                }
                else
                {
                    Logger.Log(String.Format("NetShareEnum(handle_b={0:x},sHostname={1}) called",
                    handle_b.ToInt32(), sHostname), Logger.FileShareManagerLogLevel);

                    maxlen = 20;

                    nret = NetShareEnum(handle_b,
                                            sHostname,
                                            2,
                                            ref pBuf,
                                            maxlen,
                                            ref cRead,
                                            ref cTotal,
                                            ref hResume);
                }

                Logger.Log(String.Format(
                        "NetShareEnum(); result={0}, pBuf={1}, cRead={2}, cTotal={3}, hResume={4}",
                    nret, pBuf, cRead, cTotal, hResume));

                // now, iterate through the data in pBuf
                IntPtr pCur = pBuf;
                for (int i = 0; i < cRead; i++)
                {
                    // marshal the entry into
                    SHARE_INFO_2 si2 = (SHARE_INFO_2)Marshal.PtrToStructure(pCur, typeof(SHARE_INFO_2));

                    // only allow regular diskshares
                    // TODO: Review this. Should we not display admin shares?
                    if (si2.shi2_type == STYPE_DISKTREE)
                    {
                        string[] sShareInfo = { si2.shi2_netname, si2.shi2_path, si2.shi2_remark, si2.shi2_current_uses.ToString() };
                        ShareList.Add(i, sShareInfo);
                    }

                    // advance to the next entry
                    pCur = (IntPtr)((int)pCur + Marshal.SizeOf(si2));
                }
                if (pBuf != IntPtr.Zero)
                {
                    // free the data
                    if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
                    {
                        NetApiBufferFree(pBuf);
                    }
                    else
                    {
                        SrvSvcFreeMemory(pBuf);
                    }
                }
                // all done
                return ShareList;
            }
            catch (Win32Exception we)
            {
                throw new LikewiseAPIException(we);
            }
        }
Exemplo n.º 20
0
        public static bool EnsureNullSession(string sServer, CredentialEntry ce)
        {
            if (String.IsNullOrEmpty(sServer))
            {
                return(false);
            }

            Logger.Log(String.Format("Session.EnsureNullSession({0}, {1}) called",
                                     sServer, ce),
                       Logger.netAPILogLevel);

            if (ce == null)
            {
                Logger.Log("Session.EnsureNullSession() called with CredentialEntry ce=null, returning false",
                           Logger.authLogLevel);
                return(false);
            }

            sServer = Canon(sServer);

            try
            {
                // if we already have a session, don't recreate it
                if (alSessions.Contains(sServer))
                {
                    return(true);
                }
                else
                {
                    try
                    {
                        DeleteNullSession(sServer);
                    }
                    catch (AuthSessionException aex)
                    {
                        Logger.Log("EnsureNullSession: DeleteNullSession failed (as expected) beacuse " + aex.Message, Logger.netAPILogLevel);
                    }

                    try
                    {
                        if (CreateNullSession(sServer, ce.MachineName, ce))
                        {
                            alSessions.Add(sServer);
                            return(true);
                        }
                    }
                    catch (AuthSessionException aex)
                    {
                        Logger.Log("EnsureNullSession: CreateNullSession failed unexpectedly. beacuse " + aex.Message, Logger.netAPILogLevel);
                    }
                }
                return(false);
            }
            catch (DllNotFoundException ex)
            {
                Logger.ShowUserError(String.Format(
                                         "DllNotFound Exception caught in SharesAPI.EnumShares: Could not load library: {0}",
                                         ex.Message));
                ce.Invalidate(sServer);
                return(false);
            }
            catch (Exception ex)
            {
                Logger.LogException("Session.EnsureNullSession", ex);
                ce.Invalidate(sServer);
                return(false);
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Deletes a printer from the designated server. Must have administrator access to it.
 /// </summary>
 /// <param name="sServer"></param>
 /// <param name="sPrinter"></param>
 public static void DeletePrinter(CredentialEntry ce, string sServer, string sPrinter)
 {
     Session.EnsureNullSession(sServer, ce);
     
     // first, open the printer
     string s = Canon(sServer) + @"\" + sPrinter;
     int hPrinter;
     PRINTER_DEFAULTS pd = new PRINTER_DEFAULTS();
     pd.pDatatype = IntPtr.Zero;
     pd.pDevMode = IntPtr.Zero;
     pd.DesiredAccess = PRINTER_ALL_ACCESS;
     IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(pd));
     Marshal.StructureToPtr(pd, p, false);
     if (!OpenPrinter(s, out hPrinter, p))
     {
         // free memory
         Marshal.DestroyStructure(p, typeof(PRINTER_DEFAULTS));
         Marshal.FreeHGlobal(p);
         
         int nError = Marshal.GetLastWin32Error();
         Win32Exception we = new Win32Exception(nError);
         if (nError == nErrorAccessDenied)
         {
             throw new AuthException(we);
         }
         else
         {
             throw we;
         }
     }
     
     Marshal.DestroyStructure(p, typeof(PRINTER_DEFAULTS));
     Marshal.FreeHGlobal(p);
     
     // now remove it from AD
     PRINTER_INFO_7 pi7 = new PRINTER_INFO_7();
     pi7.pszObjectGUID = IntPtr.Zero;
     pi7.dwAction = (uint) DSPRINT_OPTIONS.DSPRINT_UNPUBLISH;
     p = Marshal.AllocHGlobal(Marshal.SizeOf(pi7));
     Marshal.StructureToPtr(pi7, p, false);
     SetPrinter(hPrinter, 7, p, 0);
     
     // NOTE: we swallow any error since the operation may be left in a "pending" state rather
     // than returning success or failure right away.
     
     // free memory
     Marshal.DestroyStructure(p, typeof(PRINTER_INFO_7));
     Marshal.FreeHGlobal(p);
     
     // finally, remove the printer
     if (!DeletePrinter(hPrinter))
     {
         int nError = Marshal.GetLastWin32Error();
         Win32Exception we = new Win32Exception(nError);
         if (nError == nErrorAccessDenied)
         {
             throw new AuthException(we);
         }
         else
         {
             throw we;
         }
     }
 }
Exemplo n.º 22
0
 public static Process RunMMC(CredentialEntry ce, string sHostname)
 {
     Session.EnsureNullSession(sHostname, ce);
     return ProcessUtil.ShellExec(Environment.SystemDirectory, "fsmgmt.msc", "/s /computer=" + sHostname, "open");
 }
        /// <summary>
        /// Method to load data to the tab pages while loading
        /// Gets all the tab pages that are of type MPage and get calls the SetData()
        /// Queries the ldap message to the selected node
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="user"></param>
        /// <param name="dirnode"></param>
        /// <param name="ldapSchemaCache"></param>
        public void SetData(CredentialEntry ce, string servername, string user, ADUCDirectoryNode dirnode, LDAPSchemaCache ldapSchemaCache)
        {
            Applied = false;
            _plugin = dirnode.Plugin as ADUCPlugin;
            this.Text = String.Format(this.Text, user);

            objInfo = new ObjectPropertyInfo
                                      (ce,
                                      servername,
                                      user,
                                      dirnode,
                                      null
                                      );

            threadMain = new Thread(new ThreadStart(AddPagesToThread));
            threadMain.Start();

            _plugin.Propertywindowhandles.Add(objInfo.dirnode.DistinguishedName, this);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Queries and fills the ldap message for the selected group
        /// Gets the attribute list from AD for group schema attribute.
        /// search for the attributes description, cn or name and displays them in a controls
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="name"></param>
        /// <param name="dirnode"></param>
        public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
        {
            try
            {
                this.dirnode = dirnode;

                DirectoryContext dirContext = dirnode.LdapContext;

                //first obtain the current userAccountControl value
                DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dirContext.DomainName, dirnode.DistinguishedName));

                profilePath = de.Properties["profilePath"].Value as string;
                scriptPath = de.Properties["scriptPath"].Value as string;
                homeDirectory = de.Properties["homeDirectory"].Value as string;
                homeDrive = de.Properties["homeDrive"].Value as string;

                foreach (string ch in Charlist)
                {
                    cbDrive.Items.Add(ch);
                }

                if (homeDrive != null)
                {
                    rbConnect.Checked = true;
                    txtConnect.Text = homeDirectory;
                    int selectedIndex = 0;
                    if (cbDrive.Items.Contains(homeDrive))
                    {
                        selectedIndex = cbDrive.Items.IndexOf(homeDrive);
                    }
                    else
                    {
                        selectedIndex = cbDrive.Items.Add(homeDrive);
                    }
                    cbDrive.SelectedIndex = selectedIndex;
                }
                else
                {
                    rbLocalPath.Checked = true;
                    txtLocalPath.Text = homeDirectory;
                    cbDrive.SelectedIndex = 0;
                }

                txtProfilePath.Text = profilePath;
                txtLogonScript.Text = scriptPath;

                ParentContainer.DataChanged = false;

                ParentContainer.btnApply.Enabled = false;
            }
            catch (Exception e)
            {
                Logger.LogException("UserGeneralEditPage.SetData", e);
            }
        }
Exemplo n.º 25
0
    /// <summary>
    /// Method to load data to the tab pages while loading
    /// Gets the all attribute list for the selected AD object by querying the Ldap Message.
    /// </summary>
    /// <param name="ce"></param>
    /// <param name="servername"></param>
    /// <param name="username"></param>
    /// <param name="dirNode"></param
    public void SetData(CredentialEntry ce, string servername, string username, ADUCDirectoryNode dirNode)
    {
        try
        {
            dirnode = dirNode;
            InitLdapMessage();
            schemaCache = dirnode.LdapContext.SchemaCache;

            if (objectClasses != null && objectClasses.Length != 0)
            {
                MandatoryAttributes = new List<string>();
                foreach (string objectClass in objectClasses)
                {
                    LdapClassType classtype = schemaCache.GetSchemaTypeByObjectClass(objectClass) as LdapClassType;
                    if (classtype != null && classtype.MandatoryAttributes != null)
                    {
                        foreach (string attr in classtype.MandatoryAttributes)
                        {
                            MandatoryAttributes.Add(attr);
                        }
                    }
                }
                if (dirnode.ObjectClass.Trim().Equals("user", StringComparison.InvariantCultureIgnoreCase) ||
                    dirnode.ObjectClass.Trim().Equals("group", StringComparison.InvariantCultureIgnoreCase) ||
                    dirnode.ObjectClass.Trim().Equals("computer", StringComparison.InvariantCultureIgnoreCase))
                {
                    MandatoryAttributes.Add("objectSid");
                    MandatoryAttributes.Add("sAMAccountName");
                    if (!MandatoryAttributes.Contains("cn"))
                    {
                        MandatoryAttributes.Add("cn");
                    }
                }
            }

            FillAttributeList(true, out _modifiedPageObject);
            ParentContainer.DataChanged = false;
            if (_modifiedPageObject != null)
            {
                _OriginalPageObject = (ADEditPageObject)_modifiedPageObject.Clone();
            }
            else
            {
                _OriginalPageObject = new ADEditPageObject();
            }
            UpdateApplyButton();
        }
        catch (Exception e)
        {
            Logger.LogException("ADEditPage.SetData", e);
        }
    }
 /// <summary>
 /// Queries and fills the ldap message for the Domain
 /// Gets the attribute list from AD for Domain schema attribute.
 /// search for the attributes description
 /// </summary>
 /// <param name="ce"></param>
 /// <param name="servername"></param>
 /// <param name="name"></param>
 /// <param name="dirnode"></param>
 public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
 {
     try
     {
         this.dirnode = dirnode;
         int ret = -1;
         List<LdapEntry> ldapEntries = null;
         
         ret = dirnode.LdapContext.ListChildEntriesSynchronous
         (dirnode.DistinguishedName,
         LdapAPI.LDAPSCOPE.BASE,
         "(objectClass=*)",
         null,
         false,
         out ldapEntries);
         
         if (ldapEntries == null || ldapEntries.Count == 0)
         {
             return;
         }
         
         LdapEntry ldapNextEntry = ldapEntries[0];
         
         string[] attrsList = ldapNextEntry.GetAttributeNames();
         
         if (attrsList != null)
         {
             foreach (string attr in attrsList)
             {
                 string sValue = "";
                 
                 LdapValue[] attrValues = ldapNextEntry.GetAttributeValues(attr, dirnode.LdapContext);
                 
                 if (attrValues != null && attrValues.Length > 0)
                 {
                     foreach (LdapValue value in attrValues)
                     {
                         sValue = sValue + "," + value.stringData;
                     }
                 }
                 
                 if (sValue.StartsWith(","))
                 {
                     sValue = sValue.Substring(1);
                 }
                 
                 if (string.Compare(sValue, "") == 0)
                 {
                     sValue = "<Not Set>";
                 }
                 
                 if (string.Compare(attr, "description") == 0)
                 {
                     this.txtDescription.Text = sValue;
                     Description = sValue;
                 }
                 
                 //As of now we are not getting canonicalName attribute in the list because of paging issue
                 if (string.Compare(attr, "canonicalName") == 0)
                 {
                     this.Namelabel.Text = sValue.Substring(0, sValue.Length - 1);
                 }
                 
                 if (string.Compare(attr, "name") == 0)
                 {
                     this.textBoxDomainName.Text = sValue.ToUpper();
                     this.Namelabel.Text = sValue;
                 }
             }
             
             this.lblForestLevel.Text = this.labelDomainLevel.Text = "Windows Server 2003";
             
             this.ParentContainer.DataChanged = false;
             this.ParentContainer.btnApply.Enabled = false;
         }
     }
     catch (Exception e)
     {
         container.ShowError(e.Message);
     }
     // throw new NotImplementedException();
 }
Exemplo n.º 27
0
 public static Process ViewShare(CredentialEntry ce, string sHostname, string sShare)
 {
     Session.EnsureNullSession(sHostname, ce);
     return ProcessUtil.Exec(Environment.SystemDirectory, "explorer.exe", @"\\" + sHostname + @"\" + sShare);
 }
Exemplo n.º 28
0
        public static bool IsNullOrEmpty(CredentialEntry ce)
        {
            if (ce == null ||
                String.IsNullOrEmpty(ce.Domain) ||
                String.IsNullOrEmpty(ce.Password) ||
                String.IsNullOrEmpty(ce.UserName))
            {
                return true;
            }

            return false;
        }
Exemplo n.º 29
0
    private bool ProcessMembers(CredentialEntry ce, string domain)
    {
        bool retVal = true;
        uint result = (uint)LUGAPI.WinError.ERROR_SUCCESS;

        for (int i = 0; i < lvMembers.Items.Count; i++)
        {
            try
            {
                result = LUGAPI.NetAddGroupMember(
                    _hn.hostName,
                    this.GroupName,
                    lvMembers.Items[i].Text
                    );

                if (result != (uint)LUGAPI.WinError.ERROR_SUCCESS)
                {
                    container.ShowError(String.Format(
                        "User \"{0}\" could not be added:\n{1}",
                        lvMembers.Items[i].Text,
                        ErrorCodes.WIN32String((int)result)));
                }
            }
            catch (Exception)
            {
                retVal = false;
                container.ShowError(
                String.Format("Failed to add user {0} to group {1}", lvMembers.Items[i].Text, this.GroupName));
            }
            
        }
        return retVal;
    }
 /// <summary>
 /// Queries and fills the ldap message for the selected User
 /// Gets the attribute list from AD for User schema attribute.
 /// search for the attributes givenName, displayName, sAMAccountName,
 /// memberOf, sAMAccountType, userPrincipalName, sn and displays them in a controls
 /// </summary>
 /// <param name="ce"></param>
 /// <param name="servername"></param>
 /// <param name="name"></param>
 /// <param name="dirnode"></param>
 public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
 {
     try
     {
         int ret = -1;
         _editObject = new UserGenerelEditObject();
         this.dirnode = dirnode;
         
         List<LdapEntry> ldapEntries = null;
         
         ret = dirnode.LdapContext.ListChildEntriesSynchronous(
         dirnode.DistinguishedName,
         LdapAPI.LDAPSCOPE.BASE,
         "(objectClass=*)",
         null,
         false,
         out ldapEntries);
         
         if (ldapEntries == null || ldapEntries.Count == 0)
         {
             return;
         }
         
         LdapEntry ldapNextEntry = ldapEntries[0];
         
         string[] attrsList = ldapNextEntry.GetAttributeNames();
         
         if (attrsList != null)
         {
             foreach (string attr in attrsList)
             {
                 string sValue = "";
                 
                 LdapValue[] attrValues = ldapNextEntry.GetAttributeValues(attr, dirnode.LdapContext);
                 
                 if (attrValues != null && attrValues.Length > 0)
                 {
                     foreach (LdapValue value in attrValues)
                     {
                         sValue = sValue + "," + value.stringData;
                     }
                 }
                 
                 if (sValue.StartsWith(","))
                 {
                     sValue = sValue.Substring(1);
                 }
                 if (string.Compare(sValue, "") == 0)
                 {
                     sValue = "<Not Set>";
                 }
                 
                 if (string.Compare(attr, "cn") == 0)
                 {
                     this.lblUserName.Text = sValue;
                 }
                 
                 if (string.Compare(attr, "givenName") == 0)
                 {
                     this.FnametextBox.Text = sValue;
                     _editObject.FirstName = sValue;
                 }
                 
                 if (string.Compare(attr, "initials") == 0)
                 {
                     this.InitialTextBox.Text = sValue;
                     _editObject.Initails = sValue;
                 }
                 
                 if (string.Compare(attr, "sn") == 0)
                 {
                     this.LnametextBox.Text = sValue;
                     _editObject.LastName = sValue;
                 }
                 
                 if (string.Compare(attr, "displayName") == 0)
                 {
                     this.DisplayNametextBox.Text = sValue;
                     _editObject.DisplayName = sValue;
                 }
                 
                 if (string.Compare(attr, "description") == 0)
                 {
                     this.DescriptextBox.Text = sValue;
                     _editObject.Description = sValue;
                 }
                 
                 if (string.Compare(attr, "physicalDeliveryOfficeName") == 0)
                 {
                     this.OfficetextBox.Text = sValue;
                     _editObject.Office = sValue;
                 }
                 
                 if (string.Compare(attr, "telephoneNumber") == 0)
                 {
                     this.TelephonetextBox.Text = sValue;
                     _editObject.TelephoneNumber = sValue;
                 }
                 
                 if (string.Compare(attr, "mail") == 0)
                 {
                     this.emailtextBox.Text = sValue;
                     _editObject.Email = sValue;
                 }
                 
                 if (string.Compare(attr, "wWWHomePage") == 0)
                 {
                     this.webpagetextBox.Text = sValue;
                     _editObject.WebPage = sValue;
                 }
                 if (string.Compare(attr, "url") == 0)
                 {
                     _editObject.WebPageOther = sValue;
                 }
                 if (string.Compare(attr, "otherTelephone") == 0)
                 {
                     sValue = sValue.Replace(',', ';');
                     _editObject.TelephoneNumberOther = sValue;
                 }
             }
         }
         
         if (_editObject != null)
         {
             _originalObject = (UserGenerelEditObject)_editObject.Clone();
         }
         else
         {
             _originalObject = new UserGenerelEditObject();
         }
         ParentContainer.DataChanged = false;
         UpdateApplyButton();
     }
     catch (Exception e)
     {
         Logger.LogException("UserGeneralEditPage.SetData", e);
     }
 }
        /// <summary>
        /// Queries and fills the ldap message for the selected User
        /// Gets the attribute list from AD for User schema attribute.
        /// search for the attributes givenName, displayName, sAMAccountName,
        /// memberOf, sAMAccountType, userPrincipalName, sn and displays them in a controls
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="name"></param>
        /// <param name="dirnode"></param>
        public void SetData(CredentialEntry ce, string servername, string name, ADUCDirectoryNode dirnode)
        {
            try
            {
                this.dirnode = dirnode;
                SetControlStatus();

                int iOuCount = 0; int iUserCount = 0; int iCompCount = 0; int iGroupCount = 0; int iContactCount = 0;
                int iOtherCount = 0; int iTotalSummary = 0;

                foreach (ADUCDirectoryNode dn in this.parentDlg.ObjectCounts)
                {
                    if (dn != null)
                    {
                        if (dn.ObjectClass.Trim().Equals("OrganizationalUnit", StringComparison.InvariantCultureIgnoreCase))
                        {
                            iOuCount++;
                        }
                        else if (dn.ObjectClass.Trim().Equals("user", StringComparison.InvariantCultureIgnoreCase))
                        {
                            iUserCount++;
                        }
                        else if (dn.ObjectClass.Trim().Equals("group", StringComparison.InvariantCultureIgnoreCase))
                        {
                            iGroupCount++;
                        }
                        else if (dn.ObjectClass.Trim().Equals("computer", StringComparison.InvariantCultureIgnoreCase))
                        {
                            iCompCount++;
                        }
                        else if (dn.ObjectClass.Trim().Equals("contact", StringComparison.InvariantCultureIgnoreCase))
                        {
                            iContactCount++;
                        }
                        else
                        {
                            iOtherCount++;
                        }
                    }
                }
                if (iOuCount != 0)
                {
                    lblOUs.Show();
                    lblOUs.Text = iOuCount.ToString();
                    iTotalSummary += iOuCount;
                }
                if (iUserCount != 0)
                {
                    lblUsers.Show();
                    iTotalSummary += iUserCount;
                    lblUsers.Text = iUserCount.ToString();
                }
                if (iGroupCount != 0)
                {
                    lblGroups.Show();
                    iTotalSummary += iGroupCount;
                    lblGroups.Text = iGroupCount.ToString();
                }
                if (iCompCount != 0)
                {
                    lblComputers.Show();
                    iTotalSummary += iCompCount;
                    lblComputers.Text = iCompCount.ToString();
                }
                if (iContactCount != 0)
                {
                    lblContacts.Show();
                    iTotalSummary += iContactCount;
                    lblContacts.Text = iContactCount.ToString();
                }
                if (iOtherCount != 0)
                {
                    lblOthers.Show();
                    iTotalSummary += iOtherCount;
                    lblOthers.Text = iOtherCount.ToString();
                }
                lblSummary.Text = iTotalSummary.ToString();
            }
            catch (Exception e)
            {
                Logger.LogException("MultiItemsGeneralEditPage.SetData", e);
            }
        }
Exemplo n.º 32
0
#pragma warning restore 414
#endif

        #endregion

        #region Static Interface
        public static bool CreateNullSession(string sServer, string sShortname, CredentialEntry ce)
        {
            Logger.Log(
                String.Format("Session.CreateNullSession({0}, {1}, {2}) called", sServer, sShortname, ce),
                Logger.netAPILogLevel);

            int nErr;

            // set up the user name and password; map "root" as needed
            string sUsername;
            string sPassword;

            if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
            {
                if (ce != null && !ce.DefaultCreds && ce.Password != new String('*', 16))
                {
                    if (ce.UserName.IndexOf('\\') < 0 && !String.IsNullOrEmpty(ce.Domain))
                    {
                        sUsername = String.Format("{0}\\{1}", ce.Domain, ce.UserName);
                    }
                    else
                    {
                        sUsername = ce.UserName;
                    }
                    sPassword = ce.Password;
                }
                else
                {
                    // setup for default creds
                    sUsername = null;
                    sPassword = null;
                    Logger.Log("CreateNullSession(): Using default creds", Logger.netAPILogLevel);
                }
            }
            else
            {
                if (ce.UserName.IndexOf(@"\") < 0 && !String.IsNullOrEmpty(ce.Domain))
                {
                    sUsername = String.Format("{0}\\{1}", ce.Domain, ce.UserName);
                }
                else
                {
                    sUsername = ce.UserName;
                }
                sPassword = ce.Password;
            }

            // set up a NETRESOURCE structure
            NETRESOURCE nr = new NETRESOURCE();

            nr.dwScope       = 0;
            nr.dwType        = 0;
            nr.dwDisplayType = 0;
            nr.dwUsage       = 0;
            nr.LocalName     = null;
            nr.RemoteName    = @"\\" + sServer + @"\IPC$";
            nr.Comment       = null;
            nr.Provider      = null;

            // try the operation. Throws exception if it fails.
            if (Configurations.currentPlatform == LikewiseTargetPlatform.Windows)
            {
                nErr = WindowsSession.WNetAddConnection2(nr, sPassword, sUsername, 0);
            }
            else
            {
                nErr = WNetAddConnection2(nr, sPassword, sUsername, 0);
            }

            //HACK: WNetAddConnection2 appears to return 'access denied' even when it has just granted access!
            //this is a workaround with the side-effect that the user will never be warned when their password
            //is invalid.
            if (nErr == (int)ErrorCodes.WIN32Enum.ERROR_ACCESS_DENIED)
            {
                Logger.Log(String.Format("CreateNullSession(): Ignoring error!  nErr={0}: {1}",
                                         nErr, ErrorCodes.WIN32String(nErr)), Logger.LogLevel.Error);

                System.Windows.Forms.MessageBox.Show("WNetAddConnection2 success but ERROR_ACCESS_DENIED");

                return(true);
            }
            else if (nErr != 0)
            {
                ce.Invalidate(sServer);

                Logger.Log(String.Format("CreateNullSession(): nErr={0}: {1}",
                                         nErr, ErrorCodes.WIN32String(nErr)), Logger.LogLevel.Error);
                return(false);
            }

            Logger.Log("CreateNullSession() successful", Logger.netAPILogLevel);

            return(true);
        }
Exemplo n.º 33
0
        /// <summary>
        /// Method to load data to the tab pages while loading
        /// Gets all the tab pages that are of type MPage and gets calls the SetData()
        /// Queries the ldap message to the selected node
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="computer"></param>
        /// <param name="dirnode"></param>
        /// <param name="ldapSchemaCache"></param>
        public void SetData(CredentialEntry ce, string sharename, object shareInfo)
        {
            Applied = false;

            this.Text = String.Format(Text, sharename);

            ICollection pages = this.GetPages();

            foreach (MPPage page in pages)
            {
                if (page != null)
                {
                    IDirectoryPropertiesPage ipp = page as IDirectoryPropertiesPage;
                    if (ipp != null)
                    {
                        ipp.SetData(ce, sharename, shareInfo);
                    }
                }
            }
        }
Exemplo n.º 34
0
 /// <summary>
 /// Fetches data about the printers available on the designated server
 /// </summary>
 /// <param name="sServer"></param>
 /// <param name="dt">The DataTable into which the data should be placed. dt MUST have been created properly with CreateDataTable</param>
 public static Dictionary<int, string[]> FetchPrinterData(CredentialEntry ce, string sServer)
 {
     int dwFlags = (int)PEFlags.PRINTER_ENUM_NAME;
     string Name = Canon(sServer);
     int Level = 2;
     IntPtr pPrinterEnum = IntPtr.Zero;
     int cBufNeeded = 0;
     int cReturned = 0;
     
     if (!Session.EnsureNullSession(sServer, ce))
     {
         return null;
     }
     
     Dictionary<int, string[]> printInfoList = new Dictionary<int, string[]>();
     
     ///
     /// TODO: revise. Samba 3.0.13 fails if we pass in a null buffer. To avoid this
     /// pass in a pointer to a zero length buffer!
     ///
     
     #if SAMBAFIXED
     if (EnumPrinters( dwFlags, Name, Level, pPrinterEnum, 0, ref cBufNeeded, ref cReturned))
     {
         // Can only happen if no printers available!
         return;
     }
     #else
     {
         
     }
     pPrinterEnum = Marshal.AllocHGlobal(0);
     if (EnumPrinters(dwFlags, Name, Level, pPrinterEnum, 0, ref cBufNeeded, ref cReturned))
     {
         // free the mem
         Marshal.FreeHGlobal(pPrinterEnum);
         
         // Can only happen if no printers available!
         return null;
     }
     // free the mem
     Marshal.FreeHGlobal(pPrinterEnum);
     #endif
     
     // Normally, we fail because we need a bigger buffer. However, if we fail
     // with RPC_S_CALL_FAILED, this means that we "succeeded" but that the remote
     // machine has nothing to tell us
     int nError = Marshal.GetLastWin32Error();
     
     if (nError == nErrorRPC_S_CALL_FAILED)
     {
         return null;
     }
     
     if (nError != ERROR_INSUFFICIENT_BUFFER)
     {
         // Any other error results in an exception
         string sErr;
         if (nError == nErrorBadRPC)
         {
             sErr = sBadServerName;
         }
         else if (nError == nErrorAccessDenied)
         {
             throw new AuthException(new Win32Exception(nError));
         }
         else
         {
             sErr = string.Format(sErrorMsg, sServer, nError);
         }
         throw new Win32Exception(sErr);
     }
     
     // allocate a big enough buffer
     pPrinterEnum = Marshal.AllocHGlobal(cBufNeeded);
     
     // retry
     if (!EnumPrinters(dwFlags, Name, Level, pPrinterEnum, cBufNeeded, ref cBufNeeded, ref cReturned))
     {
         nError = Marshal.GetLastWin32Error();
         Win32Exception we = new Win32Exception(nError);
         if (nError == nErrorAccessDenied)
         {
             throw new AuthException(we);
         }
         else
         {
             throw we;
         }
     }
     
     // iterate through the retrieved entries, copying printer entries
     // to the output table
     IntPtr pCur = pPrinterEnum;
     for (int i = 0; i < cReturned; i++)
     {
         // marshal the entry into
         PRINTER_INFO_2 pi2 = new PRINTER_INFO_2();
         Marshal.PtrToStructure(pCur, pi2);
         
         // trim off server name
         string sName = Marshal.PtrToStringUni(pi2.pPrinterName);
         if (sName.StartsWith(@"\\"))
         {
             // yep, trim off prefix
             int ibackwhack = sName.LastIndexOf(@"\");
             sName = sName.Substring(ibackwhack + 1);
         }
         
         string[] printInfo ={ Marshal.PtrToStringUni(pi2.pShareName), Marshal.PtrToStringUni(pi2.pDriverName), pi2.cJobs.ToString(), Marshal.PtrToStringUni(pi2.pComment) };
         
         // advance to the next entry
         pCur = (IntPtr)((int)pCur + Marshal.SizeOf(pi2));
         
         printInfoList.Add(i, printInfo);
     }
     
     // free the mem
     Marshal.FreeHGlobal(pPrinterEnum);
     
     return printInfoList;
 }
Exemplo n.º 35
0
        /// <summary>
        /// Method to create the Folder in Sysvol for created GPO object with the corresponding guid ID
        /// </summary>
        /// <param name="sGuid"></param>
        /// <returns></returns>
        private bool CreateGPOFolderInSysVol(string sGuid, string displayname)
        {
            Logger.Log("CreateGPOFolderInSysVol", Logger.GPMCLogLevel);

            if (Configurations.currentPlatform == LikewiseTargetPlatform.UnixOrLinux ||
            Configurations.currentPlatform == LikewiseTargetPlatform.Darwin)
            {

                try
                {
                    string sTempPath = Configurations.tempDirectory;
                    string sDomainPath = Path.Combine(sTempPath, dirContext.DomainName.ToLower());
                    string sLocalMountPath = Path.Combine(sDomainPath, @"sysvol");
                    sLocalMountPath = Path.Combine(sLocalMountPath, "policies");

                    //Replace the '\' with the '\\'
                    if (sLocalMountPath.IndexOf(@"\") >= 0)
                        sLocalMountPath = sLocalMountPath.Replace(@"\", @"\\");

                    if (!Directory.Exists(sLocalMountPath))
                    {
                        Configurations.MakeDirectoryRecursive(sLocalMountPath);
                    }

                    //create the Folder with the Guid given to the Group Policy Object
                    string sGPOSysVolPath = Path.Combine(sLocalMountPath, "{" + sGuid + "}");

                    if (!Directory.Exists(sGPOSysVolPath))
                    {
                        try
                        {
                            string sMachinepath = Path.Combine(sGPOSysVolPath, "Machine");
                            string sUserPath = Path.Combine(sGPOSysVolPath, "User");
                            string sGPOGPTPath = Path.Combine(sGPOSysVolPath, "GPT.INI");

                            Configurations.MakeDirectoryRecursive(sGPOSysVolPath);
                            Configurations.MakeDirectoryRecursive(sMachinepath);
                            Configurations.MakeDirectoryRecursive(sUserPath);

                            if (!File.Exists(sGPOGPTPath))
                            {
                                string sTePath = Path.Combine(System.IO.Path.GetTempPath(), "GPT.INI");

                                FileStream fStream = new FileStream(sTePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                                StreamWriter writer = new StreamWriter(fStream);

                                writer.WriteLine("[General]");
                                writer.WriteLine("Version=0");
                                writer.WriteLine(string.Format("displayName={0}", displayname));

                                writer.Flush();
                                writer.Close();
                                fStream.Close();

                                File.Move(sTePath, sGPOGPTPath.Replace(@"\\", @"\"));
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogException("objectsListPage:CreateGPOFolderInSysVol", ex);
                        }
                    }

                    sLocalMountPath = sGPOSysVolPath;

                    //Make the remote path to access the SysVol from the Server
                    string sRemoteMountPath = String.Format(@"//{0}/sysvol", dirContext.DomainControllerName);
                    sRemoteMountPath = String.Concat(sRemoteMountPath, "/", dirContext.DomainName, @"/policies");

                    CredentialEntry creds = new CredentialEntry(
                    dirContext.UserName,
                    dirContext.Password,
                    dirContext.DomainName);

                    //string changeDirectoryPath = String.Format(@"{0}\\Policies", dirContext.DomainName);
                    //SMBClient sysVolHandle = new SMBClient(creds, sLocalMountPath, sRemoteMountPath, changeDirectoryPath);
                    LwioCopy sysVolHandle = new LwioCopy(creds, sLocalMountPath, sRemoteMountPath);

                    sysVolHandle.UploadFile("{" + sGuid + "}");
                }
                catch (Exception ex)
                {
                    Logger.LogException("objectsListPage:CreateGPOFolderInSysVol", ex);
                }
            }

            return true;
        }
        /// <summary>
        /// Method to load data to the tab pages while loading
        /// Gets all the tab pages that are of type MPage and gets call the SetData()
        /// Queries the ldap message to the selected node
        /// </summary>
        /// <param name="ce"></param>
        /// <param name="servername"></param>
        /// <param name="computer"></param>
        /// <param name="dirnode"></param>
        /// <param name="ldapSchemaCache"></param>
        public void SetData(CredentialEntry ce, string servername, string sOU, ADUCDirectoryNode dirnode, LDAPSchemaCache ldapSchemaCache)
        {
            Applied = false;
            _plugin = dirnode.Plugin as ADUCPlugin;

            objInfo = new ObjectPropertyInfo
                                     (ce,
                                     servername,
                                     sOU,
                                     dirnode,
                                     null);

            threadMain = new Thread(new ThreadStart(AddPagesToThread));
            threadMain.Start();
        }