Beispiel #1
0
        /// <summary>
        /// Creates command based on the commanf info, reading the calues from attributes
        /// </summary>
        /// <param name="cmdInfo">Command defition</param>
        /// <param name="attributes">Attribute values</param>
        /// <param name="config">Configuration object</param>
        /// <returns>
        /// Ready to execute Command
        /// </returns>
        /// <exception cref="ArgumentNullException">if some of the param is null</exception>
        internal static Command GetCommand(PSExchangeConnector.CommandInfo cmdInfo, ICollection <ConnectorAttribute> attributes, ExchangeConfiguration config)
        {
            Assertions.NullCheck(cmdInfo, "cmdInfo");
            Assertions.NullCheck(attributes, "attributes");

            // create command
            Command cmd = new Command(cmdInfo.Name);

            // map name attribute, if mapping specified
            if (!string.IsNullOrEmpty(cmdInfo.NameParameter))
            {
                object val = GetAttValue(Name.NAME, attributes);
                if (val != null)
                {
                    cmd.Parameters.Add(cmdInfo.NameParameter, val);
                }
            }

            foreach (string attName in cmdInfo.Parameters)
            {
                object val = GetAttValue(attName, attributes);
                if (val == null && attName.Equals("DomainController"))
                {
                    // add domain controller if not provided
                    val = ActiveDirectoryUtils.GetDomainControllerName(config);
                }

                if (val != null)
                {
                    cmd.Parameters.Add(attName, val);
                }
            }

            return(cmd);
        }
Beispiel #2
0
        public override DirectoryEntry NewItem(DirectoryEntry parent, string name)
        {
            DirectoryEntry entry = base.NewItem(parent, name);

            string domainName = ActiveDirectoryUtils.GetDomainDnsName(parent);

            entry.Properties["sAMAccountName"].Value    = name;
            entry.Properties["userPrincipalName"].Value = name + '@' + domainName;

            return(entry);
        }
        private void LoadSpaceData(PackageInfo packageInfo)
        {
            int              serviceId       = PackageController.GetPackageServiceId(packageInfo.PackageId, ResourceGroups.HostedOrganizations);
            ServiceInfo      serviceInfo     = ServerController.GetServiceInfo(serviceId);
            StringDictionary serviceSettings = ServerController.GetServiceSettingsAdmin(serviceId);

            Global.RootOU = serviceSettings["RootOU"];
            Global.PrimaryDomainController = serviceSettings["PrimaryDomainController"];
            Global.TempDomain = serviceSettings["TempDomain"];
            ServerInfo serverInfo = ServerController.GetServerById(serviceInfo.ServerId);

            Global.ADRootDomain  = serverInfo.ADRootDomain;
            Global.NetBiosDomain = ActiveDirectoryUtils.GetNETBIOSDomainName(Global.ADRootDomain);
        }
Beispiel #4
0
 private static string ExtractCommonName(string distinguishedName)
 {
     return(ActiveDirectoryUtils.GetCnValueUnescaped(distinguishedName));
 }
Beispiel #5
0
        /// <summary>
        /// Creates command based on the commanf info, reading the calues from attributes
        /// </summary>
        /// <param name="cmdInfo">Command defition</param>
        /// <param name="attributes">Attribute values - UID in these is ignored! It should be passed as a separate parameter</param>
        /// <param name="config">Configuration object</param>
        /// <returns>
        /// Ready to execute Command
        /// </returns>
        /// <exception cref="ArgumentNullException">if some of the param is null</exception>
        internal static Command GetCommand(PSExchangeConnector.CommandInfo cmdInfo, ICollection <ConnectorAttribute> attributes, Uid uidAttribute, Name nameAttribute, ExchangeConfiguration config)
        {
            Assertions.NullCheck(cmdInfo, "cmdInfo");

            LOG.Trace("GetCommand: cmdInfo name = {0}", cmdInfo.Name);

            ISet <string> parametersSet = new HashSet <string>();

            // create command
            Command cmd = new Command(cmdInfo.Name);

            if (!string.IsNullOrEmpty(cmdInfo.UidParameter) && !parametersSet.Contains(cmdInfo.UidParameter))
            {
                Uid    uidAttr = uidAttribute != null ? uidAttribute : ConnectorAttributeUtil.GetUidAttribute(attributes);
                string uid     = uidAttr != null?uidAttr.GetUidValue() : null;

                if (uid != null)
                {
                    cmd.Parameters.Add(cmdInfo.UidParameter, ActiveDirectoryUtils.ConvertADGUIDtoObjectGUID(uid));
                    parametersSet.Add(cmdInfo.UidParameter);
                }
            }

            // map name attribute, if mapping specified
            if (!string.IsNullOrEmpty(cmdInfo.NameParameter) && !parametersSet.Contains(cmdInfo.NameParameter))
            {
                Name   nameAttr = nameAttribute != null ? nameAttribute : ConnectorAttributeUtil.GetNameFromAttributes(attributes);
                string name     = nameAttr != null?nameAttr.GetNameValue() : null;;
                if (name != null)
                {
                    cmd.Parameters.Add(cmdInfo.NameParameter, name);
                    parametersSet.Add(cmdInfo.NameParameter);
                }
            }

            if (cmdInfo.UsesConfirm)
            {
                cmd.Parameters.Add("confirm", false);
                parametersSet.Add("confirm");
            }

            if (cmdInfo.UsesDomainController)
            {
                cmd.Parameters.Add("DomainController", ActiveDirectoryUtils.GetDomainControllerName(config));
                parametersSet.Add("DomainController");
            }

            // TODO check this only for user-related operations
            bool emailAddressesPresent     = GetAttValues(ExchangeConnectorAttributes.AttEmailAddresses, attributes) != null;
            bool primarySmtpAddressPresent = GetAttValues(ExchangeConnectorAttributes.AttPrimarySmtpAddress, attributes) != null;

            if (emailAddressesPresent && primarySmtpAddressPresent)
            {
                throw new ArgumentException(ExchangeConnectorAttributes.AttEmailAddresses + " and " + ExchangeConnectorAttributes.AttPrimarySmtpAddress + " cannot be both set.");
            }

            if (attributes != null)
            {
                foreach (string attName in cmdInfo.Parameters)
                {
                    object valueToSet = null;

                    ConnectorAttribute attribute = ConnectorAttributeUtil.Find(attName, attributes);
                    if (attribute != null)
                    {
                        if (attribute.Value != null && attribute.Value.Count > 1)
                        {
                            List <string> stringValues = new List <string>();
                            foreach (object val in attribute.Value)
                            {
                                stringValues.Add(val.ToString());
                            }
                            valueToSet = stringValues.ToArray();
                        }
                        else
                        {
                            valueToSet = ConnectorAttributeUtil.GetSingleValue(attribute);
                        }
                        if (parametersSet.Contains(attName))
                        {
                            throw new InvalidOperationException("Parameter " + attName + " is already defined for command " + cmdInfo.Name);
                        }
                        cmd.Parameters.Add(attName, valueToSet);
                        parametersSet.Add(attName);
                    }
                }
            }

            LOG.Trace("GetCommand exit: cmdInfo name = {0}", cmdInfo.Name);
            return(cmd);
        }
        /// <summary>
        /// Returns fully qualified netbios account name.
        /// </summary>
        /// <param name="accountName">Account name.</param>
        /// <returns>Fully qualified netbios account name.</returns>
        private string AttachNetbiosDomainName(string accountName)
        {
            string domainNetbiosName = String.Format("{0}\\", ActiveDirectoryUtils.GetNETBIOSDomainName(ServerSettings.ADRootDomain));

            return(String.Format("{0}{1}", domainNetbiosName, accountName.Replace(domainNetbiosName, String.Empty)));
        }
        private void AddOrReplaceDatabase(ObjectClass oclass, Uid uid, ICollection <ConnectorAttribute> attributes, OperationOptions options, AbstractConfiguration connectorConfiguration)
        {
            if (!ObjectClass.ACCOUNT.Equals(oclass))
            {
                LOG.Info("Nothing to do");
                return;
            }
            // вычисляем значение атрибута Database только если он не был передан
            // и дополнительно пришёл атрибут RecipientType со значением UserMailbox
            ConnectorAttribute database      = GetAttribute(attributes, "Database");
            ConnectorAttribute recipientType = GetAttribute(attributes, "RecipientType");

            if (database != null || recipientType == null || !recipientType.Value.First().ToString().Equals("UserMailbox"))
            {
                LOG.Info("Nothing to do");
                return;
            }

            DirectoryEntry container = null;

            try
            {
                ActiveDirectoryConfiguration config = (ActiveDirectoryConfiguration)connectorConfiguration;

                // вычисляем dn, для update'а находим по uid
                string dn = "";
                if (uid != null)
                {
                    DirectoryEntry entry = new DirectoryEntry(ActiveDirectoryUtils.GetLDAPPath(config.LDAPHostName, uid.GetUidValue()), config.DirectoryAdminName, config.DirectoryAdminPassword);
                    dn = (string)entry.Properties["distinguishedName"][0];
                    entry.Dispose();
                }
                else
                {
                    dn = GetAttribute(attributes, "__NAME__").Value.First().ToString();
                }
                string parentDn          = ActiveDirectoryUtils.GetParentDn(dn);
                string ldapContainerPath = ActiveDirectoryUtils.GetLDAPPath(config.LDAPHostName, parentDn);

                container = new DirectoryEntry(ldapContainerPath, config.DirectoryAdminName, config.DirectoryAdminPassword);

                // поиск значения Database в родительских OU
                string defaultHomeMdb = null;
                while (defaultHomeMdb == null && container != null)
                {
                    LOG.Info("Looking for DefaultHomeMdb in {0}", container.Path);
                    defaultHomeMdb = GetDefaultHomeMdb(container);
                    if (defaultHomeMdb != null)
                    {
                        LOG.Info("Found! DefaultHomeMdb = {0} (in container {1})", defaultHomeMdb, container.Path);
                    }
                    else
                    {
                        LOG.Info("Did not found DefaultHomeMdb in container {0}", container.Path);
                    }
                    try
                    {
                        container = container.Parent;
                    }
                    catch (Exception e)
                    {
                        LOG.Info("Error: " + e.Message);
                        container = null;
                    }
                }

                // установка значения атрибута, если не нашли указываем значение по умолчанию
                if (defaultHomeMdb != null)
                {
                    LOG.Info("Setting DefaultHomeMdb: " + defaultHomeMdb);
                    AddOrReplaceAttribute(attributes, "Database", defaultHomeMdb);
                }
                else
                {
                    LOG.Info("Did not found DefaultHomeMdb, will set default value");
                    AddOrReplaceAttribute(attributes, "Database", "MSK-RN-DAG01-1GB-02");
                }
            }
            finally
            {
                if (container != null)
                {
                    container.Dispose();
                }
            }
        }
Beispiel #8
0
        public void Update(UpdateOpContext context)
        {
            ExchangeConnector        exconn = (ExchangeConnector)context.Connector;
            ActiveDirectoryConnector adconn = exconn.ActiveDirectoryConnector;

            // update in AD first
            var filtered = ExchangeUtility.FilterOut(
                context.Attributes,
                PSExchangeConnector.CommandInfo.EnableMailbox,
                PSExchangeConnector.CommandInfo.EnableMailUser,
                PSExchangeConnector.CommandInfo.SetMailbox,
                PSExchangeConnector.CommandInfo.SetMailUser);

            adconn.Update(context.UpdateType, context.ObjectClass, context.Uid, filtered, context.Options);

            // retrieve Exchange-related information about the user
            string          query         = "(objectGUID=" + ActiveDirectoryUtils.ConvertUIDToSearchString(context.Uid) + ")";
            ConnectorObject currentObject = _helper.GetCurrentObject(context, query);
            ICollection <ConnectorAttribute> attributesForReplace = _helper.DetermineNewAttributeValues(context, currentObject);

            attributesForReplace = DeduplicateEmailAddresses(context, attributesForReplace);

            string origRcptType;
            var    newRcptType = _helper.DetermineOrigAndNewAttributeValue(context, currentObject, attributesForReplace, ExchangeConnectorAttributes.AttRecipientType, out origRcptType);

            if (newRcptType == null)
            {
                newRcptType = ExchangeConnectorAttributes.RcptTypeUser;
            }

            string origDatabase;
            var    newDatabase = _helper.DetermineOrigAndNewAttributeValue(context, currentObject, attributesForReplace, ExchangeConnectorAttributes.AttDatabase, out origDatabase);

            // PART 1 - DEALING WITH MailUser CASE

            if (ExchangeConnectorAttributes.RcptTypeMailUser.Equals(newRcptType))
            {
                // disabling Mailbox if needed
                if (ExchangeConnectorAttributes.RcptTypeMailBox.Equals(origRcptType))
                {
                    Command cmdDisable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.DisableMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                    cmdDisable.Parameters.Add("Confirm", false);
                    _helper.InvokePipeline(exconn, cmdDisable);
                }

                // enabling MailUser if needed
                if (!ExchangeConnectorAttributes.RcptTypeMailUser.Equals(origRcptType))
                {
                    // Enable-MailUser needs the value of ExternalEmailAddress, so we have to get it
                    string origExternalEmailAddress;
                    var    newExternalEmailAddress = _helper.DetermineOrigAndNewAttributeValue(context, currentObject, attributesForReplace, ExchangeConnectorAttributes.AttExternalEmailAddress, out origExternalEmailAddress);

                    if (String.IsNullOrEmpty(newExternalEmailAddress))
                    {
                        throw new InvalidOperationException("Missing ExternalEmailAddress value, which is required for a MailUser");
                    }
                    ExchangeUtility.SetAttValue(ExchangeConnectorAttributes.AttExternalEmailAddress, newExternalEmailAddress, attributesForReplace);

                    // now execute the Enable-MailUser command
                    Command cmdEnable = ExchangeUtility.GetCommand(
                        PSExchangeConnector.CommandInfo.EnableMailUser, attributesForReplace, context.Uid, exconn.Configuration);
                    _helper.InvokePipeline(exconn, cmdEnable);
                }

                // setting MailUser attributes
                Command cmdSet = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.SetMailUser, attributesForReplace, context.Uid, exconn.Configuration);
                _helper.InvokePipeline(exconn, cmdSet);
            }

            // PART 2 - DEALING WITH UserMailbox CASE

            else if (ExchangeConnectorAttributes.RcptTypeMailBox.Equals(newRcptType))
            {
                // enable mailbox if necessary

                // we should execute something like this here:
                // get-user -identity id|?{$_.RecipientType -eq "User"}|enable-mailbox -database "db"
                // unfortunately I was not able to get it working with the pipeline... that's why there are two commands
                // executed :-(
                // alternatively there can be something like:
                // get-user -identity id -RecipientTypeDetails User|enable-mailbox -database "db", but we have then trouble
                // with detecting attempt to change the database attribute
                if (!ExchangeConnectorAttributes.RcptTypeMailBox.Equals(origRcptType))
                {
                    Command cmdEnable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.EnableMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                    _helper.InvokePipeline(exconn, cmdEnable);
                }
                else
                {
                    // are we trying to update the database?
                    if (newDatabase != null && origDatabase != null && !newDatabase.Equals(origDatabase))
                    {
                        throw new ArgumentException(
                                  context.ConnectorConfiguration.ConnectorMessages.Format(
                                      "ex_not_updatable", "Update of [{0}] attribute is not supported", ExchangeConnectorAttributes.AttDatabase));
                    }
                }

                Command cmdSet = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.SetMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                _helper.InvokePipeline(exconn, cmdSet);
            }

            // PART 3 - DEALING WITH User CASE

            else if (ExchangeConnectorAttributes.RcptTypeUser.Equals(newRcptType))
            {
                if (ExchangeConnectorAttributes.RcptTypeMailBox.Equals(origRcptType))
                {
                    Command cmdDisable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.DisableMailbox, attributesForReplace, context.Uid, exconn.Configuration);
                    cmdDisable.Parameters.Add("Confirm", false);
                    _helper.InvokePipeline(exconn, cmdDisable);
                }
                else if (ExchangeConnectorAttributes.RcptTypeMailUser.Equals(origRcptType))
                {
                    Command cmdDisable = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.DisableMailUser, attributesForReplace, context.Uid, exconn.Configuration);
                    cmdDisable.Parameters.Add("Confirm", false);
                    _helper.InvokePipeline(exconn, cmdDisable);
                }
                else if (ExchangeConnectorAttributes.RcptTypeUser.Equals(origRcptType))
                {
                    // if orig is User, there is no need to disable anything
                }
                else
                {
                    throw new InvalidOperationException("Invalid original recipient type: " + origRcptType);
                }

                Command cmdSet = ExchangeUtility.GetCommand(PSExchangeConnector.CommandInfo.SetUser, attributesForReplace, context.Uid, exconn.Configuration);
                _helper.InvokePipeline(exconn, cmdSet);
            }
            else
            {
                // unsupported rcpt type
                throw new ArgumentException(
                          context.ConnectorConfiguration.ConnectorMessages.Format(
                              "ex_bad_rcpt", "Recipient type [{0}] is not supported", newRcptType));
            }
        }