示例#1
0
 public LdapSaveSyncOperation(LdapSettings settings, Tenant tenant, LdapOperationType operation, LdapLocalization resource = null)
     : base(settings, tenant, operation, resource)
 {
     _ldapChanges = new LdapChangeCollection {
         Tenant = tenant
     };
 }
        public LdapSettings GetLdapSettings()
        {
            CheckLdapPermissions();

            var settings = LdapSettings.Load();

            settings = settings.Clone() as LdapSettings; // clone LdapSettings object for clear password (potencial AscCache.Memory issue)

            if (settings == null)
            {
                return(new LdapSettings().GetDefault() as LdapSettings);
            }

            settings.Password      = null;
            settings.PasswordBytes = null;

            if (settings.IsDefault)
            {
                return(settings);
            }

            var defaultSettings = settings.GetDefault();

            if (settings.Equals(defaultSettings))
            {
                settings.IsDefault = true;
            }

            return(settings);
        }
示例#3
0
        public async Task SetLdapSettingsAsync(LdapSettings ldapSettings)
        {
            if (ldapSettings == null)
            {
                throw new ArgumentNullException(nameof(LdapSettings));
            }

            ldapSettings.Password = _dataProtectionService.Encrypt(ldapSettings.Password);

            var json = JsonConvert.SerializeObject(ldapSettings);

            var appSettings = await _appSettingsRepository.GetByIdAsync(ServerConstants.Domain);

            if (appSettings == null)
            {
                appSettings = new AppSettings()
                {
                    Id    = ServerConstants.Domain,
                    Value = json
                };
                await _appSettingsRepository.AddAsync(appSettings);
            }
            else
            {
                appSettings.Value = json;
                await _appSettingsRepository.UpdateAsync(appSettings);
            }
        }
 public WindowsStreamSecurityUpgradeAcceptor(WindowsStreamSecurityUpgradeProvider parent)
     : base(FramingUpgradeString.Negotiate)
 {
     _parent         = parent;
     _clientSecurity = new SecurityMessageProperty();
     _ldapSettings   = parent.LdapSettings;
 }
示例#5
0
        public AdDirectoryService(LdapSettings settings, AdOptions adOptions)
        {
            // TODO NTBS-1672 run a DNS query that does the foollwing:
            // dig +short -t srv _ldap._tcp.SP4-0JG._sites.dc._msdcs.phe.gov.uk
            // dig +short -t srv _ldap._tcp.dc._msdcs.caduceus.local
            // and pick a dc to request
            _settings   = settings;
            _adOptions  = adOptions;
            _connection = new LdapConnection();
            Log.Information($"Connecting to AD: {settings.AdAddressName}:{settings.Port}");
            _connection.Connect(settings.AdAddressName, settings.Port);
            var withOrWithout = string.IsNullOrEmpty(settings.Password) ? "without" : "with";

            Log.Information($"Binding: {settings.UserIdentifier} {withOrWithout} a password");
            _connection.Bind(GetDistinguishedName(settings.UserIdentifier), settings.Password);
            if (_connection.Bound)
            {
                Log.Information("Bind completed");
            }
            else
            {
                var bindingException = new ApplicationException("Binding to LDAP failed");
                Log.Error(bindingException, "Aborting LDAP connection");
                throw bindingException;
            }
        }
示例#6
0
        private bool UserExistsInLdapDirectory(LdapSettings ldapSettings, LoginInfo loginInfo)
        {
            var userName = loginInfo.UserName != null?loginInfo.UserName.Trim() : loginInfo.Login;

            var filter = I18NHelper.FormatInvariant("(&(objectCategory={0})({1}={2}))", ldapSettings.GetEffectiveUserObjectCategoryAttribute(), ldapSettings.GetEffectiveAccountNameAttribute(), LdapHelper.EscapeLdapSearchFilter(userName));

            try
            {
                var found = _authenticator.SearchLdap(ldapSettings, filter);

                if (found)
                {
                    return(true);
                }

                _log.LogInformation(LogSourceLdap, I18NHelper.FormatInvariant("User '{0}' is not found in LDAP directory {1}", userName, ldapSettings.LdapAuthenticationUrl));

                return(false);
            }
            catch (Exception ex)
            {
                _log.LogInformation(LogSourceLdap, I18NHelper.FormatInvariant("Error while searching a user in LDAP directory {0}", ldapSettings.LdapAuthenticationUrl));
                _log.LogError(LogSourceLdap, ex);

                return(false);
            }
        }
示例#7
0
 public GroupSidClaimCollection(ClaimsIdentity claimsIdentity, LdapSettings ldapSettings)
 {
     if (claimsIdentity is WindowsIdentity)
     {
         var windowsIdentity = (WindowsIdentity)claimsIdentity;
         if (windowsIdentity.Token != IntPtr.Zero)
         {
             foreach (var groupId in windowsIdentity.Groups)
             {
                 var      group        = groupId.Translate(typeof(NTAccount));
                 string[] domainGroups = group.Value.Split(new char[] { '\\' });
                 if (domainGroups.Length > 1)
                 {
                     base.Add(new Claim(ClaimTypes.Role, domainGroups[1], Rights.Identity));
                 }
                 else
                 {
                     base.Add(new Claim(ClaimTypes.Role, group, Rights.Identity));
                 }
             }
         }
     }
     else if (ldapSettings != null)
     {
         List <Claim> allClaims = LdapAdapter.RetrieveClaimsAsync(ldapSettings, claimsIdentity.Name).GetAwaiter().GetResult();
         foreach (Claim roleClaim in allClaims)
         {
             base.Add(roleClaim);
         }
     }
 }
        public static void RegisterAll()
        {
            var task = new Task(() =>
            {
                var tenants = CoreContext.TenantManager.GetTenants();
                foreach (var t in tenants)
                {
                    var tId = t.TenantId;

                    var cronSettings = LdapCronSettings.LoadForTenant(tId);

                    if (string.IsNullOrEmpty(cronSettings.Cron))
                    {
                        continue;
                    }

                    if (LdapSettings.LoadForTenant(tId).EnableLdapAuthentication)
                    {
                        RegisterAutoSync(t, cronSettings.Cron);
                    }
                    else
                    {
                        cronSettings.Cron = null;
                        cronSettings.Save();
                    }
                }
            }, TaskCreationOptions.LongRunning);

            task.Start();
        }
        private LdapProviderService GetLdapProviderSerivce(LdapSettings settings, PolicyProvider policyProvider)
        {
            var logger = new Mock <ILogger>().Object;
            var ldapConnectionProvider = new LdapConnectionProvider(settings, logger);

            return(new LdapProviderService(ldapConnectionProvider, logger, policyProvider));
        }
示例#10
0
        static X509Certificate2 Ldap(CertificateSubject certSubject)
        {
            LdapSettings settings = ConfigurationHandler.GetConfigurationSection <LdapSettings>();

            // Print out info
            Console.WriteLine();
            Console.WriteLine("2. Certificate download");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine(" Using host");
            Console.WriteLine("  " + settings.Host);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();


            // Create the LDAP client
            LdapLookupFactory  ldapClientFactory = new LdapLookupFactory();
            ICertificateLookup ldapClient        = ldapClientFactory.CreateLdapLookupClient();

            // Lookup the certificate using LDAP
            X509Certificate2 certificate = ldapClient.GetCertificate(certSubject);

            Console.WriteLine(" Downloaded certificate with LDAP:");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("  " + certificate.Subject);
            Console.ForegroundColor = ConsoleColor.White;

            return(certificate);
        }
 public AdDirectoryServiceFactory(
     IOptions <LdapSettings> LdapSettings,
     IOptions <AdOptions> adfsOptions)
 {
     _ldapSettings = LdapSettings.Value;
     _adOptions    = adfsOptions.Value;
 }
示例#12
0
        /// <summary>
        /// Initializes an instance of this object.
        /// </summary>
        public User()
        {
            store = Store.GetStore();
            if (store.DefaultDomain == null)
            {
                throw new SimiasException(User.missingDomainMessage);
            }

            // Is the default domain always the correct domain?
            domain = store.GetDomain(store.DefaultDomain);
            if (domain == null)
            {
                throw new SimiasException(User.missingDomainMessage);
            }

            if (domain.IsType("Enterprise") == false)
            {
                throw new SimiasException(User.missingDomainMessage);
            }

            ldapSettings = LdapSettings.Get(Store.StorePath);


            // Make sure the password is set on the admin
            SetAdminPassword();
        }
示例#13
0
 /// <summary>
 /// Trys to get the provided attribues on the first found user entry
 /// </summary>
 /// <param name="ldapConfig">LDAP configuration</param>
 public bool TestUserAttributes(LdapSettings ldapConfig)
 {
     using DirectoryEntry entry = Connect($"{GetLdapStr(ldapConfig)}/{ldapConfig.LdapUserDN},{ldapConfig.LdapBaseDN}");
     return(TestAttributes(entry, ldapConfig.LdapUserFilter,
                           ldapConfig.LdapUserGuidAttr,
                           ldapConfig.LdapUserNameAttr,
                           ldapConfig.LdapUserEmailAttr));
 }
        public void ChangeHostBehavior(ServiceHostBase host)
        {
            var          srvCredentials = new CoreWCF.Description.ServiceCredentials();
            LdapSettings _ldapSettings  = new LdapSettings("yourownserver.mscore.local", "mscore.local", "yourowntoporg");

            srvCredentials.WindowsAuthentication.LdapSetting = _ldapSettings;
            host.Description.Behaviors.Add(srvCredentials);
        }
示例#15
0
 public LdapSaveSyncOperation(LdapSettings settings, Tenant tenant, LdapOperationType operation, LdapLocalization resource = null, string userId = null)
     : base(settings, tenant, operation, resource)
 {
     _ldapChanges = new LdapChangeCollection {
         Tenant = tenant
     };
     _currentUser = userId != null?CoreContext.UserManager.GetUsers(Guid.Parse(userId)) : null;
 }
示例#16
0
 protected override void OnInitialized()
 {
     AppSettingsService = ScopedServices.GetRequiredService <IAppSettingsService>();
     LdapSettings       = new LdapSettings()
     {
         Host = Host
     };
 }
示例#17
0
 public UserService(IOptions <EnvironmentSettings> environmentSettings, UserManager <User> userManager,
                    SignInManager <User> signInManager, IOptions <LdapSettings> ldapSettings, IStudentService studentService)
 {
     _environmentSettings = environmentSettings.Value;
     _userManager         = userManager;
     _signInManager       = signInManager;
     _ldapSettings        = ldapSettings.Value;
     _studentService      = studentService;
 }
示例#18
0
 /// <summary>
 /// Creates a new <see cref="LdapContext"/>.
 /// </summary>
 /// <inheritdoc />
 public LdapContext(
     HttpContext context,
     AuthenticationScheme scheme,
     NegotiateOptions options,
     LdapSettings settings)
     : base(context, scheme, options)
 {
     LdapSettings = settings;
 }
        static TestUtils()
        {
            settings = System.Configuration.ConfigurationSettings.GetConfig("LdapSettings") as LdapSettings;

            if (settings == null)
            {
                throw new InvalidOperationException("Invalid Configuration Specified");
            }
        }
    public void EnabledWithoutDomainThrows()
    {
        var settings = new LdapSettings
        {
            EnableLdapClaimResolution = true
        };

        Assert.Throws <ArgumentException>(() => settings.Validate());
    }
示例#21
0
 public ActiveDirectoryAuthProvider(
     ILogger <ActiveDirectoryAuthProvider> logger,
     LdapSettings ldapSettings,
     ILdapAuthRepository ldapAuthRepo)
 {
     _logger       = logger;
     _ldapSettings = ldapSettings;
     _ldapRepo     = ldapAuthRepo;
 }
示例#22
0
        private void ProcessSearchObjects(LdapConnection conn, LdapSettings settings)
        {
            foreach (string searchContext in settings.SearchContexts)
            {
                string[] searchAttributes = { "objectClass" };

                log.Debug("SearchObject: " + searchContext);

                try
                {
                    LdapEntry     ldapEntry       = conn.Read(searchContext, searchAttributes);
                    LdapAttribute attrObjectClass = ldapEntry.getAttribute("objectClass");
                    String[]      values          = attrObjectClass.StringValueArray;

                    if (IsUser(values) == true)
                    {
                        // Process SearchDN as
                        log.Debug("Processing User Object...");
                        ProcessSearchUser(conn, searchContext, "", "");
                    }
                    else if (IsGroup(values) == true)
                    {
                        // Process SearchDN as
                        log.Debug("Processing Group Object...");
                        //ProcessSearchGroup( conn, searchContext );
                        ProcessSearchContainer(conn, searchContext);
                    }
                    else if (IsContainer(values) == true)
                    {
                        // Process SearchDN as Container
                        log.Debug("Processing Container Object...");
                        ProcessSearchContainer(conn, searchContext);
                    }
                    else
                    {
                        log.Debug("Invalid objectClass: " + values[0]);
                        log.Debug(attrObjectClass.ToString());
                    }
                }
                catch (SimiasShutdownException s)
                {
                    log.Error(s.Message);
                    throw s;
                }
                catch (LdapException e)
                {
                    log.Error(e.LdapErrorMessage);
                    log.Error(e.StackTrace);
                }
                catch (Exception e)
                {
                    log.Error(e.Message);
                    log.Error(e.StackTrace);
                }
            }
        }
        public ActiveDirectoryAccountServiceTest()
        {
            var settings = new LdapSettings();

            settings.ServerName = "dir.company.com";
            settings.SearchBase = "o=company,c=an";
            //settings.Credentials.DomainUserName = "******";
            //settings.Credentials.Password = "";
            service = new ActiveDirectoryAccountService(settings);
        }
    public void AccountPasswordWithoutAccountNameThrows()
    {
        var settings = new LdapSettings
        {
            EnableLdapClaimResolution = true,
            MachineAccountPassword    = "******"
        };

        Assert.Throws <ArgumentException>(() => settings.Validate());
    }
示例#25
0
 internal WindowsClaimSet(ClaimsIdentity claimsIdentity, string authenticationType, bool includeWindowsGroups, DateTime expirationTime, bool clone, IList <Claim> _fromClaims, LdapSettings ldapSettings)
     : this(authenticationType, includeWindowsGroups, expirationTime, clone, _fromClaims)
 {
     if (claimsIdentity == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(claimsIdentity));
     }
     _windowsIdentity = (clone && claimsIdentity is WindowsIdentity) ? SecurityUtils.CloneWindowsIdentityIfNecessary((WindowsIdentity)claimsIdentity, authenticationType) : claimsIdentity;
     _ldapSettings    = ldapSettings;
 }
示例#26
0
        public NovellLdapHelper(LdapSettings settings) :
            base(settings)
        {
            var password = string.IsNullOrEmpty(settings.Password)
                ? GetPassword(settings.PasswordBytes)
                : settings.Password;

            LDAPSearcher = new NovellLdapSearcher(settings.Login, password, settings.Server, settings.PortNumber,
                                                  settings.StartTls, settings.Ssl, settings.AcceptCertificate, settings.AcceptCertificateHash);
        }
示例#27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ldapConfig"></param>
        /// <param name="appConfig"></param>
        public UserManager(IOptions <LdapSettings> ldapConfig, IOptions <AppSettings> appConfig)
        {
            _ldapconfig = ldapConfig.Value;
            _appConfig  = appConfig.Value;

            _connection = new LdapConnection
            {
                SecureSocketLayer = true
            };
        }
        public async Task <IActionResult> TestLDAPAsync([FromForm] LdapSettings ldapConfig)
        {
            // Check authorization
            if (!(await User.IsAdminAsync(_authorizationService)))
            {
                return(Unauthorized());
            }

            _logger.LogDebug("Testing LDAP for config: {0}", ldapConfig);

            int userCount  = 0;
            int groupCount = 0;

            try
            {
                // Combine host, port and protocol to a single string
                string ldapStr = _ldapService.GetLdapStr(ldapConfig);

                // Try to connect
                if (!_ldapService.TestConnection(ldapStr))
                {
                    _logger.LogWarning("LDAP connection test failed");
                    return(Ok(new FailureResponse("Connection test failed: Check hostname and credientials")));
                }

                // Count entries
                userCount  = _ldapService.GetUserCount(ldapConfig);
                groupCount = _ldapService.GetGroupCount(ldapConfig);

                // Test user attributes
                if (userCount > 0 &&
                    !_ldapService.TestUserAttributes(ldapConfig))
                {
                    _logger.LogWarning("User attribute test failed");
                    return(Ok(new FailureResponse("User attributes not found")));
                }

                // Test group attributes
                if (groupCount > 0 &&
                    !_ldapService.TestGroupAttrbutes(ldapConfig))
                {
                    _logger.LogWarning("Group attribute test failed");
                    return(Ok(new FailureResponse("Group attributes not found")));
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "Error while LDAP test");
                return(Ok(new ErrorRespose(e)));
            }

            // Return success message
            _logger.LogDebug("LDAP test successfull. Found {0} users and {1} groups.", userCount, groupCount);
            return(Ok(new StringValueRespose($"Found {userCount} users and {groupCount} groups")));
        }
示例#29
0
        /// <summary>
        /// Saves new LDAP settings
        /// </summary>
        /// <param name="ldapConfig">LDAP configuration</param>
        public async Task <int> ChangeLdapConfig(LdapSettings ldapConfig)
        {
            // AppSettings has only one record
            var appSettings = _dbContext.AppSettings.First();

            // Update config
            appSettings.LdapConfig = ldapConfig;

            // Save
            return(await _dbContext.SaveChangesAsync());
        }
示例#30
0
        /// <summary>
        /// Fill configuration section with default live values
        /// </summary>
        public virtual void SetDefaultLdapConfig()
        {
            LdapSettings ldapSettings = ConfigurationHandler.GetConfigurationSection <LdapSettings>();

            // Lookup for live OCES certificates ldapSettings.Host = "dir.certifikat.dk";
            ldapSettings.Host                    = "crtdir.certifikat.dk";
            ldapSettings.MaxResults              = 1;
            ldapSettings.Port                    = 389;
            ldapSettings.ConnectionTimeoutMsec   = 5000;
            ldapSettings.SearchClientTimeoutMsec = 5000;
            ldapSettings.SearchServerTimeoutMsec = 5000;
        }