Exemple #1
0
 /// <summary>
 /// SDK initializer which should be called one time only on first script call.
 /// </summary>
 public static void Initialize()
 {
     ContextOptions.Initialize();
     Scanner.Initialize();
     TileReader.Initialize();
     ScriptLogger.Initialize();
 }
Exemple #2
0
 private void CheckDisallowedOptions(ContextOptions testOptions)
 {
     if ((this.contextOptions & testOptions) == testOptions)
     {
         throw new InvalidOperationException(string.Format("The operation is not allowed due to the mode selected at creation time. testOptions = {0}, contextOptions = {1}.", testOptions, this.contextOptions));
     }
 }
Exemple #3
0
        public static PrincipalContext CreatePrincipalContext(Configuration config)
        {
            PrincipalContext context;

            if (config.SSL == true)
            {
                ContextOptions options = ContextOptions.Negotiate | ContextOptions.SecureSocketLayer;

                if (string.IsNullOrWhiteSpace(config.Username) || string.IsNullOrWhiteSpace(config.Password))
                {
                    context = new PrincipalContext(ContextType.Domain, config.Domain, config.ContainerDN, options);
                }
                else
                {
                    context = new PrincipalContext(ContextType.Domain, config.Domain, config.ContainerDN, options, config.Username, config.Password);
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(config.Username) || string.IsNullOrWhiteSpace(config.Password))
                {
                    context = new PrincipalContext(ContextType.Domain, config.Domain, config.ContainerDN);
                }
                else
                {
                    context = new PrincipalContext(ContextType.Domain, config.Domain, config.ContainerDN, config.Username, config.Password);
                }
            }

            return(context);
        }
Exemple #4
0
        /// <summary>
        /// Connect to the Security Account Manager service and retrieve the user principal
        /// structure for a given username or user email address.
        /// </summary>
        /// <param name="userOrEmail">User login name or account email address</param>
        /// <returns>User Principal data structure if found</returns>
        public static async Task <UserPrincipal> GetUserPrincipal(string userOrEmail)
        {
            ContextOptions options = ContextOptions.Negotiate | ContextOptions.Sealing | ContextOptions.Signing;

            if (ConfigurationManager.AppSettings["ad-bind-force-ssl"] == "1")
            {
                options = ContextOptions.Negotiate | ContextOptions.SecureSocketLayer;
            }

            using (PrincipalContext context = new PrincipalContext(ContextType.Domain, null, null, options))
            {
                // Try to retrieve the user principal data from the security account manager
                UserPrincipal userItem = null;

                if (userOrEmail.IndexOf('@') >= 0)
                {
                    return(await WindowsSamController.GetUserPrincipalByUpn(userOrEmail, context) ??
                           await GetUserPrincipalByEmail(userOrEmail, context) ??
                           throw new NotFoundException());
                }
                else
                {
                    userItem = await Task.Run(() => UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userOrEmail));
                }

                // If we couldn't find a matching account, throw an error to the calling routine
                if (userItem == null)
                {
                    throw new NotFoundException();
                }

                // Otherwise, return the principal structure located
                return(userItem);
            }
        }
Exemple #5
0
        internal static AuthenticationTypes MapOptionsToAuthTypes(ContextOptions options)
        {
            AuthenticationTypes authenticationType = AuthenticationTypes.Secure;

            if ((options & ContextOptions.SimpleBind) != 0)
            {
                authenticationType = AuthenticationTypes.None;
            }
            if ((options & ContextOptions.ServerBind) != 0)
            {
                authenticationType = authenticationType | AuthenticationTypes.ServerBind;
            }
            if ((options & ContextOptions.SecureSocketLayer) != 0)
            {
                authenticationType = authenticationType | AuthenticationTypes.Encryption;
            }
            if ((options & ContextOptions.Signing) != 0)
            {
                authenticationType = authenticationType | AuthenticationTypes.Signing;
            }
            if ((options & ContextOptions.Sealing) != 0)
            {
                authenticationType = authenticationType | AuthenticationTypes.Sealing;
            }
            return(authenticationType);
        }
Exemple #6
0
        public bool Validate(string userName, string password, ContextOptions connectionMethod)
        {
            // empty username and password on the local box
            // causes authentication to succeed.  If the username is empty we should just fail it
            // here.
            if (userName != null && userName.Length == 0)
            {
                return(false);
            }

            if (_contextType == ContextType.Domain || _contextType == ContextType.ApplicationDirectory)
            {
                try
                {
                    NetworkCredential networkCredential = new NetworkCredential(userName, password);
                    BindLdap(networkCredential, connectionMethod);
                    return(true);
                }
                catch (LdapException ldapex)
                {
                    if (ldapex.ErrorCode == ExceptionHelper.ERROR_LOGON_FAILURE)
                    {
                        return(false);
                    }

                    throw;
                }
            }
            else
            {
                return(BindSam(_serverName, userName, password));
            }
        }
Exemple #7
0
        /// <summary>
        /// This method returns the context options for the Server Type.
        /// </summary>
        /// <param name="serverType">The server type to be converted to the corresponding ContextOptions</param>
        /// <returns></returns>
        public static ContextOptions ConvertToContextOptions(uint serverType)
        {
            ContextOptions contextOptions = 0;

            if ((0 != (serverType & ServerType.OPC_DA205_Wrapper)) ||
                (0 != (serverType & ServerType.OPC_UA_DA_Wrapper)) ||
                (0 != (serverType & ServerType.Xi_DataServer)) ||
                (0 != (serverType & ServerType.OPC_XMLDA_Wrapper)))
            {
                contextOptions |= (Xi.Contracts.Constants.ContextOptions.EnableDataAccess);
            }
            if ((0 != (serverType & ServerType.OPC_AE11_Wrapper)) ||
                (0 != (serverType & ServerType.OPC_UA_AC_Wrapper)) ||
                (0 != (serverType & ServerType.Xi_EventServer)))
            {
                contextOptions |= (Xi.Contracts.Constants.ContextOptions.EnableAlarmsAndEventsAccess);
            }
            if ((0 != (serverType & ServerType.OPC_HDA12_Wrapper)) ||
                (0 != (serverType & ServerType.OPC_UA_HDA_Wrapper)) ||
                (0 != (serverType & ServerType.Xi_EventServer)))
            {
                contextOptions |= (Xi.Contracts.Constants.ContextOptions.EnableJournalDataAccess);
            }
            if (0 != (serverType & ServerType.Xi_EventJournalServer))
            {
                contextOptions |= (Xi.Contracts.Constants.ContextOptions.EnableJournalAlarmsAndEventsAccess);
            }
            return(contextOptions);
        }
Exemple #8
0
        /// <summary>
        /// Validate the passed credentials against the directory supplied.
        /// The supplied options will determine the directory method for credential validation.
        /// </summary>
        public bool ValidateCredentials(string userName, string password, ContextOptions options)
        {
            // Perform credential validation using fast concurrent bind...
            CheckDisposed();

            if ((userName == null && password != null) ||
                (userName != null && password == null))
            {
                throw new ArgumentException(SR.ContextBadUserPwdCombo);
            }

            if (options != ContextOptions.Negotiate && _contextType == ContextType.Machine)
            {
                throw new ArgumentException(SR.ContextOptionsNotValidForMachineStore);
            }

#if TESTHOOK
            if (contextType == ContextType.Test)
            {
                return(true);
            }
#endif

            return(_credValidate.Validate(userName, password, options));
        }
Exemple #9
0
        static internal AuthenticationTypes MapOptionsToAuthTypes(ContextOptions options)
        {
            AuthenticationTypes authTypes = AuthenticationTypes.Secure;

            if ((options & ContextOptions.SimpleBind) != 0)
            {
                authTypes = AuthenticationTypes.None;
            }

            if ((options & ContextOptions.ServerBind) != 0)
            {
                authTypes |= AuthenticationTypes.ServerBind;
            }

            if ((options & ContextOptions.SecureSocketLayer) != 0)
            {
                authTypes |= AuthenticationTypes.SecureSocketsLayer;
            }

            if ((options & ContextOptions.Signing) != 0)
            {
                authTypes |= AuthenticationTypes.Signing;
            }

            if ((options & ContextOptions.Sealing) != 0)
            {
                authTypes |= AuthenticationTypes.Sealing;
            }

            return(authTypes);
        }
Exemple #10
0
        /// <summary>
        /// 初始化并返加一个读写分离的数据库上下文对象.
        /// </summary>
        /// <param name="options">初始化数据库上下文对象所需要的选项.</param>
        /// <returns></returns>
        public static DatabaseContext Initialize(ContextOptions options)
        {
            DatabaseContext DbContext = new DatabaseContext();

            DbContext.ReadEngine  = new DataEngine(options.ReadAccess, options.Parser);
            DbContext.WriteEngine = new DataEngine(options.WriteAccess, options.Parser);
            return(DbContext);
        }
 public Contexts(ContextOptions options)
 {
     if (options == null)
     {
         throw new Exception("Contexts options are missing");
     }
     Options = options;
 }
        public ADMethodsAccountManagementDefault()
        {
            string appContextOptionsValidate         = ConfigurationManager.AppSettings["ContextOptionsValidate"];
            string appContextOptionsPrincipalContext = ConfigurationManager.AppSettings["ContextOptionsContext"];

            contextOptionsValidate         = (ContextOptions)Enum.Parse(typeof(ContextOptions), appContextOptionsValidate, true);
            contextOptionsPrincipalContext = (ContextOptions)Enum.Parse(typeof(ContextOptions), appContextOptionsPrincipalContext, true);
        }
        protected override void Configure(ContextOptions <Product> options)
        {
            options.CalculationStrategy = CalculationStrategy.Full;

            NameFilter   = options.Filter(product => product.Name).With(domain => domain.List("Name"));
            RatingFilter = options.Filter(product => product.Rating).With(domain => domain.Range("Rating"));
            SoldFilter   = options.Filter(product => product.Sold).With(domain => domain.GreaterThan("Sold"));
        }
 public void Ctor_InvalidOptions_ThrowsInvalidEnumArgumentException(ContextOptions options)
 {
     AssertExtensions.Throws <InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Machine, "name", null, options));
     AssertExtensions.Throws <InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Domain, "name", null, options));
     AssertExtensions.Throws <InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "container", options));
     AssertExtensions.Throws <InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Machine, "name", null, options, "userName", "password"));
     AssertExtensions.Throws <InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Domain, "name", null, options, "userName", "password"));
     AssertExtensions.Throws <InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "container", options, "userName", "password"));
 }
Exemple #15
0
        /// <summary>
        /// 初始化并返加一个读写分离的数据库上下文对象.
        /// </summary>
        /// <param name="func">用于配置并返回需要的选项.</param>
        /// <returns></returns>
        public static DatabaseContext Initialize(Func <ContextOptions> func)
        {
            ContextOptions options = func();

            if (options == null)
            {
                throw new NoNullAllowedException("The options required to initialize a database context object are not configured.");
            }
            return(Initialize(options));
        }
Exemple #16
0
        public ADMethodsAccountManagement(string username, string password)
        {
            sServiceUser     = username;
            sServicePassword = password;

            string appContextOptionsValidate         = ConfigurationManager.AppSettings["ContextOptionsValidate"];
            string appContextOptionsPrincipalContext = ConfigurationManager.AppSettings["ContextOptionsContext"];

            contextOptionsValidate         = (ContextOptions)Enum.Parse(typeof(ContextOptions), appContextOptionsValidate, true);
            contextOptionsPrincipalContext = (ContextOptions)Enum.Parse(typeof(ContextOptions), appContextOptionsPrincipalContext, true);
        }
        private static ContextOptions SetBindingOptions(IEnumerable <ITaskItem> value)
        {
            ContextOptions s = new ContextOptions();

            foreach (ITaskItem option in value)
            {
                s |= (ContextOptions)Enum.Parse(typeof(ContextOptions), option.ItemSpec);
            }

            return(s);
        }
Exemple #18
0
    protected string _eval(string code, Action <ContextOptions> on_options = null)
    {
        ContextOptions options = new ContextOptions();

        on_options?.Invoke(options);
        Context context = new Context(
            options: options,
            parser: new PHP.Parser.Parser()
            );

        return(context.Eval(code));
    }
Exemple #19
0
        public PrincipalContext(
            ContextType contextType, string name, string container, ContextOptions options, string userName, string password)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering ctor");

            if ((userName == null && password != null) ||
                (userName != null && password == null))
                throw new ArgumentException(SR.ContextBadUserPwdCombo);

            if ((options & ~(ContextOptions.Signing | ContextOptions.Negotiate | ContextOptions.Sealing | ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind | ContextOptions.ServerBind)) != 0)
                throw new InvalidEnumArgumentException(nameof(options), (int)options, typeof(ContextOptions));

            if (contextType == ContextType.Machine && ((options & ~ContextOptions.Negotiate) != 0))
            {
                throw new ArgumentException(SR.InvalidContextOptionsForMachine);
            }

            if ((contextType == ContextType.Domain || contextType == ContextType.ApplicationDirectory) &&
                (((options & (ContextOptions.Negotiate | ContextOptions.SimpleBind)) == 0) ||
                (((options & (ContextOptions.Negotiate | ContextOptions.SimpleBind)) == ((ContextOptions.Negotiate | ContextOptions.SimpleBind))))))
            {
                throw new ArgumentException(SR.InvalidContextOptionsForAD);
            }

            if ((contextType != ContextType.Machine) &&
                (contextType != ContextType.Domain) &&
                (contextType != ContextType.ApplicationDirectory)
            #if TESTHOOK
                && (contextType != ContextType.Test)
            #endif
                )
            {
                throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(ContextType));
            }

            if ((contextType == ContextType.Machine) && (container != null))
                throw new ArgumentException(SR.ContextNoContainerForMachineCtx);

            if ((contextType == ContextType.ApplicationDirectory) && ((string.IsNullOrEmpty(container)) || (string.IsNullOrEmpty(name))))
                throw new ArgumentException(SR.ContextNoContainerForApplicationDirectoryCtx);

            _contextType = contextType;
            _name = name;
            _container = container;
            _options = options;

            _username = userName;
            _password = password;

            DoServerVerifyAndPropRetrieval();

            _credValidate = new CredentialValidator(contextType, name, _serverProperties);
        }
Exemple #20
0
 static SessionController()
 {
     try
     {
         Domain.GetComputerDomain();
         Context = ContextType.Domain;
         ContextOptions = ContextOptions.SimpleBind;
     }
     catch(Exception)
     {
         Context = ContextType.Machine;
         ContextOptions = ContextOptions.Negotiate;
     }
 }
Exemple #21
0
 private void lockedLdapBind(LdapConnection current, NetworkCredential creds, ContextOptions contextOptions)
 {
     current.AuthType = ((ContextOptions.SimpleBind & contextOptions) > 0 ? AuthType.Basic : AuthType.Negotiate);
     current.SessionOptions.Signing = ((ContextOptions.Signing & contextOptions) > 0 ? true : false);
     current.SessionOptions.Sealing = ((ContextOptions.Sealing & contextOptions) > 0 ? true : false);
     if ((null == creds.UserName) && (null == creds.Password))
     {
         current.Bind();
     }
     else
     {
         current.Bind(creds);
     }
 }
        private void lockedLdapBind(LdapConnection current, NetworkCredential creds, ContextOptions contextOptions)
        {
            AuthType       authType;
            bool           flag;
            bool           flag1;
            LdapConnection ldapConnection = current;

            if ((ContextOptions.SimpleBind & contextOptions) > 0)
            {
                authType = AuthType.Basic;
            }
            else
            {
                authType = AuthType.Negotiate;
            }
            ldapConnection.AuthType = authType;
            LdapSessionOptions sessionOptions = current.SessionOptions;

            if ((ContextOptions.Signing & contextOptions) > 0)
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
            sessionOptions.Signing = flag;
            LdapSessionOptions ldapSessionOption = current.SessionOptions;

            if ((ContextOptions.Sealing & contextOptions) > 0)
            {
                flag1 = true;
            }
            else
            {
                flag1 = false;
            }
            ldapSessionOption.Sealing = flag1;
            if (creds.UserName != null || creds.Password != null)
            {
                current.Bind(creds);
                return;
            }
            else
            {
                current.Bind();
                return;
            }
        }
        public GetPasswordForm(string user, string domain, ContextType type, ContextOptions options)
        {
            this.InitializeComponent();

            if (!string.IsNullOrEmpty(domain))
            {
                this.Text += domain + @"\";
            }
            
            this.Text += user;
            this.user = user;
            this.domain = domain;
            this.contextType = type;
            this.contextOptions = options;
        }
        public GetPasswordForm(string user, string domain, ContextType type, ContextOptions options)
        {
            this.InitializeComponent();

            if (!string.IsNullOrEmpty(domain))
            {
                this.Text += domain + @"\";
            }

            this.Text          += user;
            this.user           = user;
            this.domain         = domain;
            this.contextType    = type;
            this.contextOptions = options;
        }
Exemple #25
0
//=========================================================================================
//end of main
//=========================================================================================
        static void acceptQuesticle(PlayerMobile P, Mobile npc)
        {
            Console.WriteLine("Accepting quest");
            ContextOptions.Initialize();
            npc.ContextMenu.Parse();
            Stealth.Client.Wait(1500);
            npc.ContextMenu.Click("Talk", true);


            //foreach(Gump gumps in Gump.ActiveGumps)
            //{
            //    Console.WriteLine("gump type: " + gumps.GumpType);
            //    Console.WriteLine("serial: " + gumps.Serial.Value);
            //    Console.WriteLine("buttons: " + gumps.Buttons.Count);
            //}

            Gump questGump;

            Gump.WaitForGump(2460962336, 5000, out questGump);
            if (questGump == null)
            {
                Console.WriteLine("questgump is null");
            }
            Stealth.Client.Wait(1000);
            questGump.Buttons.First().Click();
            Gump secondQuestGump;

            Gump.WaitForGump(2685952746, 5000, out secondQuestGump);

            if (secondQuestGump == null)
            {
                Console.WriteLine("second quest gump is null");
            }
            Stealth.Client.Wait(1000);
            secondQuestGump.Buttons.First().Click();

            Gump questAcceptedGump;

            Gump.WaitForGump(1353954171, 5000, out questAcceptedGump);

            if (questAcceptedGump == null)
            {
                Console.WriteLine("questAcceptedGump is null");
            }
            Stealth.Client.Wait(1000);
            questAcceptedGump.Close();
            //Console.ReadLine();
        }
Exemple #26
0
        public static PrincipalContext CreateLdapContext(string domainname, string containerdn, bool ssl)
        {
            PrincipalContext context;

            if (ssl == true)
            {
                ContextOptions options = ContextOptions.Negotiate | ContextOptions.SecureSocketLayer;
                context = new PrincipalContext(ContextType.Domain, domainname, containerdn, options);
            }
            else
            {
                context = new PrincipalContext(ContextType.Domain, domainname, containerdn);
            }

            return(context);
        }
Exemple #27
0
 internal LatencyDetectionContext(LatencyDetectionLocation location, ContextOptions contextOptions, string version, object hash, params IPerformanceDataProvider[] providers)
 {
     this.latencyDetectionLocation = location;
     this.assemblyVersion          = version;
     this.StackTraceContext        = hash;
     this.contextOptions           = contextOptions;
     if ((contextOptions & ContextOptions.DoNotMeasureTime) == ContextOptions.DoNotMeasureTime)
     {
         this.timer = null;
     }
     else
     {
         this.timer = MyStopwatch.StartNew();
     }
     this.SetDataProviders(providers);
 }
Exemple #28
0
        public ContextOptionsTest()
        {
            Randomizer.Seed = new Random(0);

            var testGenericSources = new Faker <GenericSource>();

            testGenericSources.RuleFor(entity => entity.Int, faker => faker.Random.Int(0, 10));
            testGenericSources.RuleFor(entity => entity.Double, faker => faker.Random.Double(0, 20));
            testGenericSources.RuleFor(entity => entity.Float, faker => faker.Random.Float(0, 30));
            var items = testGenericSources.GenerateLazy(20).ToList();

            var queryable = items.AsQueryable();

            _testInstance = new ContextOptions <GenericSource>(queryable, options =>
            {
                _contextOptionsInitialized = true;
            });
        }
        // Throws exception if ctxBase is not a computer object
        public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options)
        {
            Debug.Assert(ctxBase != null);
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Constructing SAMStoreCtx for {0}", ctxBase.Path);

            Debug.Assert(SAMUtils.IsOfObjectClass(ctxBase, "Computer"));

            _ctxBase    = ctxBase;
            _ownCtxBase = ownCtxBase;

            if (username != null && password != null)
            {
                _credentials = new NetCred(username, password);
            }

            _contextOptions = options;
            _authTypes      = SDSUtils.MapOptionsToAuthTypes(options);
        }
 public bool ValidateCredentials(string userName, string password, ContextOptions options)
 {
     this.CheckDisposed();
     if ((userName != null || password == null) && (userName == null || password != null))
     {
         if (options == ContextOptions.Negotiate || this.contextType != ContextType.Machine)
         {
             return(this.credValidate.Validate(userName, password, options));
         }
         else
         {
             throw new ArgumentException(StringResources.ContextOptionsNotValidForMachineStore);
         }
     }
     else
     {
         throw new ArgumentException(StringResources.ContextBadUserPwdCombo);
     }
 }
        public bool Validate(string userName, string password, ContextOptions connectionMethod)
        {
            bool flag;

            if (userName == null || userName.Length != 0)
            {
                if (this.contextType == ContextType.Domain || this.contextType == ContextType.ApplicationDirectory)
                {
                    try
                    {
                        NetworkCredential networkCredential = new NetworkCredential(userName, password);
                        this.BindLdap(networkCredential, connectionMethod);
                        flag = true;
                    }
                    catch (LdapException ldapException1)
                    {
                        LdapException ldapException = ldapException1;
                        if ((long)ldapException.ErrorCode != (long)ExceptionHelper.ERROR_LOGON_FAILURE)
                        {
                            throw;
                        }
                        else
                        {
                            flag = false;
                        }
                    }
                    return(flag);
                }
                else
                {
                    return(this.BindSam(this.serverName, userName, password));
                }
            }
            else
            {
                return(false);
            }
        }
        public override void VisitQueryModel(QueryModel queryModel)
        {
            base.VisitQueryModel(queryModel);

            if (ContextOptions.FindExtension <SqlServerOptionsExtension>()?.RowNumberPaging == true)
            {
                var visitor = new RowNumberPagingExpressionVisitor();

                SelectExpression mainSelectExpression;
                if (QueriesBySource.TryGetValue(queryModel.MainFromClause, out mainSelectExpression))
                {
                    visitor.Visit(mainSelectExpression);
                }

                foreach (var additionalSource in queryModel.BodyClauses.OfType <IQuerySource>())
                {
                    SelectExpression additionalFromExpression;
                    if (QueriesBySource.TryGetValue(additionalSource, out additionalFromExpression))
                    {
                        visitor.Visit(mainSelectExpression);
                    }
                }
            }
        }
Exemple #33
0
 public PrincipalContext(ContextType contextType, string name, string container, ContextOptions options) :
     this(contextType, name, container, options, null, null)
 { }
Exemple #34
0
        public bool Validate(string userName, string password, ContextOptions connectionMethod)
        {
            // empty username and password on the local box
            // causes authentication to succeed.  If the username is empty we should just fail it
            // here.
            if (userName != null && userName.Length == 0)
                return false;

            if (_contextType == ContextType.Domain || _contextType == ContextType.ApplicationDirectory)
            {
                try
                {
                    NetworkCredential networkCredential = new NetworkCredential(userName, password);
                    BindLdap(networkCredential, connectionMethod);
                    return true;
                }
                catch (LdapException ldapex)
                {
                    if (ldapex.ErrorCode == ExceptionHelper.ERROR_LOGON_FAILURE)
                    {
                        return false;
                    }

                    throw;
                }
            }
            else
            {
                return (BindSam(_serverName, userName, password));
            }
        }
Exemple #35
0
		private void lockedLdapBind(LdapConnection current, NetworkCredential creds, ContextOptions contextOptions)
		{
			AuthType authType;
			bool flag;
			bool flag1;
			LdapConnection ldapConnection = current;
			if ((ContextOptions.SimpleBind & contextOptions) > 0)
			{
				authType = AuthType.Basic;
			}
			else
			{
				authType = AuthType.Negotiate;
			}
			ldapConnection.AuthType = authType;
			LdapSessionOptions sessionOptions = current.SessionOptions;
			if ((ContextOptions.Signing & contextOptions) > 0)
			{
				flag = true;
			}
			else
			{
				flag = false;
			}
			sessionOptions.Signing = flag;
			LdapSessionOptions ldapSessionOption = current.SessionOptions;
			if ((ContextOptions.Sealing & contextOptions) > 0)
			{
				flag1 = true;
			}
			else
			{
				flag1 = false;
			}
			ldapSessionOption.Sealing = flag1;
			if (creds.UserName != null || creds.Password != null)
			{
				current.Bind(creds);
				return;
			}
			else
			{
				current.Bind();
				return;
			}
		}
Exemple #36
0
		private bool BindLdap(NetworkCredential creds, ContextOptions contextOptions)
		{
			LdapConnection item;
			int lDAPSSLPORT;
			bool flag;
			int num;
			bool flag1 = (ContextOptions.SecureSocketLayer & contextOptions) > 0;
			if (this.contextType != ContextType.ApplicationDirectory)
			{
				CredentialValidator ldapDirectoryIdentifier = this;
				string str = this.serverName;
				if (flag1)
				{
					lDAPSSLPORT = LdapConstants.LDAP_SSL_PORT;
				}
				else
				{
					lDAPSSLPORT = LdapConstants.LDAP_PORT;
				}
				ldapDirectoryIdentifier.directoryIdent = new LdapDirectoryIdentifier(str, lDAPSSLPORT);
			}
			else
			{
				CredentialValidator credentialValidator = this;
				string str1 = this.serverProperties.dnsHostName;
				if (flag1)
				{
					num = this.serverProperties.portSSL;
				}
				else
				{
					num = this.serverProperties.portLDAP;
				}
				credentialValidator.directoryIdent = new LdapDirectoryIdentifier(str1, num);
			}
			if (!flag1)
			{
				flag = false;
			}
			else
			{
				flag = this.fastConcurrentSupported;
			}
			bool flag2 = flag;
			int num1 = Convert.ToInt32(flag2) * 2 + Convert.ToInt32(flag1);
			if (this.connCache.Contains(num1))
			{
				item = (LdapConnection)this.connCache[(object)num1];
			}
			else
			{
				lock (this.cacheLock)
				{
					if (this.connCache.Contains(num1))
					{
						item = (LdapConnection)this.connCache[(object)num1];
					}
					else
					{
						item = new LdapConnection(this.directoryIdent);
						item.SessionOptions.SecureSocketLayer = flag1;
						if (flag2)
						{
							try
							{
								item.SessionOptions.FastConcurrentBind();
							}
							catch (PlatformNotSupportedException platformNotSupportedException)
							{
								item.Dispose();
								item = null;
								this.fastConcurrentSupported = false;
								num1 = Convert.ToInt32(flag1);
								item = new LdapConnection(this.directoryIdent);
								item.SessionOptions.SecureSocketLayer = flag1;
							}
						}
						this.connCache.Add(num1, item);
					}
				}
			}
			if (!flag2 || !this.fastConcurrentSupported)
			{
				lock (this.cacheLock)
				{
					this.lockedLdapBind(item, creds, contextOptions);
				}
			}
			else
			{
				this.lockedLdapBind(item, creds, contextOptions);
			}
			return true;
		}
Exemple #37
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);
		}
 public PrincipalContextFull(ContextType contextType, string name, string container, ContextOptions options)
     : base(contextType, name, container, options)
 {
 }
Exemple #39
0
		public bool ValidateCredentials(string userName, string password, ContextOptions options)
		{
			this.CheckDisposed();
			if ((userName != null || password == null) && (userName == null || password != null))
			{
				if (options == ContextOptions.Negotiate || this.contextType != ContextType.Machine)
				{
					return this.credValidate.Validate(userName, password, options);
				}
				else
				{
					throw new ArgumentException(StringResources.ContextOptionsNotValidForMachineStore);
				}
			}
			else
			{
				throw new ArgumentException(StringResources.ContextBadUserPwdCombo);
			}
		}
Exemple #40
0
		public PrincipalContext(ContextType contextType, string name, string container, ContextOptions options, string userName, string password)
		{
			this.initializationLock = new object();
			if ((userName != null || password == null) && (userName == null || password != null))
			{
				if ((options & -64) == 0)
				{
					if (contextType != ContextType.Machine || (options & (ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer | ContextOptions.Signing | ContextOptions.Sealing | ContextOptions.ServerBind)) == 0)
					{
						if ((contextType == ContextType.Domain || contextType == ContextType.ApplicationDirectory) && ((options & (ContextOptions.Negotiate | ContextOptions.SimpleBind)) == 0 || (options & (ContextOptions.Negotiate | ContextOptions.SimpleBind)) == (ContextOptions.Negotiate | ContextOptions.SimpleBind)))
						{
							throw new ArgumentException(StringResources.InvalidContextOptionsForAD);
						}
						else
						{
							if (contextType == ContextType.Machine || contextType == ContextType.Domain || contextType == ContextType.ApplicationDirectory)
							{
								if (contextType != ContextType.Machine || container == null)
								{
									if (contextType != ContextType.ApplicationDirectory || !string.IsNullOrEmpty(container) && !string.IsNullOrEmpty(name))
									{
										this.contextType = contextType;
										this.name = name;
										this.container = container;
										this.options = options;
										this.username = userName;
										this.password = password;
										this.DoServerVerifyAndPropRetrieval();
										this.credValidate = new CredentialValidator(contextType, name, this.serverProperties);
										return;
									}
									else
									{
										throw new ArgumentException(StringResources.ContextNoContainerForApplicationDirectoryCtx);
									}
								}
								else
								{
									throw new ArgumentException(StringResources.ContextNoContainerForMachineCtx);
								}
							}
							else
							{
								throw new InvalidEnumArgumentException("contextType", contextType, typeof(ContextType));
							}
						}
					}
					else
					{
						throw new ArgumentException(StringResources.InvalidContextOptionsForMachine);
					}
				}
				else
				{
					throw new InvalidEnumArgumentException("options", options, typeof(ContextOptions));
				}
			}
			else
			{
				throw new ArgumentException(StringResources.ContextBadUserPwdCombo);
			}
		}
 public PrincipalContextFull(ContextType contextType, string name, string container, ContextOptions options,
     string userName, string password)
     : base(contextType, name, container, options, userName, password)
 {
 }
Exemple #42
0
        public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions)
        {
            string contextName = name;
            string userName = null;
            bool explicitCreds = false;
            if (credentials != null && credentials.UserName != null)
            {
                if (credentials.Domain != null)
                    userName = credentials.Domain + "\\" + credentials.UserName;
                else
                    userName = credentials.UserName;

                explicitCreds = true;
            }
            else
            {
                userName = Utils.GetNT4UserName();
            }

            GlobalDebug.WriteLineIf(
                        GlobalDebug.Info,
                        "SDSCache",
                        "GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}",
                        name,
                        userName,
                        explicitCreds.ToString(),
                        contextOptions.ToString());

            if (!_isSAM)
            {
                // Determine the domain DNS name

                // DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY
                int flags = unchecked((int)(0x40000000 | 0x00000010 | 0x00000100));
                UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags);
                contextName = info.DomainName;
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName);

            ManualResetEvent contextReadyEvent = null;

            while (true)
            {
                Hashtable credTable = null;
                PrincipalContext ctx = null;

                // Wait for the PrincipalContext to be ready
                if (contextReadyEvent != null)
                {
                    GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting");

                    contextReadyEvent.WaitOne();
                }

                contextReadyEvent = null;

                lock (_tableLock)
                {
                    CredHolder credHolder = (CredHolder)_table[contextName];

                    if (credHolder != null)
                    {
                        GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName);

                        credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
                        Debug.Assert(credTable != null);

                        object o = credTable[userName];

                        if (o is Placeholder)
                        {
                            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder");

                            // A PrincipalContext is currently being constructed by another thread.
                            // Wait for it.
                            contextReadyEvent = ((Placeholder)o).contextReadyEvent;
                            continue;
                        }

                        WeakReference refToContext = o as WeakReference;
                        if (refToContext != null)
                        {
                            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null");

                            ctx = (PrincipalContext)refToContext.Target;  // null if GC'ed

                            // If the PrincipalContext hasn't been GCed or disposed, use it.
                            // Otherwise, we'll need to create a new one
                            if (ctx != null && ctx.Disposed == false)
                            {
                                GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext");
                                return ctx;
                            }
                            else
                            {
                                GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing");
                                credTable.Remove(userName);
                            }
                        }
                    }

                    // Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable
                    // are non-null (contexts exist, but none for the userName).  Either way, we need to create a PrincipalContext.

                    if (credHolder == null)
                    {
                        GlobalDebug.WriteLineIf(
                                GlobalDebug.Info,
                                "SDSCache",
                                "GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString());

                        // No contexts exist for the contextName.  Create a CredHolder for the contextName so we have a place
                        // to store the PrincipalContext we'll be creating.
                        credHolder = new CredHolder();
                        _table[contextName] = credHolder;

                        credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
                    }

                    // Put a placeholder on the contextName/userName slot, so that other threads that come along after
                    // we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us
                    credTable[userName] = new Placeholder();
                }

                // Now we just need to create a PrincipalContext for the contextName and credentials
                GlobalDebug.WriteLineIf(
                        GlobalDebug.Info,
                        "SDSCache",
                        "GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString());

                ctx = new PrincipalContext(
                                (_isSAM ? ContextType.Machine : ContextType.Domain),
                                contextName,
                                null,
                                contextOptions,
                                (credentials != null ? credentials.UserName : null),
                                (credentials != null ? credentials.Password : null)
                                );

                lock (_tableLock)
                {
                    Placeholder placeHolder = (Placeholder)credTable[userName];

                    // Replace the placeholder with the newly-created PrincipalContext
                    credTable[userName] = new WeakReference(ctx);

                    // Signal waiting threads to continue.  We do this after inserting the PrincipalContext
                    // into the table, so that the PrincipalContext is ready as soon as the other threads wake up.
                    // (Actually, the order probably doesn't matter, since even if we did it in the
                    // opposite order and the other thread woke up before we inserted the PrincipalContext, it would
                    // just block as soon as it tries to acquire the tableLock that we're currently holding.)
                    bool f = placeHolder.contextReadyEvent.Set();
                    Debug.Assert(f == true);
                }

                return ctx;
            }
        }
Exemple #43
0
        public PrincipalContext(
                    ContextType contextType, string name, string container, ContextOptions options, string userName, string password)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering ctor");

            if ((userName == null && password != null) ||
                (userName != null && password == null))
                throw new ArgumentException(StringResources.ContextBadUserPwdCombo);

            if ((options & ~(ContextOptions.Signing | ContextOptions.Negotiate | ContextOptions.Sealing | ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind | ContextOptions.ServerBind)) != 0)
                throw new InvalidEnumArgumentException("options", (int)options, typeof(ContextOptions));

            if (contextType == ContextType.Machine && ((options & ~ContextOptions.Negotiate) != 0))
            {
                throw new ArgumentException(StringResources.InvalidContextOptionsForMachine);
            }

            if ((contextType == ContextType.Domain || contextType == ContextType.ApplicationDirectory) &&
                (((options & (ContextOptions.Negotiate | ContextOptions.SimpleBind)) == 0) ||
                (((options & (ContextOptions.Negotiate | ContextOptions.SimpleBind)) == ((ContextOptions.Negotiate | ContextOptions.SimpleBind))))))
            {
                throw new ArgumentException(StringResources.InvalidContextOptionsForAD);
            }

            if ((contextType != ContextType.Machine) &&
                (contextType != ContextType.Domain) &&
                (contextType != ContextType.ApplicationDirectory)
#if TESTHOOK                
                && (contextType != ContextType.Test)
#endif
                )
            {
                throw new InvalidEnumArgumentException("contextType", (int)contextType, typeof(ContextType));
            }

            if ((contextType == ContextType.Machine) && (container != null))
                throw new ArgumentException(StringResources.ContextNoContainerForMachineCtx);

            if ((contextType == ContextType.ApplicationDirectory) && ((String.IsNullOrEmpty(container)) || (String.IsNullOrEmpty(name))))
                throw new ArgumentException(StringResources.ContextNoContainerForApplicationDirectoryCtx);

            _contextType = contextType;
            _name = name;
            _container = container;
            _options = options;

            _username = userName;
            _password = password;

            DoServerVerifyAndPropRetrieval();

            _credValidate = new CredentialValidator(contextType, name, _serverProperties);
        }
Exemple #44
0
        // Throws exception if ctxBase is not a computer object
        public SAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, ContextOptions options)
        {
            Debug.Assert(ctxBase != null);
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Constructing SAMStoreCtx for {0}", ctxBase.Path);

            Debug.Assert(SAMUtils.IsOfObjectClass(ctxBase, "Computer"));

            _ctxBase = ctxBase;
            _ownCtxBase = ownCtxBase;

            if (username != null && password != null)
                _credentials = new NetCred(username, password);

            _contextOptions = options;
            _authTypes = SDSUtils.MapOptionsToAuthTypes(options);
        }
Exemple #45
0
        /// <summary>
        /// Validate the passed credentials against the directory supplied.
        //   The supplied options will determine the directory method for credential validation.
        /// </summary>
        public bool ValidateCredentials(string userName, string password, ContextOptions options)
        {
            // Perform credential validation using fast concurrent bind...            
            CheckDisposed();

            if ((userName == null && password != null) ||
                (userName != null && password == null))
                throw new ArgumentException(StringResources.ContextBadUserPwdCombo);

            if (options != ContextOptions.Negotiate && _contextType == ContextType.Machine)
                throw new ArgumentException(StringResources.ContextOptionsNotValidForMachineStore);

#if TESTHOOK
                if ( contextType == ContextType.Test )
                {
                    return true;
                }
#endif

            return (_credValidate.Validate(userName, password, options));
        }
		static DefaultContextOptions()
		{
			DefaultContextOptions.MachineDefaultContextOption = ContextOptions.Negotiate;
			DefaultContextOptions.ADDefaultContextOption = ContextOptions.Negotiate | ContextOptions.Signing | ContextOptions.Sealing;
		}
Exemple #47
0
        internal AuthZSet(
                    byte[] userSid,
                    NetCred credentials,
                    ContextOptions contextOptions,
                    string flatUserAuthority,
                    StoreCtx userStoreCtx,
                    object userCtxBase)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                    "AuthZSet",
                                    "AuthZSet: SID={0}, authority={1}, storeCtx={2}",
                                    Utils.ByteArrayToString(userSid),
                                    flatUserAuthority,
                                    userStoreCtx.GetType());

            _userType = userStoreCtx.OwningContext.ContextType;
            _userCtxBase = userCtxBase;
            _userStoreCtx = userStoreCtx;
            _credentials = credentials;
            _contextOptions = contextOptions;

            // flatUserAuthority is flat domain name if userType == Domain,
            // flat host name if userType == LocalMachine
            _flatUserAuthority = flatUserAuthority;

            // Preload the PrincipalContext cache with the user's PrincipalContext
            _contexts[flatUserAuthority] = userStoreCtx.OwningContext;

            IntPtr hUser = IntPtr.Zero;

            //
            // Get the SIDs of the groups to which the user belongs
            //

            IntPtr pClientContext = IntPtr.Zero;
            IntPtr pResManager = IntPtr.Zero;
            IntPtr pBuffer = IntPtr.Zero;

            try
            {
                UnsafeNativeMethods.LUID luid = new UnsafeNativeMethods.LUID();
                luid.low = 0;
                luid.high = 0;

                _psMachineSid = new SafeMemoryPtr(Utils.GetMachineDomainSid());
                _psUserSid = new SafeMemoryPtr(Utils.ConvertByteArrayToIntPtr(userSid));

                bool f;
                int lastError = 0;

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Initializing resource manager");

                // Create a resource manager
                f = UnsafeNativeMethods.AuthzInitializeResourceManager(
                                            UnsafeNativeMethods.AUTHZ_RM_FLAG.AUTHZ_RM_FLAG_NO_AUDIT,
                                            IntPtr.Zero,
                                            IntPtr.Zero,
                                            IntPtr.Zero,
                                            null,
                                            out pResManager
                                            );

                if (f)
                {
                    GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting ctx from SID");

                    // Construct a context for the user based on the user's SID
                    f = UnsafeNativeMethods.AuthzInitializeContextFromSid(
                                                0,                  // default flags
                                                _psUserSid.DangerousGetHandle(),
                                                pResManager,
                                                IntPtr.Zero,
                                                luid,
                                                IntPtr.Zero,
                                                out pClientContext
                                                );

                    if (f)
                    {
                        int bufferSize = 0;

                        GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx");

                        // Extract the group SIDs from the user's context.  Determine the size of the buffer we need.
                        f = UnsafeNativeMethods.AuthzGetInformationFromContext(
                                                    pClientContext,
                                                    2,	                // AuthzContextInfoGroupsSids 
                                                    0,
                                                    out bufferSize,
                                                    IntPtr.Zero
                                                    );
                        if (!f && (bufferSize > 0) && (Marshal.GetLastWin32Error() == 122) /*ERROR_INSUFFICIENT_BUFFER*/)
                        {
                            GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Getting info from ctx (size={0})", bufferSize);

                            Debug.Assert(bufferSize > 0);

                            // Set up the needed buffer
                            pBuffer = Marshal.AllocHGlobal(bufferSize);

                            // Extract the group SIDs from the user's context, into our buffer.0
                            f = UnsafeNativeMethods.AuthzGetInformationFromContext(
                                                        pClientContext,
                                                        2,	                // AuthzContextInfoGroupsSids 
                                                        bufferSize,
                                                        out bufferSize,
                                                        pBuffer
                                                        );

                            if (f)
                            {
                                // Marshall the native buffer into managed SID_AND_ATTR structures.
                                // The native buffer holds a TOKEN_GROUPS structure:
                                //
                                //        struct TOKEN_GROUPS {
                                //                DWORD GroupCount;
                                //                SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY];
                                //        };
                                //

                                // Extract TOKEN_GROUPS.GroupCount                

                                UnsafeNativeMethods.TOKEN_GROUPS tokenGroups = (UnsafeNativeMethods.TOKEN_GROUPS)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_GROUPS));

                                int groupCount = tokenGroups.groupCount;

                                GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "Found {0} groups", groupCount);

                                // Extract TOKEN_GROUPS.Groups, by iterating over the array and marshalling
                                // each native SID_AND_ATTRIBUTES into a managed SID_AND_ATTR.
                                UnsafeNativeMethods.SID_AND_ATTR[] groups = new UnsafeNativeMethods.SID_AND_ATTR[groupCount];

                                IntPtr currentItem = new IntPtr(pBuffer.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.TOKEN_GROUPS)) - Marshal.SizeOf(typeof(IntPtr)));

                                for (int i = 0; i < groupCount; i++)
                                {
                                    groups[i] = (UnsafeNativeMethods.SID_AND_ATTR)Marshal.PtrToStructure(currentItem, typeof(UnsafeNativeMethods.SID_AND_ATTR));

                                    currentItem = new IntPtr(currentItem.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.SID_AND_ATTR)));
                                }

                                _groupSidList = new SidList(groups);
                            }
                            else
                            {
                                lastError = Marshal.GetLastWin32Error();
                            }
                        }
                        else
                        {
                            lastError = Marshal.GetLastWin32Error();
                            // With a zero-length buffer, this should have never succeeded
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        lastError = Marshal.GetLastWin32Error();
                    }
                }
                else
                {
                    lastError = Marshal.GetLastWin32Error();
                }

                if (!f)
                {
                    GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "Failed to retrieve group list, {0}", lastError);

                    throw new PrincipalOperationException(
                                    String.Format(
                                            CultureInfo.CurrentCulture,
                                            StringResources.AuthZFailedToRetrieveGroupList,
                                            lastError));
                }

                // Save off the buffer since it still holds the native SIDs referenced by SidList
                _psBuffer = new SafeMemoryPtr(pBuffer);
                pBuffer = IntPtr.Zero;
            }
            catch (Exception e)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Error, "AuthZSet", "Caught exception {0} with message {1}", e.GetType(), e.Message);

                if (_psBuffer != null && !_psBuffer.IsInvalid)
                    _psBuffer.Close();

                if (_psUserSid != null && !_psUserSid.IsInvalid)
                    _psUserSid.Close();

                if (_psMachineSid != null && !_psMachineSid.IsInvalid)
                    _psMachineSid.Close();

                // We're on a platform that doesn't have the AuthZ library
                if (e is DllNotFoundException)
                    throw new NotSupportedException(StringResources.AuthZNotSupported, e);

                if (e is EntryPointNotFoundException)
                    throw new NotSupportedException(StringResources.AuthZNotSupported, e);

                throw;
            }
            finally
            {
                if (pClientContext != IntPtr.Zero)
                    UnsafeNativeMethods.AuthzFreeContext(pClientContext);

                if (pResManager != IntPtr.Zero)
                    UnsafeNativeMethods.AuthzFreeResourceManager(pResManager);

                if (pBuffer != IntPtr.Zero)
                    Marshal.FreeHGlobal(pBuffer);
            }
        }
Exemple #48
0
		public ADAMStoreCtx(DirectoryEntry ctxBase, bool ownCtxBase, string username, string password, string serverName, ContextOptions options) : base(ctxBase, ownCtxBase, username, password, options)
		{
			this.objectListLock = new object();
			this.userSuppliedServerName = serverName;
		}
Exemple #49
0
		public bool Validate(string userName, string password, ContextOptions connectionMethod)
		{
			bool flag;
			if (userName == null || userName.Length != 0)
			{
				if (this.contextType == ContextType.Domain || this.contextType == ContextType.ApplicationDirectory)
				{
					try
					{
						NetworkCredential networkCredential = new NetworkCredential(userName, password);
						this.BindLdap(networkCredential, connectionMethod);
						flag = true;
					}
					catch (LdapException ldapException1)
					{
						LdapException ldapException = ldapException1;
						if ((long)ldapException.ErrorCode != (long)ExceptionHelper.ERROR_LOGON_FAILURE)
						{
							throw;
						}
						else
						{
							flag = false;
						}
					}
					return flag;
				}
				else
				{
					return this.BindSam(this.serverName, userName, password);
				}
			}
			else
			{
				return false;
			}
		}
Exemple #50
0
        private bool BindLdap(NetworkCredential creds, ContextOptions contextOptions)
        {
            LdapConnection current = null;
            bool useSSL = (ContextOptions.SecureSocketLayer & contextOptions) > 0;

            if (_contextType == ContextType.ApplicationDirectory)
            {
                _directoryIdent = new LdapDirectoryIdentifier(_serverProperties.dnsHostName, useSSL ? _serverProperties.portSSL : _serverProperties.portLDAP);
            }
            else
            {
                _directoryIdent = new LdapDirectoryIdentifier(_serverName, useSSL ? LdapConstants.LDAP_SSL_PORT : LdapConstants.LDAP_PORT);
            }

            bool attemptFastConcurrent = useSSL && _fastConcurrentSupported;
            int index = Convert.ToInt32(attemptFastConcurrent) * 2 + Convert.ToInt32(useSSL);

            if (!_connCache.Contains(index))
            {
                lock (_cacheLock)
                {
                    if (!_connCache.Contains(index))
                    {
                        current = new LdapConnection(_directoryIdent);
                        // First attempt to turn on SSL
                        current.SessionOptions.SecureSocketLayer = useSSL;

                        if (attemptFastConcurrent)
                        {
                            try
                            {
                                current.SessionOptions.FastConcurrentBind();
                            }
                            catch (PlatformNotSupportedException)
                            {
                                current.Dispose();
                                current = null;
                                _fastConcurrentSupported = false;
                                index = Convert.ToInt32(useSSL);
                                current = new LdapConnection(_directoryIdent);
                                // We have fallen back to another connection so we need to set SSL again.
                                current.SessionOptions.SecureSocketLayer = useSSL;
                            }
                        }

                        _connCache.Add(index, current);
                    }
                    else
                    {
                        current = (LdapConnection)_connCache[index];
                    }
                }
            }
            else
            {
                current = (LdapConnection)_connCache[index];
            }

            // If we are performing fastConcurrentBind there is no need to prevent multithreadaccess.  FSB is thread safe and multi cred safe
            // FSB also always has the same contextoptions so there is no need to lock the code that is modifying the current connection
            if (attemptFastConcurrent && _fastConcurrentSupported)
            {
                lockedLdapBind(current, creds, contextOptions);
            }
            else
            {
                lock (_cacheLock)
                {
                    lockedLdapBind(current, creds, contextOptions);
                }
            }
            return true;
        }
Exemple #51
0
		public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions)
		{
			string nT4UserName;
			PrincipalContext target;
			PrincipalContext principalContext;
			ContextType contextType;
			string userName;
			string password;
			Hashtable hashtables;
			Hashtable hashtables1;
			string domainName = name;
			bool flag = false;
			if (credentials == null || credentials.UserName == null)
			{
				nT4UserName = Utils.GetNT4UserName();
			}
			else
			{
				if (credentials.Domain == null)
				{
					nT4UserName = credentials.UserName;
				}
				else
				{
					nT4UserName = string.Concat(credentials.Domain, "\\", credentials.UserName);
				}
				flag = true;
			}
			if (!this.isSAM)
			{
				int num = 0x40000110;
				UnsafeNativeMethods.DomainControllerInfo dcName = Utils.GetDcName(null, domainName, null, num);
				domainName = dcName.DomainName;
			}
			ManualResetEvent manualResetEvent = null;
			while (true)
			{
				Hashtable hashtables2 = null;
				if (manualResetEvent != null)
				{
					manualResetEvent.WaitOne();
				}
				manualResetEvent = null;
				lock (this.tableLock)
				{
					SDSCache.CredHolder item = (SDSCache.CredHolder)this.table[domainName];
					if (item != null)
					{
						if (flag)
						{
							hashtables1 = item.explicitCreds;
						}
						else
						{
							hashtables1 = item.defaultCreds;
						}
						hashtables2 = hashtables1;
						object obj = hashtables2[nT4UserName];
						if (obj as SDSCache.Placeholder == null)
						{
							WeakReference weakReference = obj as WeakReference;
							if (weakReference != null)
							{
								target = (PrincipalContext)weakReference.Target;
								if (target == null || target.Disposed)
								{
									hashtables2.Remove(nT4UserName);
								}
								else
								{
									principalContext = target;
									break;
								}
							}
						}
						else
						{
							manualResetEvent = ((SDSCache.Placeholder)obj).contextReadyEvent;
							continue;
						}
					}
					if (item == null)
					{
						item = new SDSCache.CredHolder();
						this.table[domainName] = item;
						if (flag)
						{
							hashtables = item.explicitCreds;
						}
						else
						{
							hashtables = item.defaultCreds;
						}
						hashtables2 = hashtables;
					}
					hashtables2[nT4UserName] = new SDSCache.Placeholder();
					if (this.isSAM)
					{
						contextType = ContextType.Machine;
					}
					else
					{
						contextType = ContextType.Domain;
					}
					string str = domainName;
					object obj1 = null;
					ContextOptions contextOption = contextOptions;
					if (credentials != null)
					{
						userName = credentials.UserName;
					}
					else
					{
						userName = null;
					}
					if (credentials != null)
					{
						password = credentials.Password;
					}
					else
					{
						password = null;
					}
					target = new PrincipalContext(contextType, str, obj1, contextOption, userName, password);
					lock (this.tableLock)
					{
						SDSCache.Placeholder placeholder = (SDSCache.Placeholder)hashtables2[nT4UserName];
						hashtables2[nT4UserName] = new WeakReference(target);
						placeholder.contextReadyEvent.Set();
					}
					return target;
				}
			}
			return principalContext;
		}
Exemple #52
0
 private void lockedLdapBind(LdapConnection current, NetworkCredential creds, ContextOptions contextOptions)
 {
     current.AuthType = ((ContextOptions.SimpleBind & contextOptions) > 0 ? AuthType.Basic : AuthType.Negotiate);
     current.SessionOptions.Signing = ((ContextOptions.Signing & contextOptions) > 0 ? true : false);
     current.SessionOptions.Sealing = ((ContextOptions.Sealing & contextOptions) > 0 ? true : false);
     if ((null == creds.UserName) && (null == creds.Password))
     {
         current.Bind();
     }
     else
     {
         current.Bind(creds);
     }
 }
Exemple #53
0
		internal AuthZSet(byte[] userSid, NetCred credentials, ContextOptions contextOptions, string flatUserAuthority, StoreCtx userStoreCtx, object userCtxBase)
		{
			this.currentGroup = -1;
			this.contexts = new Hashtable();
			this.localMachineIsDC = null;
			this.userType = userStoreCtx.OwningContext.ContextType;
			this.userCtxBase = userCtxBase;
			this.userStoreCtx = userStoreCtx;
			this.credentials = credentials;
			this.contextOptions = contextOptions;
			this.flatUserAuthority = flatUserAuthority;
			this.contexts[flatUserAuthority] = userStoreCtx.OwningContext;
			IntPtr zero = IntPtr.Zero;
			IntPtr intPtr = IntPtr.Zero;
			IntPtr zero1 = IntPtr.Zero;
			try
			{
				try
				{
					UnsafeNativeMethods.LUID lUID = new UnsafeNativeMethods.LUID();
					lUID.low = 0;
					lUID.high = 0;
					this.psMachineSid = new AuthZSet.SafeMemoryPtr(Utils.GetMachineDomainSid());
					this.psUserSid = new AuthZSet.SafeMemoryPtr(Utils.ConvertByteArrayToIntPtr(userSid));
					int lastWin32Error = 0;
					bool flag = UnsafeNativeMethods.AuthzInitializeResourceManager(UnsafeNativeMethods.AUTHZ_RM_FLAG.AUTHZ_RM_FLAG_NO_AUDIT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, null, out intPtr);
					if (!flag)
					{
						lastWin32Error = Marshal.GetLastWin32Error();
					}
					else
					{
						flag = UnsafeNativeMethods.AuthzInitializeContextFromSid(0, this.psUserSid.DangerousGetHandle(), intPtr, IntPtr.Zero, lUID, IntPtr.Zero, out zero);
						if (!flag)
						{
							lastWin32Error = Marshal.GetLastWin32Error();
						}
						else
						{
							int num = 0;
							flag = UnsafeNativeMethods.AuthzGetInformationFromContext(zero, 2, 0, out num, IntPtr.Zero);
							if (flag || num <= 0 || Marshal.GetLastWin32Error() != 122)
							{
								lastWin32Error = Marshal.GetLastWin32Error();
							}
							else
							{
								zero1 = Marshal.AllocHGlobal(num);
								flag = UnsafeNativeMethods.AuthzGetInformationFromContext(zero, 2, num, out num, zero1);
								if (!flag)
								{
									lastWin32Error = Marshal.GetLastWin32Error();
								}
								else
								{
									UnsafeNativeMethods.TOKEN_GROUPS structure = (UnsafeNativeMethods.TOKEN_GROUPS)Marshal.PtrToStructure(zero1, typeof(UnsafeNativeMethods.TOKEN_GROUPS));
									int num1 = structure.groupCount;
									UnsafeNativeMethods.SID_AND_ATTR[] sIDANDATTRArray = new UnsafeNativeMethods.SID_AND_ATTR[num1];
									IntPtr intPtr1 = new IntPtr(zero1.ToInt64() + (long)Marshal.SizeOf(typeof(UnsafeNativeMethods.TOKEN_GROUPS)) - (long)Marshal.SizeOf(typeof(IntPtr)));
									for (int i = 0; i < num1; i++)
									{
										sIDANDATTRArray[i] = (UnsafeNativeMethods.SID_AND_ATTR)Marshal.PtrToStructure(intPtr1, typeof(UnsafeNativeMethods.SID_AND_ATTR));
										intPtr1 = new IntPtr(intPtr1.ToInt64() + (long)Marshal.SizeOf(typeof(UnsafeNativeMethods.SID_AND_ATTR)));
									}
									this.groupSidList = new SidList(sIDANDATTRArray);
								}
							}
						}
					}
					if (flag)
					{
						this.psBuffer = new AuthZSet.SafeMemoryPtr(zero1);
						zero1 = IntPtr.Zero;
					}
					else
					{
						object[] objArray = new object[1];
						objArray[0] = lastWin32Error;
						throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.AuthZFailedToRetrieveGroupList, objArray));
					}
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					if (this.psBuffer != null && !this.psBuffer.IsInvalid)
					{
						this.psBuffer.Close();
					}
					if (this.psUserSid != null && !this.psUserSid.IsInvalid)
					{
						this.psUserSid.Close();
					}
					if (this.psMachineSid != null && !this.psMachineSid.IsInvalid)
					{
						this.psMachineSid.Close();
					}
					if (exception as DllNotFoundException == null)
					{
						if (exception as EntryPointNotFoundException == null)
						{
							throw;
						}
						else
						{
							throw new NotSupportedException(StringResources.AuthZNotSupported, exception);
						}
					}
					else
					{
						throw new NotSupportedException(StringResources.AuthZNotSupported, exception);
					}
				}
			}
			finally
			{
				if (zero != IntPtr.Zero)
				{
					UnsafeNativeMethods.AuthzFreeContext(zero);
				}
				if (intPtr != IntPtr.Zero)
				{
					UnsafeNativeMethods.AuthzFreeResourceManager(intPtr);
				}
				if (zero1 != IntPtr.Zero)
				{
					Marshal.FreeHGlobal(zero1);
				}
			}
		}
        private static ContextOptions SetBindingOptions(IEnumerable<ITaskItem> value)
        {
            ContextOptions s = new ContextOptions();
            foreach (ITaskItem option in value)
            {
                s |= (ContextOptions)Enum.Parse(typeof(ContextOptions), option.ItemSpec);
            }

            return s;
        }