/// <summary>
        /// Gets the directory entry.
        /// </summary>
        /// <param name="ldapPath">The LDAP path. Example: LDAP://yourdomain.com </param>
        /// <param name="userName">Name of the user. Exmaple: Domain\Account</param>
        /// <param name="password">The password. Sample: 123456</param>
        /// <param name="authenticationType">Type of the authentication.</param>
        /// <returns>DirectoryEntry.</returns>
        public static DirectoryEntry GetDirectoryEntry(string ldapPath, string userName, string password, AuthenticationTypes authenticationType = AuthenticationTypes.Secure)
        {
            try
            {
                ldapPath.CheckEmptyString("ldapPath");
                userName.CheckEmptyString("userName");
                password.CheckEmptyString("password");

                return new DirectoryEntry()
                {
                    Path = ldapPath,
                    Username = userName,
                    Password = password,
                    AuthenticationType = authenticationType
                };
            }
            catch (Exception ex)
            {
                throw ex.Handle( new { ldapPath, userName, password });
            }
        }
Beispiel #2
0
 public string ConnectToLDAP() {
     List<string> props = new List<string>();
     props.Add("cn");
     AuthenticationType = AuthenticationTypes.Secure;
     type = LdapService.ActiveDirectory;
     return Connect(userName, "(SAMAccountName=" + userName + ")", props);
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="Type">
		/// A <see cref="AuthenticationTypes"/>
		/// </param>
		/// <param name="Username">
		/// A <see cref="System.String"/>
		/// </param>
		/// <param name="Password">
		/// A <see cref="System.String"/>
		/// </param>
		public RemoteAuthentication(AuthenticationTypes Type,
									 string Username,
									 string Password) {
			this.Type = Type;
			this.Username = Username;
			this.Password = Password;
		}
		public TestConfiguration()
		{
			NameValueCollection config = (NameValueCollection) ConfigurationSettings.GetConfig ("System.DirectoryServices.Test/Settings");
			if (config != null) {
				string servername = config ["servername"];
				string port = config ["port"];
				_serverRoot = "LDAP://" + servername + (port.Equals ("389") ? String.Empty : (":" + port)) + "/";

				_baseDn = config ["basedn"];

				_username = config ["username"];
				_password = config ["password"];

				string authType = config ["authenticationtype"];

				string [] authTypes = authType.Split (new char[] { '|' });

				_authenticationType = (AuthenticationTypes) 0;

				foreach (string s in authTypes)
					foreach (AuthenticationTypes type in Enum.GetValues (typeof (AuthenticationTypes)))
						if (s.Trim ().Equals (type.ToString ()))
							_authenticationType |= type;	
			}

			//Console.WriteLine ("Connecting to {0} with credentials {1}:{2} and security {3}",ConnectionString,Username,Password,AuthenticationType);
		}
 public ServerDetails(string server, bool bUseIntergratedAuthentication)
 {
     this.Server = server;
     if (!bUseIntergratedAuthentication)
     {
         this.RequiredAuthentication = AuthenticationTypes.None;
     }
     else
     {
         this.requiredAuthentication = AuthenticationTypes.IntegratedAuthentication;
     }
 }
 /// <summary>
 /// Validation without proxy.
 /// </summary>
 /// <param name="url">URL to VersionOne instance.</param>
 /// <param name="username">VersionOne username.</param>
 /// <param name="password">VersionOne password.</param>
 /// <param name="authenticationType">VersionOne authentication type</param>
 public ConnectionValidationEventArgs(string url, string username, string password, AuthenticationTypes authenticationType)
 {
     this.authenticationType = authenticationType;
     this.url = url;
     this.username = username;
     this.password = password;
     this.useProxy = false;
     this.versionOneSettings.AuthenticationType = authenticationType;
     this.versionOneSettings.ApplicationUrl = url;
     this.versionOneSettings.Username = username;
     this.versionOneSettings.Password = password;
 }
Beispiel #7
0
 private static DirectoryEntry CreateDirectoryEntry(string rootDistinguishedName, string login, string password, AuthenticationTypes type)
 {
     try
     {
         return new DirectoryEntry(rootDistinguishedName, login, password, type);
     }
     catch (Exception e)
     {
         _log.ErrorFormat("Can't get access to directory: {0}. {1}", rootDistinguishedName, e);
         return null;
     }
 }
 /// <summary>
 ///   Initializes a new instance of the <see cref="DirectoryDataFactory" /> class.
 /// </summary>
 /// <param name="connectionString"> The connection string. </param>
 /// <param name="username"> The username. </param>
 /// <param name="password"> The password. </param>
 /// <param name="connectionProtection"> The connection protection. </param>
 /// <param name="absoluteCacheTimeout"> The absolute cache timeout. </param>
 /// <remarks>
 ///   Create and initialize an instance of this class for accessing Active Directory data.
 /// </remarks>
 public DirectoryDataFactory(string connectionString,
                             string username,
                             string password,
                             AuthenticationTypes connectionProtection,
                             TimeSpan absoluteCacheTimeout)
 {
     this._connectionString = connectionString;
     this._username = username;
     this._password = password;
     this._connectionProtection = connectionProtection;
     this._cacheTimeout = absoluteCacheTimeout;
     Initialize();
 }
Beispiel #9
0
		public Krb5Helper(string name, string clientName, Subject subject, AuthenticationTypes authenticationTypes, string mech)
		{
			_encryption = (authenticationTypes & AuthenticationTypes.Sealing) != 0;
			_signing = (authenticationTypes & AuthenticationTypes.Signing) != 0;
			_delegation = (authenticationTypes & AuthenticationTypes.Delegation) != 0;

			CreateContextPrivilegedAction action = new CreateContextPrivilegedAction (name, clientName, mech,_encryption,_signing,_delegation);
			try {
				_context = (GSSContext) Subject.doAs (subject,action);
			}
			catch (PrivilegedActionException e) {
				throw new LdapException ("Problem performing token exchange with the server",LdapException.OTHER,"",e.getCause()); 
			}
		}
        public CrossReferenceCollection( string UserName, string Password, AuthenticationTypes AuthType )
        {
            try
            {
                // Obtain NETBIOS only if LDAP accessible to prevent error
                DirectoryEntry rootLDAP = new DirectoryEntry( "LDAP://rootDSE", UserName, Password, AuthType );
                string crossRefPath = "LDAP://CN=Partitions," + rootLDAP.Properties["configurationNamingContext"].Value.ToString();
                DirectoryEntry objCrossRefContainer;

                if( ( UserName.Length > 0 ) && ( Password.Length > 0 ) )
                {
                    objCrossRefContainer = new DirectoryEntry( crossRefPath, UserName, Password, AuthType );
                }
                else
                {
                    objCrossRefContainer = new DirectoryEntry( crossRefPath );
                }

                DirectoryEntry objCrossRef;
                foreach( DirectoryEntry tempLoopVar_objCrossRef in objCrossRefContainer.Children )
                {
                    objCrossRef = tempLoopVar_objCrossRef;
                    if( !Convert.ToBoolean( objCrossRef.Properties["nETBIOSName"].Value == null ) )
                    {
                        string netBIOSName = Convert.ToString( objCrossRef.Properties["nETBIOSName"].Value );
                        string canonicalName = Convert.ToString( objCrossRef.Properties["dnsRoot"].Value );
                        string domainPath = Convert.ToString( objCrossRef.Properties["nCName"].Value );
                        CrossReference crossRef = new CrossReference( domainPath, netBIOSName, canonicalName );
                        this.Add( crossRef );
                    }
                }
                //mProcessLog += "Accessing LDAP : OK"
            }
            catch( COMException ex )
            {
                //mProcessLog += "Accessing LDAP : FAIL" & "<br>"
                mProcessLog += ex.Message + "<br>";
            }
        }
Beispiel #11
0
        /// <summary>
        /// Active Directory 서버에서 사용자 인증을 수행한다.
        /// </summary>
        /// <param name="adPath">AD 서버 경로 (ex: LDAP://ServerName )</param>
        /// <param name="username">사용자 Id</param>
        /// <param name="password">사용자 비밀번호</param>
        /// <param name="authType">인증 형식</param>
        /// <returns>인증 성공 여부</returns>
        public static bool Authenticate(string adPath, string username, string password, AuthenticationTypes authType) {
            adPath.ShouldNotBeWhiteSpace("adPath");
            username.ShouldNotBeWhiteSpace("username");

            if(IsDebugEnabled)
                log.Debug("Authenticate with adPath=[{0}], username=[{1}], password=[{2}], authType=[{3}]",
                          adPath, username, password, authType);

            bool result = false;
            DirectoryEntry entry = null;

            try {
                entry = new DirectoryEntry(adPath, username, password, authType);

                var nativeObject = entry.NativeObject;
                result = (nativeObject != null);
            }
            catch(Exception ex) {
                if(log.IsWarnEnabled) {
                    log.Warn("AD DirectoryEntry 조회에 실패했습니다. adPath=[{0}]", adPath);
                    log.Warn(ex);
                }

                result = false;
            }
            finally {
                if(entry != null)
                    entry.Dispose();
            }

            if(IsDebugEnabled)
                log.Debug("Authenticate with adPath=[{0}], username=[{1}], password=[{2}], authType=[{3}], result=[{4}]",
                          adPath, username, password, authType, result);

            return result;
        }
Beispiel #12
0
        /// <summary>
        /// </summary>
        /// <remarks>
        /// Accessing ADs costs lots of resource so we better put ADs object into app cache
        /// </remarks>
        public static Domain GetDomain( string Path, string UserName, string Password, AuthenticationTypes AuthenticationType )
        {
            Domain Domain = (Domain)DataCache.GetCache( Path );
            if( Domain == null )
            {
                if( ( UserName.Length > 0 ) && ( Password.Length > 0 ) )
                {
                    Domain = new Domain( Path, UserName, Password, AuthenticationType );
                }
                else
                {
                    Domain = new Domain( Path );
                }

                DataCache.SetCache( Path, Domain );
            }

            return Domain;
        }
Beispiel #13
0
        internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType, bool AdsObjIsExternal)
        {
            _adsObject = adsObject as UnsafeNativeMethods.IAds;
            if (_adsObject == null)
            {
                throw new ArgumentException(SR.DSDoesNotImplementIADs);
            }

            // GetInfo is not needed here. ADSI executes an implicit GetInfo when GetEx
            // is called on the PropertyValueCollection. 0x800704BC error might be returned
            // on some WinNT entries, when iterating through 'Users' group members.
            // if (forceBind)
            //     this.adsObject.GetInfo();
            _path     = _adsObject.ADsPath;
            _useCache = useCache;

            _authenticationType = authenticationType;
            _credentials        = new NetworkCredential(username, password);
            if (username == null)
            {
                _userNameIsNull = true;
            }

            if (password == null)
            {
                _passwordIsNull = true;
            }

            if (!useCache)
            {
                CommitChanges();
            }

            _options = new DirectoryEntryConfiguration(this);

            // We are starting from an already bound connection so make sure the options are set properly.
            // If this is an externallly managed com object then we don't want to change it's current behavior
            if (!AdsObjIsExternal)
            {
                InitADsObjectOptions();
            }
        }
 internal AbstractWebServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, ClientConfig config, AuthenticationTypes authenticationType)
     : this(new SessionAWSCredentials(awsAccessKeyId, awsSecretAccessKey, awsSessionToken), config, authenticationType)
 {
 }
Beispiel #15
0
		private static void UpdateGroupMembership(Principal group, DirectoryEntry de, NetCred credentials, AuthenticationTypes authTypes)
		{
			int num;
			PrincipalCollection valueForProperty = (PrincipalCollection)group.GetValueForProperty("GroupPrincipal.Members");
			UnsafeNativeMethods.IADsGroup nativeObject = (UnsafeNativeMethods.IADsGroup)de.NativeObject;
			try
			{
				if (valueForProperty.Cleared)
				{
					UnsafeNativeMethods.IADsMembers aDsMember = nativeObject.Members();
					IEnumVARIANT enumVARIANT = (IEnumVARIANT)aDsMember._NewEnum;
					object[] objArray = new object[1];
					do
					{
						num = enumVARIANT.Next(1, objArray, IntPtr.Zero);
						if (num != 0)
						{
							continue;
						}
						UnsafeNativeMethods.IADs aD = (UnsafeNativeMethods.IADs)objArray[0];
						nativeObject.Remove(aD.ADsPath);
					}
					while (num == 0);
					if (num != 1)
					{
						object[] str = new object[1];
						str[0] = num.ToString(CultureInfo.InvariantCulture);
						throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.SAMStoreCtxFailedToClearGroup, str));
					}
				}
				List<Principal> inserted = valueForProperty.Inserted;
				foreach (Principal principal in inserted)
				{
					Type type = principal.GetType();
					if (!(type != typeof(UserPrincipal)) || type.IsSubclassOf(typeof(UserPrincipal)) || !(type != typeof(ComputerPrincipal)) || type.IsSubclassOf(typeof(ComputerPrincipal)) || !(type != typeof(GroupPrincipal)) || type.IsSubclassOf(typeof(GroupPrincipal)))
					{
						if (!principal.unpersisted)
						{
							continue;
						}
						throw new InvalidOperationException(StringResources.StoreCtxGroupHasUnpersistedInsertedPrincipal);
					}
					else
					{
						object[] str1 = new object[1];
						str1[0] = type.ToString();
						throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.StoreCtxUnsupportedPrincipalTypeForGroupInsert, str1));
					}
				}
				foreach (Principal principal1 in inserted)
				{
					string sidADsPathFromPrincipal = SAMStoreCtx.GetSidADsPathFromPrincipal(principal1);
					if (sidADsPathFromPrincipal != null)
					{
						nativeObject.Add(sidADsPathFromPrincipal);
					}
					else
					{
						throw new InvalidOperationException(StringResources.SAMStoreCtxCouldntGetSIDForGroupMember);
					}
				}
				List<Principal> removed = valueForProperty.Removed;
				foreach (Principal principal2 in removed)
				{
					string sidADsPathFromPrincipal1 = SAMStoreCtx.GetSidADsPathFromPrincipal(principal2);
					if (sidADsPathFromPrincipal1 != null)
					{
						nativeObject.Remove(sidADsPathFromPrincipal1);
					}
					else
					{
						throw new InvalidOperationException(StringResources.SAMStoreCtxCouldntGetSIDForGroupMember);
					}
				}
			}
			catch (COMException cOMException1)
			{
				COMException cOMException = cOMException1;
				throw ExceptionHelper.GetExceptionFromCOMException(cOMException);
			}
		}
		public virtual IDirectoryEntry Create(string path, string username, string password, AuthenticationTypes authenticationTypes) {
			var entry = new DirectoryEntry(CorrectingScheme(path), username, password, authenticationTypes);
			return new DirectoryEntryWrapper(entry);
		}
 /// <summary>
 /// Initializes a mail sender
 /// </summary>
 /// <param name="Socket">The socket to use (default TCP port for SMTP is 25)</param>
 /// <param name="AuthenticationType">The form of SMTP Authentication (default: no authentication)</param>
 /// <param name="Username">Username for the SMTP server (when using authentication)</param>
 /// <param name="Password">Password for the SMTP server (when using authentication)</param>
 public SMTP_Client(SimpleSocket Socket, AuthenticationTypes AuthenticationType = AuthenticationTypes.None, string Username = "", string Password = "")
 {
     // Copies all parameters to the global scope
     this._Socket = Socket;
     this._SMTP_User = Username;
     this._SMTP_Pass = Password;
     this._SMTP_Auth = AuthenticationType;
     // By default we fill the hostname with the name of the hardware itself. We need this to identify ourself
     string Hostname = Tools.HardwareProvider.ToString();
     int LastDot = Hostname.LastIndexOf('.');
     if (LastDot > 0)
         this._LocalHostname = Hostname.Substring(0, LastDot);
     else
         this._LocalHostname = Hostname;
 }
        internal AmazonWebServiceClient(AWSCredentials credentials, ClientConfig config, bool ownCredentials, AuthenticationTypes authenticationType)
        {
            if (config.DisableLogging)
            {
                this.logger = Logger.EmptyLogger;
            }
            else
            {
                this.logger = Logger.GetLogger(this.GetType());
            }

            this.config             = config;
            this.ownCredentials     = ownCredentials;
            this.authenticationType = authenticationType;

            // Lookup cached version of refreshing credentials to reduce calls to STS.
            if (credentials is RefreshingSessionAWSCredentials)
            {
                RefreshingSessionAWSCredentials refreshCredentials = credentials as RefreshingSessionAWSCredentials;

                if (string.IsNullOrEmpty(refreshCredentials.UniqueIdentifier))
                {
                    this.credentials = credentials;
                }
                else
                {
                    this.ownCredentials = false;
                    lock (cachedRefreshingCredentialsLock)
                    {
                        if (cachedRefreshingCredentials.ContainsKey(refreshCredentials.UniqueIdentifier))
                        {
                            this.credentials = cachedRefreshingCredentials[refreshCredentials.UniqueIdentifier];
                        }
                        else
                        {
                            this.credentials = refreshCredentials;
                            cachedRefreshingCredentials[refreshCredentials.UniqueIdentifier] = refreshCredentials;
                        }
                    }
                }
            }
            else
            {
                this.credentials = credentials;
            }

            Initialize();
        }
Beispiel #19
0
 public AuthenticationOptions(Uri uri, AuthenticationTypes authenticationTypes)
     : this(uri, authenticationTypes, null)
 {
 }
Beispiel #20
0
 public AuthenticationOptions(string uri, AuthenticationTypes authenticationTypes)
     : this(new Uri(uri, UriKind.Absolute), authenticationTypes)
 {
 }
Beispiel #21
0
 internal SearchResult(NetworkCredential parentCredentials, AuthenticationTypes parentAuthenticationType)
 {
     _parentCredentials        = parentCredentials;
     _parentAuthenticationType = parentAuthenticationType;
 }
        private static DirectoryEntry NewDirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType)
        {
            DirectoryEntry de;

            if (!String.IsNullOrEmpty(username))
            {
                de = new DirectoryEntry(path, username, password, authenticationType);
            }
            else
            {
                de = new DirectoryEntry(path);
                de.AuthenticationType = authenticationType;
            }

            return(de);
        }
 internal AmazonWebServiceClient(AWSCredentials credentials, ClientConfig config, AuthenticationTypes authenticationType)
     : base(credentials, config, authenticationType)
 {
 }
Beispiel #24
0
        private bool Connect( AuthenticationTypes type )
        {
            bool res = false;
            DirectoryEntry entry = null;
            try
            {
                Logger.WriteTrace( string.Format( CultureInfo.CurrentCulture,
                                                  "Using Connection String - {0}", WorkoutConnection() ) );
                Logger.WriteTrace( string.Format( CultureInfo.CurrentCulture,
                                                  "Authentication Type - {0}", type ) );
                if( type == AuthenticationTypes.Secure )
                {
                    entry = new DirectoryEntry();
                }
                else
                {
                    if( type == AuthenticationTypes.None )
                    {
                        entry = new DirectoryEntry( ConnectionString, "", "" );
                    }
                    else
                    {
                        entry = new DirectoryEntry( ConnectionString, "", "", type );
                    }
                }
                // Do this to force the communication between us and the LDAP server.
                string name = entry.Name;
                if( string.IsNullOrEmpty( name ) == false )
                {
                    Logger.WriteAnswer( "Ldap Name", name );
                }

                if( LdapEngineType == EngineType.NotSet )
                {
                    WorkoutDefaultName( entry );
                    WorkoutEngineType( entry );
                    if( LdapEngineType == EngineType.ActiveDirectory )
                    {
                        WorkoutForestName( entry );
                    }
                }
                if( LdapEngineType != EngineType.NotSet )
                {
                    res = true;
                }
            }
            catch( COMException e )
            {
                // Check if we need to use anonymous connection (Domino server what us to!)
                if( (uint)e.ErrorCode != 0x80072027 )
                {
                    // A different type of exception so we better report it.
                    Logger.WriteTrace( string.Format( CultureInfo.CurrentCulture, "Cannot connect to LDAP Server - {0}", e.Message ) );
                }
                else
                {
                    res = Connect( AuthenticationTypes.Anonymous );
                }
            }
            finally
            {
                if( entry != null )
                {
                    entry.Dispose();
                }
            }
            return res;
        }
	public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType) {}
 internal AmazonWebServiceClient(string awsAccessKeyId, SecureString awsSecretAccessKey, ClientConfig config, AuthenticationTypes authenticationType)
     : this(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey), config, true, authenticationType)
 {
 }
 /// <summary>
 /// Validate with proxy settings.
 /// </summary>
 /// <param name="connectionSettings">Connection settings for VersionOne.</param>
 public ConnectionValidationEventArgs(VersionOneSettings connectionSettings)
 {
     this.authenticationType = connectionSettings.AuthenticationType;
     this.url = connectionSettings.ApplicationUrl;
     this.username = connectionSettings.Username;
     this.password = connectionSettings.Password;
     this.useProxy = connectionSettings.ProxySettings.Enabled;
     this.proxyDomain = connectionSettings.ProxySettings.Domain;
     this.proxyUri = connectionSettings.ProxySettings.Uri;
     this.proxyUsername = connectionSettings.ProxySettings.UserName;
     this.proxyPassword = connectionSettings.ProxySettings.Password;
     this.versionOneSettings = connectionSettings;
 }
 internal AmazonWebServiceClient(string awsAccessKeyId, string awsSecretAccessKey, ClientConfig config, AuthenticationTypes authenticationType)
     : this(authenticationType == AuthenticationTypes.Session ?
            (AWSCredentials) new RefreshingSessionAWSCredentials(awsAccessKeyId, awsSecretAccessKey, new AmazonSecurityTokenServiceConfig() { UseSecureStringForAwsSecretKey = config.UseSecureStringForAwsSecretKey }) :
            (AWSCredentials) new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey, config.UseSecureStringForAwsSecretKey),
            config, true, authenticationType)
 {
 }
Beispiel #29
0
		public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options)
		{
			this.ctxBaseLock = new object();
			this.computerInfoLock = new object();
			this.isLSAM = null;
			this.ctxBase = ctxBase;
			this.ownCtxBase = ownCtxBase;
			if (username != null && password != null)
			{
				this.credentials = new NetCred(username, password);
			}
			this.contextOptions = options;
			this.authTypes = SDSUtils.MapOptionsToAuthTypes(options);
		}
 internal AmazonWebServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, ClientConfig config, AuthenticationTypes authenticationType)
     : this(new SessionAWSCredentials(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, config.UseSecureStringForAwsSecretKey), config, true, authenticationType)
 {
 }
Beispiel #31
0
        /// <summary>
        /// Obtain Authentication settings from database
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [tamttt]	08/01/2004	Created
        /// </history>
        public Configuration()
        {
            mADSIPath = Path.GC;

            //Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings
            Authentication.Configuration authConfig = Authentication.Configuration.GetConfig();
            mPortalId = authConfig.PortalId;

            try
            {
                //Temporary fix this setting as TRUE for design, to be removed when release
                mConfigDomainPath   = authConfig.RootDomain;
                mDefaultEmailDomain = authConfig.EmailDomain;
                mUserName           = authConfig.UserName;
                mPassword           = authConfig.Password;
                mAuthenticationType = (AuthenticationTypes)(@Enum.Parse(typeof(AuthenticationTypes), authConfig.AuthenticationType.ToString()));
                // IMPORTANT: Remove ADSIPath, to be added later depends on accessing method

                this.mRootDomainPath = Utilities.ValidateDomainPath(this.mConfigDomainPath, Path.GC);
                mRootDomainPath      = mRootDomainPath.Substring(mRootDomainPath.Length - mRootDomainPath.Length - mRootDomainPath.IndexOf("DC="), mRootDomainPath.Length - mRootDomainPath.IndexOf("DC="));
            }
            catch (Exception exc)
            {
                mProcessLog += exc.Message + "<br>";
            }

            // Also check if Authentication implemented in this Windows Network
            DirectoryEntry gc = new DirectoryEntry();

            try
            {
                if (DirectoryEntry.Exists("GC://rootDSE"))
                {
                    DirectoryEntry rootGC;
                    if ((mUserName.Length > 0) && (mPassword.Length > 0))
                    {
                        rootGC = new DirectoryEntry("GC://rootDSE", mUserName, mPassword, mAuthenticationType);
                    }
                    else
                    {
                        rootGC = new DirectoryEntry("GC://rootDSE");
                    }
                    mConfigurationPath = rootGC.Properties[ADSI_CONFIGURATIONNAMIMGCONTEXT].Value.ToString();
                    mADSINetwork       = true;
                }
            }
            catch (COMException exc)
            {
                mADSINetwork   = false;
                mLDAPAccesible = false;
                mProcessLog   += exc.Message + "<br>";
                Exceptions.LogException(exc);
                // Nothing to do if we could not access Global Catalog, so return
                return;
            }

            // Also check if LDAP fully accessible
            DirectoryEntry ldap = new DirectoryEntry();

            try
            {
                if (DirectoryEntry.Exists("LDAP://rootDSE"))
                {
                    mLDAPAccesible = true;
                    mRefCollection = new CrossReferenceCollection(mUserName, mPassword, mAuthenticationType);
                }
            }
            catch (COMException exc)
            {
                mLDAPAccesible = false;
                mProcessLog   += exc.Message + "<br>";
                Exceptions.LogException(exc);
            }
        }
Beispiel #32
0
        internal static LdapConfiguration GetConfiguration(string configFile)
        {
            System.Diagnostics.Debug.WriteLine("GetConfiguration");
            if (!File.Exists(configFile))
            {
                System.Diagnostics.Debug.WriteLine(configFile + " not found ");
                return(null);
            }

            LdapConfiguration ldapConfig = null;

            try
            {
                string serverName      = "";
                string domain          = "";
                string port            = "";
                string user            = "";
                string password        = "";
                AuthenticationTypes at = AuthenticationTypes.None;

                XElement config = XDocument.Load(configFile).Element("Configuration");
                if (config != null)
                {
                    XElement child = config.Element("ServerName");
                    if (child != null)
                    {
                        serverName = child.Value;
                    }

                    child = config.Element("Domain");
                    if (child != null)
                    {
                        domain = child.Value;
                    }

                    child = config.Element("Port");
                    if (child != null)
                    {
                        port = child.Value;
                    }

                    child = config.Element("User");
                    if (child != null)
                    {
                        user = child.Value;
                    }

                    child = config.Element("Password");
                    if (child != null)
                    {
                        password = child.Value;
                    }

                    child = config.Element("AuthenticationTypes");
                    if (child != null)
                    {
                        string[] parts = child.Value.Split(',');
                        foreach (string p in parts)
                        {
                            string s = p.Trim();
                            if (s.Equals("Anonymous", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.Anonymous;
                            }
                            if (s.Equals("Delegation", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.Delegation;
                            }
                            if (s.Equals("Encryption", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.FastBind;
                            }
                            if (s.Equals("FastBind", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.FastBind;
                            }
                            if (s.Equals("ReadonlyServer", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.ReadonlyServer;
                            }
                            if (s.Equals("Sealing", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.Sealing;
                            }
                            if (s.Equals("Secure", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.Secure;
                            }
                            if (s.Equals("SecureSocketsLayer", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.SecureSocketsLayer;
                            }
                            if (s.Equals("ServerBind", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.ServerBind;
                            }
                            if (s.Equals("Signing", StringComparison.OrdinalIgnoreCase))
                            {
                                at |= AuthenticationTypes.Signing;
                            }
                        }
                    }

                    ldapConfig = new LdapConfiguration(serverName, domain, user, password, port, at);
                }
            }
            catch
            {
                // Couldn't read the configurations, usually we'll skip the tests which depend on that
            }
            return(ldapConfig);
        }
Beispiel #33
0
 internal DirectoryEntry(object adsObject, bool useCache, string username, string password, AuthenticationTypes authenticationType)
     : this(adsObject, useCache, username, password, authenticationType, false)
 {
 }
Beispiel #34
0
        internal static void InsertPrincipal(
            Principal p,
            StoreCtx storeCtx,
            GroupMembershipUpdater updateGroupMembership,
            NetCred credentials,
            AuthenticationTypes authTypes,
            bool needToSetPassword)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "Entering InsertPrincipal");

            Debug.Assert(storeCtx != null);
            Debug.Assert(storeCtx is ADStoreCtx || storeCtx is SAMStoreCtx);
            Debug.Assert(p != null);

            if ((!(p is UserPrincipal)) &&
                (!(p is GroupPrincipal)) &&
                (!(p is AuthenticablePrincipal)) &&
                (!(p is ComputerPrincipal)))
            {
                // It's not a type of Principal that we support
                GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SDSUtils", "InsertPrincipal: Bad principal type:" + p.GetType().ToString());

                throw new InvalidOperationException(SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForSave, p.GetType()));
            }

            // Commit the properties
            SDSUtils.ApplyChangesToDirectory(
                p,
                storeCtx,
                updateGroupMembership,
                credentials,
                authTypes
                );

            // Handle any saved-off operations

            // For SAM, we set password elsewhere prior to creating the principal, so needToSetPassword == false
            // For AD, we have to set the password after creating the principal, so needToSetPassword == true
            if (needToSetPassword && p.GetChangeStatusForProperty(PropertyNames.PwdInfoPassword))
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "InsertPrincipal: Setting password");

                // Only AuthenticablePrincipals can have PasswordInfo
                Debug.Assert(p is AuthenticablePrincipal);

                string password = (string)p.GetValueForProperty(PropertyNames.PwdInfoPassword);
                Debug.Assert(password != null); // if null, PasswordInfo should not have indicated it was changed

                storeCtx.SetPassword((AuthenticablePrincipal)p, password);
            }

            if (p.GetChangeStatusForProperty(PropertyNames.PwdInfoExpireImmediately))
            {
                // Only AuthenticablePrincipals can have PasswordInfo
                Debug.Assert(p is AuthenticablePrincipal);

                bool expireImmediately = (bool)p.GetValueForProperty(PropertyNames.PwdInfoExpireImmediately);

                if (expireImmediately)
                {
                    GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "InsertPrincipal: Setting pwd expired");

                    storeCtx.ExpirePassword((AuthenticablePrincipal)p);
                }
            }
        }
Beispiel #35
0
        internal DirectoryEntry(string path, bool useCache, string username, string password, AuthenticationTypes authenticationType)
        {
            _path        = path;
            _useCache    = useCache;
            _credentials = new NetworkCredential(username, password);
            if (username == null)
            {
                _userNameIsNull = true;
            }

            if (password == null)
            {
                _passwordIsNull = true;
            }

            _authenticationType = authenticationType;

            _options = new DirectoryEntryConfiguration(this);
        }
Beispiel #36
0
        internal static DirectoryEntry BuildDirectoryEntry(string path, NetCred credentials, AuthenticationTypes authTypes)
        {
            DirectoryEntry de = new DirectoryEntry(path,
                                                   credentials != null ? credentials.UserName : null,
                                                   credentials != null ? credentials.Password : null,
                                                   authTypes);

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSUtils", "BuildDirectoryEntry (1): built DE for  " + de.Path);

            return(de);
        }
Beispiel #37
0
 public Domain( string Path, string UserName, string Password, AuthenticationTypes AuthenticationType ) : base( Path, UserName, Password, AuthenticationType )
 {
     PopulateInfo();
     PopulateChild( this );
     mChildPopulate = true;
 }
Beispiel #38
0
        internal static void WriteAttribute <T>(string dePath, string attribute, T value, NetCred credentials, AuthenticationTypes authTypes)
        {
            Debug.Assert(attribute != null && attribute.Length > 0);

            // Ideally, we'd just like to set the property in the principal's DirectoryEntry and write
            // the changes to the store.  However, there might be other changes in the DirectoryEntry,
            // and we don't want to write all of them to the store.  So we must make
            // a fresh DirectoryEntry and write using that.

            DirectoryEntry copyOfDe = null;

            try
            {
                copyOfDe = SDSUtils.BuildDirectoryEntry(dePath, credentials, authTypes);

                Debug.Assert(copyOfDe != null);

                // So we don't do a implicit GetInfo() and retrieve every attribute
                copyOfDe.RefreshCache(new string[] { attribute });

                copyOfDe.Properties[attribute].Value = value;
                copyOfDe.CommitChanges();
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                // ADSI threw an exception trying to write the change
                throw ExceptionHelper.GetExceptionFromCOMException(e);
            }
            finally
            {
                if (copyOfDe != null)
                {
                    copyOfDe.Dispose();
                }
            }
        }
Beispiel #39
0
 protected static DirectoryEntry GetEntry(LdapServerInformation server, AuthenticationTypes type)
 {
     return server.GetEntry(type);
 }
Beispiel #40
0
        internal static void WriteAttribute(string dePath, string attribute, int value, NetCred credentials, AuthenticationTypes authTypes)
        {
            GlobalDebug.WriteLineIf(
                GlobalDebug.Info,
                "SDSUtils",
                "WriteAttribute: writing {0} to {1} on {2}",
                value.ToString(CultureInfo.InvariantCulture),
                attribute,
                dePath);

            Debug.Assert(attribute != null && attribute.Length > 0);

            // Ideally, we'd just like to set the property in the principal's DirectoryEntry and write
            // the changes to the store.  However, there might be other changes in the DirectoryEntry,
            // and we don't want to write all of them to the store.  So we must make
            // a fresh DirectoryEntry and write using that.

            DirectoryEntry copyOfDe = null;

            try
            {
                copyOfDe = SDSUtils.BuildDirectoryEntry(dePath, credentials, authTypes);

                Debug.Assert(copyOfDe != null);

                // So we don't do a implicit GetInfo() and retrieve every attribute
                copyOfDe.RefreshCache(new string[] { attribute });

                copyOfDe.Properties[attribute].Value = value;
                copyOfDe.CommitChanges();
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                GlobalDebug.WriteLineIf(
                    GlobalDebug.Error,
                    "SDSUtils",
                    "WriteAttribute: caught exception with message '{0}' writing {1} to {2} on {3}",
                    e.Message,
                    value.ToString(CultureInfo.InvariantCulture),
                    attribute,
                    dePath);

                // ADSI threw an exception trying to write the change
                throw ExceptionHelper.GetExceptionFromCOMException(e);
            }
            finally
            {
                if (copyOfDe != null)
                {
                    copyOfDe.Dispose();
                }
            }
        }
Beispiel #41
0
 public bool TestConnection( AuthenticationTypes type )
 {
     Logger.Write( "Connecting to LDAP...." );
     bool res = true;
     DateTime start = DateTime.Now;
     LdapEngineType = EngineType.NotSet;
     if( Connect( type ) == false )
     {
         // If here then we have tried type and anonymous, so we will try none
         if( Connect( AuthenticationTypes.None ) == false )
         {
             if( Connect( AuthenticationTypes.Anonymous ) == false )
             {
                 res = false;
             }
         }
     }
     if( res == false )
     {
         Logger.Write( "Cannot connect to LDAP..." );
     }
     else
     {
         Logger.WriteAnswerInTime( "Connected In", DateTime.Now.Subtract( start ) );
     }
     return res;
 }
Beispiel #42
0
        private AuthenticationStatus AuthenticateViaLdap(LoginInfo loginInfo, string password, AuthenticationTypes authenticationType = AuthenticationTypes.Secure)
        {
            try
            {
                _authenticator.Bind(loginInfo, password, authenticationType);

                return(AuthenticationStatus.Success);
            }
            catch (LdapException ldapException)
            {
                _log.LogError(LogSourceLdap, ldapException);
                if (ldapException.ErrorCode == LdapInvalidCredentialsErrorCode)
                {
                    return(AuthenticationStatus.InvalidCredentials);
                }

                return(AuthenticationStatus.Error);
            }
            catch (Exception ex)
            {
                _log.LogError(LogSourceLdap, ex);

                return(AuthenticationStatus.Error);
            }
        }
Beispiel #43
0
 public string ConnectToOpenLDAP() {
     List<string> props = new List<string>();
     props.Add("cn");
     AuthenticationType = AuthenticationTypes.None;
     type = LdapService.OpenLDAP;
     return Connect(openLdapUserName, "(objectClass=*)", props);
 }
Beispiel #44
0
        private AuthenticationStatus Authenticate(LoginInfo loginInfo, string password, AuthenticationTypes authenticationType = AuthenticationTypes.Secure)
        {
            var authenticationStatus = AuthenticateViaLdap(loginInfo, password, authenticationType);

            return(authenticationStatus == AuthenticationStatus.Error ? AuthenticateViaDirectory(loginInfo, password) : authenticationStatus);
        }
Beispiel #45
0
            internal ResultsEnumerator(SearchResultCollection results, string parentUserName, string parentPassword, AuthenticationTypes parentAuthenticationType)
            {
                if ((parentUserName != null) && (parentPassword != null))
                {
                    this.parentCredentials = new NetworkCredential(parentUserName, parentPassword);
                }
                this.parentAuthenticationType = parentAuthenticationType;
                this.results     = results;
                this.initialized = false;
                object section = System.Configuration.PrivilegedConfigurationManager.GetSection("system.directoryservices");

                if ((section != null) && (section is bool))
                {
                    this.waitForResult = (bool)section;
                }
            }
Beispiel #46
0
            internal ResultsEnumerator(SearchResultCollection results, string parentUserName, string parentPassword, AuthenticationTypes parentAuthenticationType)
            {
                if (parentUserName != null && parentPassword != null)
                {
                    _parentCredentials = new NetworkCredential(parentUserName, parentPassword);
                }

                _parentAuthenticationType = parentAuthenticationType;
                _results     = results;
                _initialized = false;
            }
Beispiel #47
0
        private void DoLDAPDirectoryInit()
        {
            // use the servername if they gave us one, else let ADSI figure it out
            string serverName = "";

            if (_name != null)
            {
                if (_contextType == ContextType.ApplicationDirectory)
                {
                    serverName = _serverProperties.dnsHostName + ":" +
                                 ((ContextOptions.SecureSocketLayer & _options) > 0 ? _serverProperties.portSSL : _serverProperties.portLDAP);
                }
                else
                {
                    serverName = _name;
                }

                serverName += "/";
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInit: serverName is " + serverName);

            // use the options they specified
            AuthenticationTypes authTypes = SDSUtils.MapOptionsToAuthTypes(_options);

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInit: authTypes is " + authTypes.ToString());

            DirectoryEntry de = new DirectoryEntry("LDAP://" + serverName + _container, _username, _password, authTypes);

            try
            {
                // Set the password port to the ssl port read off of the rootDSE.  Without this
                // password change/set won't work when we connect without SSL and ADAM is running
                // on non-standard port numbers.  We have already verified directory connectivity at this point
                // so this should always succeed.
                if (_serverProperties.portSSL > 0)
                {
                    de.Options.PasswordPort = _serverProperties.portSSL;
                }

                StoreCtx storeCtx = CreateContextFromDirectoryEntry(de);

                _queryCtx    = storeCtx;
                _userCtx     = storeCtx;
                _groupCtx    = storeCtx;
                _computerCtx = storeCtx;

                _connectedServer = ADUtils.GetServerName(de);
                de = null;
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(e);
            }
            catch (Exception e)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Error, "PrincipalContext",
                                        "DoLDAPDirectoryInit: caught exception of type "
                                        + e.GetType().ToString() +
                                        " and message " + e.Message);

                throw;
            }
            finally
            {
                // Cleanup the DE on failure
                if (de != null)
                {
                    de.Dispose();
                }
            }
        }
Beispiel #48
0
		public virtual void  Bind(System.String dn, System.String passwd, AuthenticationTypes authenticationTypes)
		{
#if TARGET_JVM
			if (authenticationTypes != AuthenticationTypes.None &&
				authenticationTypes != AuthenticationTypes.ServerBind &&
				authenticationTypes != AuthenticationTypes.Anonymous)
				BindSecure(dn, passwd, authenticationTypes);
			else
#endif
				Bind(Ldap_V3, dn, passwd, defSearchCons);		

			return ;
		}
        public DirectoryEntry GetEntry(AuthenticationTypes type)
        {
            DirectoryEntry entry = null;
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.AppendFormat(ResourceManager.GetString("CONN_START",
                            "Workshare.DirectorySearcher.Exceptions", typeof(LdapServerInformation).Assembly), ConnectionString);
                Logger.LogInfo(sb.ToString());

                if (UserName.Length == 0 && type == AuthenticationTypes.None)
                {
                    entry = new DirectoryEntry(ConnectionString);
                }
                else
                {
                    if (type == AuthenticationTypes.None)
                        entry = new DirectoryEntry(ConnectionString, UserName, Password); 
                    else
                        entry = new DirectoryEntry(ConnectionString, UserName, Password, type);
                }
                // Do this to force the communication between us and the LDAP server.
                string name = entry.Name;
                sb.Remove(0, sb.Length);
                
                sb.AppendFormat(m_connectionMessage, name);
				Logger.LogInfo(sb.ToString());
                if (LdapType == EngineType.NotSet ) 
                {
                    WorkoutDefaultName(entry);
                    WorkoutEngineType(entry);
                }
            }
            catch (COMException e)
            {
                // Check if we need to use anonymous connection (Domino server what us to!)
                if ((uint)e.ErrorCode != 0x80072027)
                {
					if (entry != null)
					{
						entry.Dispose();
					}
                	// A different type of exception so we better report it.
                    sb.Remove(0, sb.Length);
                    ExceptionResource er = new ExceptionResource("LDAPACCESS", "Workshare.DirectorySearcher.Exceptions", typeof(LdapServerInformation).Assembly);
                    sb.AppendFormat(er.Description, Environment.NewLine, e.Message, ConnectionString);
                    er.Description = sb.ToString();
					Logger.LogInfo(sb.ToString());
                    throw (new InvalidOperationException(sb.ToString(), e));
                }
                else
                {
                    sb.AppendFormat(ResourceManager.GetString("CONN_FAIL1",
                            "Workshare.DirectorySearcher.Exceptions", typeof(LdapServerInformation).Assembly), Environment.NewLine, e.Message);
                    // We need to use anonymous connection (Domino server what us to!)
                    if (entry != null)
                        entry.Dispose();
                    entry = GetEntry(AuthenticationTypes.Anonymous);
                }
            }
            return entry;
        }
 /// <summary>
 /// Set up the authentication credentials with the given authentication type, username and password.
 /// </summary>
 public Credentials(AuthenticationTypes type, string userName, string password)
 {
     this.Type = type;
     this.UserName = userName;
     this.Password = password;
 }
		/// <summary>
		/// Initializes a new instance of the DirectoryEntry class. The Path,
		///  Username, and Password properties are set to the specified values.
		/// </summary>
		/// <param name="path">Path of the entry i.e Ldap URL specifying 
		/// entry path</param>
		/// <param name="username">user name to use when authenticating the client
		/// </param>
		/// <param name="password">password to use when authenticating the client
		/// </param>
		/// <param name="authenticationType"> type of authentication to use</param>
		public DirectoryEntry(
				string path,
				string username,
				string password,
				AuthenticationTypes authenticationType)
		{
			_Path=path;
			_Username=username;
			_Password=password;
			_AuthenticationType=authenticationType;
		}
        /// <summary>
        ///   Initializes a new instance of the <see cref="DirectoryDataFactory" /> class.
        /// </summary>
        /// <param name="config"> The configuration data to use. </param>
        /// <remarks>
        ///   This constructor is intended to be called from within a providers Initialize method. It will read its settings from the config parameter and initialize this instance. Required settings in config are: connectionStringName = name of the connection string to use for connecting to the Active Directory server. connectionUsername = username for the connection. connectionPassword = password for the connection. Optional settings in config are: connectionProtection = level of protection and security for the Active Directory connection. None or Secure (default). cacheTimeout = how long cached Active Directory entries stys in the cache. Default is 10 minutes.
        /// </remarks>
        public DirectoryDataFactory(NameValueCollection config)
        {
            string connectionStringName;
            if (!TryGetDestructive(config, "connectionStringName", out connectionStringName))
            {
                throw new ProviderException("Required attribute connectionStringName not supplied.");
            }

            var settings = WebConfigurationManager.ConnectionStrings[connectionStringName];
            if (settings == null)
            {
                throw new ProviderException(String.Format("Connection string {0} not found.", connectionStringName));
            }

            this._connectionString = settings.ConnectionString;
            if (String.IsNullOrEmpty(this._connectionString))
            {
                throw new ProviderException(String.Format("Connection string {0} is empty.", connectionStringName));
            }

            if (!TryGetDestructive(config, "connectionUsername", out this._username))
            {
                throw new ProviderException("Required attribute connectionUsername not supplied.");
            }

            if (!TryGetDestructive(config, "connectionPassword", out this._password))
            {
                throw new ProviderException("Required attribute connectionPassword not supplied.");
            }

            this._connectionProtection = AuthenticationTypes.Secure;
            string connectionProtection;
            if (TryGetDestructive(config, "connectionProtection", out connectionProtection))
            {
                try
                {
                    this._connectionProtection = (AuthenticationTypes) Enum.Parse(typeof (AuthenticationTypes), connectionProtection, true);
                }
                catch (ArgumentException)
                {
                    throw new ProviderException(
                        String.Format("Attribute connectionProtection has illegal value {0}, supported values are {1}.",
                                      connectionProtection,
                                      String.Join(", ", Enum.GetNames(typeof (AuthenticationTypes)))));
                }
            }

            string cacheTimeSpan;
            if (TryGetDestructive(config, "cacheTimeout", out cacheTimeSpan))
            {
                if (!TimeSpan.TryParse(cacheTimeSpan, out this._cacheTimeout))
                {
                    throw new ProviderException(
                        String.Format("Attribute cacheTimeout has illegal value {0}, should be formatted as \"hours:minutes:seconds\"",
                                      cacheTimeSpan));
                }
            }
            else
            {
                this._cacheTimeout = new TimeSpan(0, 10, 0);
            }

            Initialize();
        }
Beispiel #53
0
        private void DoLDAPDirectoryInitNoContainer()
        {
            byte[] USERS_CONTAINER_GUID     = new byte[] { 0xa9, 0xd1, 0xca, 0x15, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
            byte[] COMPUTERS_CONTAINER_GUID = new byte[] { 0xaa, 0x31, 0x28, 0x25, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };

            // The StoreCtxs that will be used in the PrincipalContext, and their associated DirectoryEntry objects.
            DirectoryEntry deUserGroupOrg = null;
            DirectoryEntry deComputer     = null;
            DirectoryEntry deBase         = null;

            ADStoreCtx storeCtxUserGroupOrg = null;
            ADStoreCtx storeCtxComputer     = null;
            ADStoreCtx storeCtxBase         = null;

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering DoLDAPDirectoryInitNoContainer");

            //
            // Build a DirectoryEntry that represents the root of the domain.
            //

            // Use the RootDSE to find the default naming context
            DirectoryEntry deRootDse = null;
            string         adsPathBase;

            // use the servername if they gave us one, else let ADSI figure it out
            string serverName = "";

            if (_name != null)
            {
                serverName = _name + "/";
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: serverName is " + serverName);

            // use the options they specified
            AuthenticationTypes authTypes = SDSUtils.MapOptionsToAuthTypes(_options);

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: authTypes is " + authTypes.ToString());

            try
            {
                deRootDse = new DirectoryEntry("LDAP://" + serverName + "rootDse", _username, _password, authTypes);

                // This will also detect if the server is down or nonexistent
                string domainNC = (string)deRootDse.Properties["defaultNamingContext"][0];
                adsPathBase = "LDAP://" + serverName + domainNC;

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: domainNC is " + domainNC);
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoLDAPDirectoryInitNoContainer: adsPathBase is " + adsPathBase);
            }
            finally
            {
                // Don't allow the DE to leak
                if (deRootDse != null)
                {
                    deRootDse.Dispose();
                }
            }

            try
            {
                // Build a DE for the root of the domain using the retrieved naming context
                deBase = new DirectoryEntry(adsPathBase, _username, _password, authTypes);

                // Set the password port to the ssl port read off of the rootDSE.  Without this
                // password change/set won't work when we connect without SSL and ADAM is running
                // on non-standard port numbers.  We have already verified directory connectivity at this point
                // so this should always succeed.
                if (_serverProperties.portSSL > 0)
                {
                    deBase.Options.PasswordPort = _serverProperties.portSSL;
                }

                //
                // Use the wellKnownObjects attribute to determine the default location
                // for users and computers.
                //
                string adsPathUserGroupOrg = null;
                string adsPathComputer     = null;

                PropertyValueCollection wellKnownObjectValues = deBase.Properties["wellKnownObjects"];

                foreach (UnsafeNativeMethods.IADsDNWithBinary value in wellKnownObjectValues)
                {
                    if (Utils.AreBytesEqual(USERS_CONTAINER_GUID, (byte[])value.BinaryValue))
                    {
                        Debug.Assert(adsPathUserGroupOrg == null);
                        adsPathUserGroupOrg = "LDAP://" + serverName + value.DNString;

                        GlobalDebug.WriteLineIf(
                            GlobalDebug.Info,
                            "PrincipalContext",
                            "DoLDAPDirectoryInitNoContainer: found USER, adsPathUserGroupOrg is " + adsPathUserGroupOrg);
                    }

                    // Is it the computer container?
                    if (Utils.AreBytesEqual(COMPUTERS_CONTAINER_GUID, (byte[])value.BinaryValue))
                    {
                        Debug.Assert(adsPathComputer == null);
                        adsPathComputer = "LDAP://" + serverName + value.DNString;

                        GlobalDebug.WriteLineIf(
                            GlobalDebug.Info,
                            "PrincipalContext",
                            "DoLDAPDirectoryInitNoContainer: found COMPUTER, adsPathComputer is " + adsPathComputer);
                    }
                }

                if ((adsPathUserGroupOrg == null) || (adsPathComputer == null))
                {
                    // Something's wrong with the domain, it's not exposing the proper
                    // well-known object fields.
                    throw new PrincipalOperationException(SR.ContextNoWellKnownObjects);
                }

                //
                // Build DEs for the Users and Computers containers.
                // The Users container will also be used as the default for Groups.
                // The reason there are different contexts for groups, users and computers is so that
                // when a principal is created it will go into the appropriate default container.  This is so users don't
                // be default create principals in the root of their directory.  When a search happens the base context is used so that
                // the whole directory will be covered.
                //
                deUserGroupOrg = new DirectoryEntry(adsPathUserGroupOrg, _username, _password, authTypes);
                deComputer     = new DirectoryEntry(adsPathComputer, _username, _password, authTypes);

                StoreCtx userStore = CreateContextFromDirectoryEntry(deUserGroupOrg);

                _userCtx       = userStore;
                _groupCtx      = userStore;
                deUserGroupOrg = null;  // since we handed off ownership to the StoreCtx

                _computerCtx = CreateContextFromDirectoryEntry(deComputer);

                deComputer = null;

                _queryCtx = CreateContextFromDirectoryEntry(deBase);

                _connectedServer = ADUtils.GetServerName(deBase);

                deBase = null;
            }
            catch (Exception e)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Error,
                                        "PrincipalContext",
                                        "DoLDAPDirectoryInitNoContainer: caught exception of type "
                                        + e.GetType().ToString() +
                                        " and message " + e.Message);

                // Cleanup on failure.  Once a DE has been successfully handed off to a ADStoreCtx,
                // that ADStoreCtx will handle Dispose()'ing it
                if (deUserGroupOrg != null)
                {
                    deUserGroupOrg.Dispose();
                }

                if (deComputer != null)
                {
                    deComputer.Dispose();
                }

                if (deBase != null)
                {
                    deBase.Dispose();
                }

                if (storeCtxUserGroupOrg != null)
                {
                    storeCtxUserGroupOrg.Dispose();
                }

                if (storeCtxComputer != null)
                {
                    storeCtxComputer.Dispose();
                }

                if (storeCtxBase != null)
                {
                    storeCtxBase.Dispose();
                }

                throw;
            }
        }
Beispiel #54
0
        public void Ctor_Path_UserName_Password_AuthenticationType(string path, string userName, string password, AuthenticationTypes authenticationType)
        {
            var entry = new DirectoryEntry(path, userName, password, authenticationType);

            Assert.Equal(path ?? string.Empty, entry.Path);
            Assert.Equal(userName, entry.Username);
            Assert.Equal(authenticationType, entry.AuthenticationType);
            Assert.True(entry.UsePropertyCache);

            Assert.NotNull(entry.Children);
            Assert.NotNull(entry.Properties);
        }
Beispiel #55
0
		private void BindSecure(System.String username, System.String password, AuthenticationTypes authenticationTypes)
		{
			if ((authenticationTypes & AuthenticationTypes.Secure) != 0) {			
				LoginContext loginContext = null;
				try {					
					if (username != null && password != null) {
						AuthenticationCallbackHandler callbackHandler = new AuthenticationCallbackHandler (username,password);
						loginContext = new LoginContext (SecurityAppName, callbackHandler);
					}
					else
						loginContext = new LoginContext (SecurityAppName);

					loginContext.login ();
				}
				catch (Exception e) {
					throw new LdapException ("Failed to create login security context", 80, "", e);
				}

				Krb5Helper krb5Helper = null;
				try {
					krb5Helper = new Krb5Helper ("ldap@" + conn.Host, username, loginContext.getSubject (), authenticationTypes, SecurityMech);
				}
				finally {
					loginContext.logout();
				}
				sbyte [] token = krb5Helper.ExchangeTokens (Krb5Helper.EmptyToken);

				for (;;) {
					LdapResponseQueue queue = Bind(LdapConnection.Ldap_V3, username, token, null, null, AuthenticationMech);
					LdapResponse res = (LdapResponse) queue.getResponse ();
					if (res.ResultCode != LdapException.SASL_BIND_IN_PROGRESS &&
						res.ResultCode != LdapException.SUCCESS) {
						krb5Helper.Dispose();
						throw new LdapException(ExceptionMessages.CONNECTION_ERROR, res.ResultCode, res.ErrorMessage);
					}
					Asn1OctetString serverSaslCreds = ((RfcBindResponse)res.Asn1Object.Response).ServerSaslCreds;
					token = serverSaslCreds != null ? serverSaslCreds.byteValue () : null;

					token = krb5Helper.ExchangeTokens(token == null ? Krb5Helper.EmptyToken : token);

					if (res.ResultCode != LdapException.SASL_BIND_IN_PROGRESS)
						break;

					conn.ReplaceStreams (conn.InputStream,conn.OutputStream);
				}

				System.IO.Stream inStream = conn.InputStream;
				System.IO.Stream newIn = new SecureStream (inStream, krb5Helper);
				System.IO.Stream outStream = conn.OutputStream;
				System.IO.Stream newOut = new SecureStream (outStream, krb5Helper);
				conn.ReplaceStreams (newIn,newOut);
			}		
		}
        /// <summary>
        /// Obtain Authentication settings from database
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///     [tamttt]	08/01/2004	Created
        /// </history>
        public Configuration()
        {
            mADSIPath = Path.GC;

            //Dim _portalSettings As PortalSettings = PortalController.GetCurrentPortalSettings
            Authentication.Configuration authConfig = Authentication.Configuration.GetConfig();
            mPortalId = authConfig.PortalId;

            try
            {
                //Temporary fix this setting as TRUE for design, to be removed when release
                mConfigDomainPath = authConfig.RootDomain;
                mDefaultEmailDomain = authConfig.EmailDomain;
                mUserName = authConfig.UserName;
                mPassword = authConfig.Password;
                mAuthenticationType = (AuthenticationTypes)( @Enum.Parse( typeof( AuthenticationTypes ), authConfig.AuthenticationType.ToString() ) );
                // IMPORTANT: Remove ADSIPath, to be added later depends on accessing method

                this.mRootDomainPath = Utilities.ValidateDomainPath( this.mConfigDomainPath, Path.GC );
                mRootDomainPath = mRootDomainPath.Substring( mRootDomainPath.Length - mRootDomainPath.Length - mRootDomainPath.IndexOf( "DC=" ), mRootDomainPath.Length - mRootDomainPath.IndexOf( "DC=" ) );
            }
            catch( Exception exc )
            {
                mProcessLog += exc.Message + "<br>";
            }

            // Also check if Authentication implemented in this Windows Network
            DirectoryEntry gc = new DirectoryEntry();
            try
            {
                if( DirectoryEntry.Exists( "GC://rootDSE" ) )
                {
                    DirectoryEntry rootGC;
                    if( ( mUserName.Length > 0 ) && ( mPassword.Length > 0 ) )
                    {
                        rootGC = new DirectoryEntry( "GC://rootDSE", mUserName, mPassword, mAuthenticationType );
                    }
                    else
                    {
                        rootGC = new DirectoryEntry( "GC://rootDSE" );
                    }
                    mConfigurationPath = rootGC.Properties[ADSI_CONFIGURATIONNAMIMGCONTEXT].Value.ToString();
                    mADSINetwork = true;
                }
            }
            catch( COMException exc )
            {
                mADSINetwork = false;
                mLDAPAccesible = false;
                mProcessLog += exc.Message + "<br>";
                Exceptions.LogException( exc );
                // Nothing to do if we could not access Global Catalog, so return
                return;
            }

            // Also check if LDAP fully accessible
            DirectoryEntry ldap = new DirectoryEntry();
            try
            {
                if( DirectoryEntry.Exists( "LDAP://rootDSE" ) )
                {
                    mLDAPAccesible = true;
                    mRefCollection = new CrossReferenceCollection( mUserName, mPassword, mAuthenticationType );
                }
            }
            catch( COMException exc )
            {
                mLDAPAccesible = false;
                mProcessLog += exc.Message + "<br>";
                Exceptions.LogException( exc );
            }
        }
 private LdapConfiguration(string serverName, string searchDn, string userName, string password, string port, AuthenticationTypes at)
 {
     ServerName          = serverName;
     SearchDn            = searchDn;
     UserName            = userName;
     Password            = password;
     Port                = port;
     AuthenticationTypes = at;
 }
        internal static LdapConfiguration GetConfiguration(string configFile)
        {
            if (!File.Exists(configFile))
            {
                Environment.FailFast("LDAP test configuration file not found: " + configFile);
            }

            // To use test servers, set an environment variable LDAP_TEST_SERVER_INDEX
            // to the 0-based index of the <Connection> element in LDAP.Configuration.xml
            if (!int.TryParse(Environment.GetEnvironmentVariable("LDAP_TEST_SERVER_INDEX"), out int serverIndex))
            {
                return(null);
            }

            LdapConfiguration ldapConfig = null;

            try
            {
                XElement configuration = XDocument.Load(configFile).Element("Configuration");

                XElement connection = configuration.Elements("Connection").Skip(serverIndex).First();

                Debug.WriteLine($"Using test LDAP server {connection.Attribute("Name").Value}");

                string serverName      = "";
                string searchDn        = "";
                string port            = "";
                string user            = "";
                string password        = "";
                AuthenticationTypes at = AuthenticationTypes.None;

                XElement child = connection.Element("ServerName");
                if (child != null)
                {
                    serverName = child.Value;
                }

                child = connection.Element("SearchDN");
                if (child != null)
                {
                    searchDn = child.Value;
                }

                child = connection.Element("Port");
                if (child != null)
                {
                    port = child.Value;
                }

                child = connection.Element("User");
                if (child != null)
                {
                    user = child.Value;
                }

                child = connection.Element("Password");
                if (child != null)
                {
                    string val = child.Value;
                    if (val.StartsWith("%") && val.EndsWith("%"))
                    {
                        val = Environment.GetEnvironmentVariable(val.Substring(1, val.Length - 2));
                    }
                    password = val;
                }

                child = connection.Element("AuthenticationTypes");
                if (child != null)
                {
                    string[] parts = child.Value.Split(',');
                    foreach (string p in parts)
                    {
                        string s = p.Trim();
                        if (s.Equals("Anonymous", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.Anonymous;
                        }
                        if (s.Equals("Delegation", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.Delegation;
                        }
                        if (s.Equals("Encryption", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.FastBind;
                        }
                        if (s.Equals("FastBind", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.FastBind;
                        }
                        if (s.Equals("ReadonlyServer", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.ReadonlyServer;
                        }
                        if (s.Equals("Sealing", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.Sealing;
                        }
                        if (s.Equals("Secure", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.Secure;
                        }
                        if (s.Equals("SecureSocketsLayer", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.SecureSocketsLayer;
                        }
                        if (s.Equals("ServerBind", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.ServerBind;
                        }
                        if (s.Equals("Signing", StringComparison.OrdinalIgnoreCase))
                        {
                            at |= AuthenticationTypes.Signing;
                        }
                    }

                    ldapConfig = new LdapConfiguration(serverName, searchDn, user, password, port, at);
                }
            }
            catch (Exception ex)
            {
                // This runs within a test filter; if it throws, the test just skips. Instead we want to stop
                // so that it's quite clear that the server configuration is malformed.
                Environment.FailFast(ex.ToString());
            }
            return(ldapConfig);
        }
Beispiel #59
0
 private DirectoryEntry CreateDirectoryEntry(
     bool authentication, string dn, string login, string password, AuthenticationTypes type)
 {
     return(authentication ? new DirectoryEntry(dn, login, password, type) : new DirectoryEntry(dn));
 }
 internal AbstractWebServiceClient(string awsAccessKeyId, string awsSecretAccessKey, ClientConfig config, AuthenticationTypes authenticationType)
     : this((AWSCredentials) new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey),
            config, authenticationType)
 {
 }