コード例 #1
0
        internal void ValidateCreateContext(
            string package,
            NetworkCredential credential,
            string servicePrincipalName,
            ExtendedProtectionPolicy policy,
            ProtectionLevel protectionLevel,
            TokenImpersonationLevel impersonationLevel)
        {
            if (policy != null)
            {
                // One of these must be set if EP is turned on
                if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null)
                {
                    throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy));
                }

                _extendedProtectionPolicy = policy;
            }
            else
            {
                _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);
            }

            ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel);
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: huoxudong125/WCF-Demo
 public static WindowsIdentity CreateWindowsIdentity(string userName, string password, TokenImpersonationLevel tokenImpersonationLevel)
 {
     IntPtr token = IntPtr.Zero;
     IntPtr duplicateToken = IntPtr.Zero;
     if (LogonUser(userName, string.Empty, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))
     {
         int impersonationLevel;
         switch (tokenImpersonationLevel)
         {
             case TokenImpersonationLevel.Anonymous:
                 { impersonationLevel = 0; break; }
             case TokenImpersonationLevel.Impersonation:
                 { impersonationLevel = 2; break; }
             case TokenImpersonationLevel.Delegation:
                 { impersonationLevel = 3; break; }
             default:
                 { impersonationLevel = 1; break; }
         }
         if (DuplicateToken(token, impersonationLevel, ref duplicateToken))
         {
             return new WindowsIdentity(duplicateToken);
         }
         else
         {
             throw new InvalidOperationException(string.Format("创建模拟令牌失败 (错误代码: {0}) ", Marshal.GetLastWin32Error()));
         }
     }
     else
     {
         throw new InvalidOperationException(string.Format("用户登录失败 (错误代码: {0}) ", Marshal.GetLastWin32Error()));
     }
 }
        internal static int Compare(TokenImpersonationLevel x, TokenImpersonationLevel y)
        {
            int num = 0;
            if (x == y)
            {
                return num;
            }
            switch (x)
            {
                case TokenImpersonationLevel.Identification:
                    return -1;

                case TokenImpersonationLevel.Impersonation:
                    switch (y)
                    {
                        case TokenImpersonationLevel.Identification:
                            return 1;

                        case TokenImpersonationLevel.Delegation:
                            return -1;
                    }
                    break;

                case TokenImpersonationLevel.Delegation:
                    return 1;

                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("x", (int) x, typeof(TokenImpersonationLevel)));
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("y", (int) y, typeof(TokenImpersonationLevel)));
        }
コード例 #4
0
 //
 public virtual void AuthenticateAsClient( NetworkCredential       credential,
                                         string                  targetName,
                                         ProtectionLevel         requiredProtectionLevel,   //this will be the ultimate result or exception
                                         TokenImpersonationLevel allowedImpersonationLevel) //this OR LOWER will be ultimate result in auth context
 {
     AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel);
 }
コード例 #5
0
 internal static void ValidateImpersonationLevel(TokenImpersonationLevel impersonationLevel)
 {
     if (impersonationLevel != TokenImpersonationLevel.Identification)
     {
         throw new ArgumentOutOfRangeException(nameof(impersonationLevel), impersonationLevel.ToString(),
             SR.net_auth_supported_impl_levels);
     }
 }
 internal static bool IsDefined(TokenImpersonationLevel value)
 {
     if (((value != TokenImpersonationLevel.None) && (value != TokenImpersonationLevel.Anonymous)) && ((value != TokenImpersonationLevel.Identification) && (value != TokenImpersonationLevel.Impersonation)))
     {
         return (value == TokenImpersonationLevel.Delegation);
     }
     return true;
 }
 public SspiSecurityToken(TokenImpersonationLevel impersonationLevel, bool allowNtlm, System.Net.NetworkCredential networkCredential)
 {
     this.impersonationLevel = impersonationLevel;
     this.allowNtlm = allowNtlm;
     this.networkCredential = System.ServiceModel.Security.SecurityUtils.GetNetworkCredentialsCopy(networkCredential);
     this.effectiveTime = DateTime.UtcNow;
     this.expirationTime = this.effectiveTime.AddHours(10.0);
 }
コード例 #8
0
ファイル: SspiSecurityToken.cs プロジェクト: smulholland2/wcf
 public SspiSecurityToken(TokenImpersonationLevel impersonationLevel, bool allowNtlm, NetworkCredential networkCredential)
 {
     _impersonationLevel = impersonationLevel;
     _allowNtlm = allowNtlm;
     _networkCredential = SecurityUtils.GetNetworkCredentialsCopy(networkCredential);
     _effectiveTime = DateTime.UtcNow;
     _expirationTime = _effectiveTime.AddHours(10);
 }
コード例 #9
0
 internal WindowsClientCredential(WindowsClientCredential other)
 {
     if (other._windowsCredentials != null)
         _windowsCredentials = SecurityUtils.GetNetworkCredentialsCopy(other._windowsCredentials);
     _allowedImpersonationLevel = other._allowedImpersonationLevel;
     _allowNtlm = other._allowNtlm;
     _isReadOnly = other._isReadOnly;
 }
 public SpnegoTokenProvider(System.IdentityModel.SafeFreeCredentials credentialsHandle, SecurityBindingElement securityBindingElement) : base(securityBindingElement)
 {
     this.allowedImpersonationLevel = TokenImpersonationLevel.Identification;
     this.identityVerifier = System.ServiceModel.Security.IdentityVerifier.CreateDefault();
     this.allowNtlm = true;
     this.authenticateServer = true;
     this.interactiveNegoExLogonEnabled = true;
     this.credentialsHandle = credentialsHandle;
 }
 static TokenImpersonationLevelHelper()
 {
     TokenImpersonationLevel[] levelArray = new TokenImpersonationLevel[5];
     levelArray[1] = TokenImpersonationLevel.Anonymous;
     levelArray[2] = TokenImpersonationLevel.Identification;
     levelArray[3] = TokenImpersonationLevel.Impersonation;
     levelArray[4] = TokenImpersonationLevel.Delegation;
     TokenImpersonationLevelOrder = levelArray;
 }
コード例 #12
0
ファイル: NegoState.Unix.cs プロジェクト: er0dr1guez/corefx
 internal void ValidateCreateContext(string package,
                                     NetworkCredential credential,
                                     string servicePrincipalName,
                                     ExtendedProtectionPolicy policy,
                                     ProtectionLevel protectionLevel,
                                     TokenImpersonationLevel impersonationLevel)
 {
     throw new PlatformNotSupportedException();
 }
コード例 #13
0
 public SpnegoTokenProvider(System.IdentityModel.SafeFreeCredentials credentialsHandle, SecurityBindingElement securityBindingElement) : base(securityBindingElement)
 {
     this.allowedImpersonationLevel = TokenImpersonationLevel.Identification;
     this.identityVerifier          = System.ServiceModel.Security.IdentityVerifier.CreateDefault();
     this.allowNtlm                     = true;
     this.authenticateServer            = true;
     this.interactiveNegoExLogonEnabled = true;
     this.credentialsHandle             = credentialsHandle;
 }
コード例 #14
0
		public SspiSecurityTokenProvider (NetworkCredential credential, 
			bool allowNtlm, TokenImpersonationLevel impersonationLevel)
		{
			if (credential == null)
				throw new ArgumentNullException ("credential");
			this.credential = credential;
			allow_ntlm = allowNtlm;
			impersonation_level = impersonationLevel;
		}
コード例 #15
0
 static TokenImpersonationLevelHelper()
 {
     TokenImpersonationLevel[] levelArray = new TokenImpersonationLevel[5];
     levelArray[1] = TokenImpersonationLevel.Anonymous;
     levelArray[2] = TokenImpersonationLevel.Identification;
     levelArray[3] = TokenImpersonationLevel.Impersonation;
     levelArray[4] = TokenImpersonationLevel.Delegation;
     TokenImpersonationLevelOrder = levelArray;
 }
コード例 #16
0
            public static NetworkCredential End(IAsyncResult result,
                                                out TokenImpersonationLevel impersonationLevel, out bool allowNtlm)
            {
                GetSspiCredentialAsyncResult thisPtr = AsyncResult.End <GetSspiCredentialAsyncResult>(result);

                impersonationLevel = thisPtr.impersonationLevel;
                allowNtlm          = thisPtr.allowNtlm;
                return(thisPtr.credential);
            }
コード例 #17
0
        /// <summary>
        /// Gets an X509 certificate.
        /// </summary>
        /// <param name="subjectOrThumbprint">Subject or Thumbprint string for the certificate to get.</param>
        /// <returns><see cref="X509Certificate2"/>.</returns>
        /// <exception cref="CryptographicException">Error getting certificate from the store.</exception>
        /// <exception cref="ConfigurationErrorsException">Number of certificates found is not exactly one.</exception>
        private static X509Certificate2 GetCertificate(string subjectOrThumbprint)
        {
            WindowsImpersonationContext context = null;

            try
            {
                // If the website is using impersonation use the configured Application Pool
                // account to access the certificate store.
                WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
                if (windowsIdentity != null)
                {
                    TokenImpersonationLevel impersonationLevel = windowsIdentity.ImpersonationLevel;

                    if (impersonationLevel == TokenImpersonationLevel.Delegation || impersonationLevel == TokenImpersonationLevel.Impersonation)
                    {
                        context = WindowsIdentity.Impersonate(IntPtr.Zero);
                    }
                }

                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);

                // Change: Product Backlog Item 10247: .NET Connector - support loading certificate by Thumbprint
                // By default find certificates using SubjectName
                X509FindType findType = X509FindType.FindBySubjectName;

                // Check to see if finding certificates by Thumbprint is activated in the configuration settings
                var findCertificatesByThumbprint = GetOptionalAppSetting("FindCertificatesByThumbprint", "False");
                if (findCertificatesByThumbprint.ToLowerInvariant().Equals("true"))
                {
                    findType = X509FindType.FindByThumbprint;
                }

                X509Certificate2Collection certs = store.Certificates.Find(findType, subjectOrThumbprint, false);
                if (certs.Count != 1)
                {
                    string errMsg = Format("Found {0} certificates by subject/thumbprint {1}, expected 1.", certs.Count, subjectOrThumbprint);
                    if (traceSwitch.TraceError)
                    {
                        TraceLine(errMsg);
                    }
                    throw new ConfigurationErrorsException(errMsg);
                }
                store.Close();

                return(certs[0]);
            }
            finally
            {
                if (context != null)
                {
                    context.Undo();
                }
            }
        }
 internal IpcClientTransportSink(string channelURI, IpcClientChannel channel)
 {
     string str;
     this.portCache = new ConnectionCache();
     this._tokenImpersonationLevel = TokenImpersonationLevel.Identification;
     this._timeout = 0x3e8;
     this._channel = channel;
     string str2 = IpcChannelHelper.ParseURL(channelURI, out str);
     int startIndex = str2.IndexOf("://") + 3;
     this._portName = str2.Substring(startIndex);
 }
コード例 #19
0
ファイル: WebRequestChannel.cs プロジェクト: nuxleus/WCFWeb
 public WebRequestChannel()
 {
     // Set HWR default values
     this.allowPipelining = true;
     this.authenticationLevel = AuthenticationLevel.MutualAuthRequested;
     this.cachePolicy = WebRequest.DefaultCachePolicy;
     this.impersonationLevel = TokenImpersonationLevel.Delegation;
     this.maxResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
     this.readWriteTimeout = 5 * 60 * 1000; // 5 minutes
     this.unsafeAuthenticatedConnectionSharing = false;
 }
コード例 #20
0
        public KerberosSecurityTokenProvider(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential)
        {
            if (tokenImpersonationLevel != TokenImpersonationLevel.Identification && tokenImpersonationLevel != TokenImpersonationLevel.Impersonation)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(tokenImpersonationLevel),
                                                                                                          SR.Format(SR.ImpersonationLevelNotSupported, tokenImpersonationLevel)));
            }

            ServicePrincipalName    = servicePrincipalName ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(servicePrincipalName));
            TokenImpersonationLevel = tokenImpersonationLevel;
            _networkCredential      = networkCredential;
        }
コード例 #21
0
ファイル: NegotiateStream.cs プロジェクト: ChuangYang/corefx
 private IAsyncResult BeginAuthenticateAsClient(
     NetworkCredential credential,
     string targetName,
     ProtectionLevel requiredProtectionLevel,
     TokenImpersonationLevel allowedImpersonationLevel,
     AsyncCallback asyncCallback,
     object asyncState)
 {
     return BeginAuthenticateAsClient(credential, null, targetName,
                                      requiredProtectionLevel, allowedImpersonationLevel,
                                      asyncCallback, asyncState);
 }
コード例 #22
0
ファイル: NegoState.Unix.cs プロジェクト: er0dr1guez/corefx
 internal void ValidateCreateContext(
                                     string package,
                                     bool isServer,
                                     NetworkCredential credential,
                                     string servicePrincipalName,
                                     ChannelBinding channelBinding,
                                     ProtectionLevel protectionLevel,
                                     TokenImpersonationLevel impersonationLevel
                                     )
 {
     throw new PlatformNotSupportedException();
 }
コード例 #23
0
ファイル: WebRequestHandler.cs プロジェクト: nlhepler/mono
		public WebRequestHandler ()
		{
			allowPipelining = true;
			authenticationLevel = AuthenticationLevel.MutualAuthRequested;
			cachePolicy = System.Net.WebRequest.DefaultCachePolicy;
			continueTimeout = TimeSpan.FromMilliseconds (350);
			impersonationLevel = TokenImpersonationLevel.Delegation;
			maxResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
			readWriteTimeout = 300000;
			serverCertificateValidationCallback = null;
			unsafeAuthenticatedConnectionSharing = false;
		}
 internal WindowsClientCredential(WindowsClientCredential other)
 {
     this.allowedImpersonationLevel = TokenImpersonationLevel.Identification;
     this.allowNtlm = true;
     if (other.windowsCredentials != null)
     {
         this.windowsCredentials = System.ServiceModel.Security.SecurityUtils.GetNetworkCredentialsCopy(other.windowsCredentials);
     }
     this.allowedImpersonationLevel = other.allowedImpersonationLevel;
     this.allowNtlm = other.allowNtlm;
     this.isReadOnly = other.isReadOnly;
 }
コード例 #25
0
        public void Copy(HttpDigestClientElement from)
        {
            if (this.IsReadOnly())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
            }
            if (null == from)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("from");
            }

            this.ImpersonationLevel = from.ImpersonationLevel;
        }
コード例 #26
0
        public void Copy(HttpDigestClientElement from)
        {
            if (this.IsReadOnly())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigReadOnly)));
            }
            if (null == from)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("from");
            }

            this.ImpersonationLevel = from.ImpersonationLevel;
        }
コード例 #27
0
        public KerberosSecurityTokenProvider(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential)
        {
            if (servicePrincipalName == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("servicePrincipalName");
            if (tokenImpersonationLevel != TokenImpersonationLevel.Identification && tokenImpersonationLevel != TokenImpersonationLevel.Impersonation)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenImpersonationLevel",
                    SR.GetString(SR.ImpersonationLevelNotSupported, tokenImpersonationLevel)));
            }

            this.servicePrincipalName = servicePrincipalName;
            this.tokenImpersonationLevel = tokenImpersonationLevel;
            this.networkCredential = networkCredential;
        }
コード例 #28
0
 public static void ValidateDigestCredential(NetworkCredential credential, TokenImpersonationLevel impersonationLevel)
 {
     if (!SecurityUtils.NetworkCredentialHelper.IsDefault(credential))
     {
         // With a non-default credential, Digest will not honor a client impersonation constraint of
         // TokenImpersonationLevel.Identification.
         if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevel,
                                                             TokenImpersonationLevel.Impersonation))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
                                                                                                         SR.DigestExplicitCredsImpersonationLevel, impersonationLevel)));
         }
     }
 }
コード例 #29
0
ファイル: WindowsIdentity.cs プロジェクト: voloda/corefx
        private bool CheckNtTokenForSid(SecurityIdentifier sid)
        {
            Contract.EndContractBlock();

            // special case the anonymous identity.
            if (_safeTokenHandle.IsInvalid)
            {
                return(false);
            }

            // CheckTokenMembership expects an impersonation token
            SafeAccessTokenHandle   token = SafeAccessTokenHandle.InvalidHandle;
            TokenImpersonationLevel til   = ImpersonationLevel;
            bool isMember = false;

            try
            {
                if (til == TokenImpersonationLevel.None)
                {
                    if (!Interop.mincore.DuplicateTokenEx(_safeTokenHandle,
                                                          (uint)TokenAccessLevels.Query,
                                                          IntPtr.Zero,
                                                          (uint)TokenImpersonationLevel.Identification,
                                                          (uint)TokenType.TokenImpersonation,
                                                          ref token))
                    {
                        throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
                    }
                }


                // CheckTokenMembership will check if the SID is both present and enabled in the access token.
                if (!Interop.mincore.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
                                                          sid.BinaryForm,
                                                          ref isMember))
                {
                    throw new SecurityException(Interop.mincore.GetMessage(Marshal.GetLastWin32Error()));
                }
            }
            finally
            {
                if (token != SafeAccessTokenHandle.InvalidHandle)
                {
                    token.Dispose();
                }
            }

            return(isMember);
        }
コード例 #30
0
ファイル: RpcTests.cs プロジェクト: fsdsabel/AdvancedRpc
        private async Task <IRpcServerChannel> CreateServer <T>(T instance, ChannelType channelType, IRpcSerializer serializer = null,
                                                                TokenImpersonationLevel tokenImpersonationLevel = TokenImpersonationLevel.None,
                                                                IRpcObjectRepository localRepository            = null) where T : class
        {
            if (serializer == null)
            {
                serializer = new BinaryRpcSerializer();
            }
            switch (channelType)
            {
            case ChannelType.Tcp:
            {
                var server = new TcpRpcServerChannel(
                    serializer,
                    new RpcMessageFactory(),
                    IPAddress.Loopback,
                    11234,
                    localRepository);
                if (instance != null)
                {
                    server.ObjectRepository.RegisterSingleton(instance);
                }
                await server.ListenAsync();

                return(server);
            }

            case ChannelType.NamedPipe:
            {
                _pipeName = Guid.NewGuid().ToString();
                var server = new NamedPipeRpcServerChannel(
                    serializer,
                    new RpcMessageFactory(),
                    _pipeName,
                    localRepository: localRepository);
                if (instance != null)
                {
                    server.ObjectRepository.RegisterSingleton(instance);
                }
                await server.ListenAsync();

                return(server);
            }

            default:
                throw new NotSupportedException();
            }
        }
コード例 #31
0
            private void CompleteGetToken(IAsyncResult result)
            {
                SspiSecurityToken token = (SspiSecurityToken)this.credentialProvider.EndGetToken(result);

                if (token != null)
                {
                    this.impersonationLevel = token.ImpersonationLevel;
                    this.allowNtlm          = token.AllowNtlm;
                    if (token.NetworkCredential != null)
                    {
                        this.credential = token.NetworkCredential;
                        System.ServiceModel.Security.SecurityUtils.FixNetworkCredential(ref this.credential);
                    }
                }
                this.EnsureCredentialInitialized();
            }
コード例 #32
0
        public KerberosSecurityTokenProvider(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential)
        {
            if (servicePrincipalName == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("servicePrincipalName");
            }
            if (tokenImpersonationLevel != TokenImpersonationLevel.Identification && tokenImpersonationLevel != TokenImpersonationLevel.Impersonation)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenImpersonationLevel",
                                                                                                          SR.GetString(SR.ImpersonationLevelNotSupported, tokenImpersonationLevel)));
            }

            this.servicePrincipalName    = servicePrincipalName;
            this.tokenImpersonationLevel = tokenImpersonationLevel;
            this.networkCredential       = networkCredential;
        }
コード例 #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OverlappingPipeClientStream"/> class.
 /// </summary>
 /// <param name="serverName">Name of the server.</param>
 /// <param name="pipeName">Name of the pipe.</param>
 /// <param name="transmissionMode"></param>
 /// <param name="impersonationLevel">The impersonation level.</param>
 /// <param name="inheritability">The inheritability.</param>
 public OverlappingPipeClientStream(
     [NotNull] string serverName,
     [NotNull] string pipeName,
     PipeTransmissionMode transmissionMode,
     TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None,
     HandleInheritability inheritability = HandleInheritability.None)
     : base(new NamedPipeClientStream(
                serverName,
                pipeName,
                PipeDirection.InOut,
                PipeOptions.Asynchronous,
                impersonationLevel,
                inheritability))
 {
     Debug.Assert(Stream != null);
     ReadMode = transmissionMode;
 }
 public NamedPipeClientStream(string serverName, string pipeName, PipeAccessRights desiredAccessRights, PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability) : base(DirectionFromRights(desiredAccessRights), 0)
 {
     if (pipeName == null)
     {
         throw new ArgumentNullException("pipeName");
     }
     if (serverName == null)
     {
         throw new ArgumentNullException("serverName", System.SR.GetString("ArgumentNull_ServerName"));
     }
     if (pipeName.Length == 0)
     {
         throw new ArgumentException(System.SR.GetString("Argument_NeedNonemptyPipeName"));
     }
     if (serverName.Length == 0)
     {
         throw new ArgumentException(System.SR.GetString("Argument_EmptyServerName"));
     }
     if ((options & ~(PipeOptions.Asynchronous | PipeOptions.WriteThrough)) != PipeOptions.None)
     {
         throw new ArgumentOutOfRangeException("options", System.SR.GetString("ArgumentOutOfRange_OptionsInvalid"));
     }
     if ((impersonationLevel < TokenImpersonationLevel.None) || (impersonationLevel > TokenImpersonationLevel.Delegation))
     {
         throw new ArgumentOutOfRangeException("impersonationLevel", System.SR.GetString("ArgumentOutOfRange_ImpersonationInvalid"));
     }
     if ((inheritability < HandleInheritability.None) || (inheritability > HandleInheritability.Inheritable))
     {
         throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
     }
     if ((desiredAccessRights & ~(PipeAccessRights.AccessSystemSecurity | PipeAccessRights.FullControl)) != 0)
     {
         throw new ArgumentOutOfRangeException("desiredAccessRights", System.SR.GetString("ArgumentOutOfRange_InvalidPipeAccessRights"));
     }
     this.m_normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
     if (string.Compare(this.m_normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0)
     {
         throw new ArgumentOutOfRangeException("pipeName", System.SR.GetString("ArgumentOutOfRange_AnonymousReserved"));
     }
     this.m_inheritability = inheritability;
     this.m_impersonationLevel = impersonationLevel;
     this.m_pipeOptions = options;
     this.m_access = (int) desiredAccessRights;
 }
コード例 #35
0
        internal static IpcPort Connect(string portName, bool secure, TokenImpersonationLevel impersonationLevel, int timeout)
        {
            string lpFileName = @"\\.\pipe\" + portName;
            uint num = 0x100000;
            if (secure)
            {
                switch (impersonationLevel)
                {
                    case TokenImpersonationLevel.None:
                        num = 0x100000;
                        break;

                    case TokenImpersonationLevel.Identification:
                        num = 0x110000;
                        break;

                    case TokenImpersonationLevel.Impersonation:
                        num = 0x120000;
                        break;

                    case TokenImpersonationLevel.Delegation:
                        num = 0x130000;
                        break;
                }
            }
            while (true)
            {
                PipeHandle handle = NativePipe.CreateFile(lpFileName, 0xc0000000, 3, IntPtr.Zero, 3, 0x40000080 | num, IntPtr.Zero);
                if (handle.Handle.ToInt32() != -1)
                {
                    return new IpcPort(portName, handle);
                }
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != 0xe7L)
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ConnectIpcFailed"), new object[] { GetMessage(errorCode) }));
                }
                if (!NativePipe.WaitNamedPipe(lpFileName, timeout))
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_Busy"), new object[] { GetMessage(errorCode) }));
                }
            }
        }
 internal TcpClientTransportSink(string channelURI, TcpClientChannel channel)
 {
     string str;
     this._socketCacheTimeout = TimeSpan.FromSeconds(10.0);
     this._spn = string.Empty;
     this._retryCount = 1;
     this._tokenImpersonationLevel = TokenImpersonationLevel.Identification;
     this._protectionLevel = ProtectionLevel.EncryptAndSign;
     this._channel = channel;
     string uriString = TcpChannelHelper.ParseURL(channelURI, out str);
     this.ClientSocketCache = new SocketCache(new SocketHandlerFactory(this.CreateSocketHandler), this._socketCachePolicy, this._socketCacheTimeout);
     Uri uri = new Uri(uriString);
     if (uri.IsDefaultPort)
     {
         throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_UrlMustHavePort"), new object[] { channelURI }));
     }
     this.m_machineName = uri.Host;
     this.m_port = uri.Port;
     this._machineAndPort = this.m_machineName + ":" + this.m_port;
 }
コード例 #37
0
 WindowsSspiNegotiation(bool isServer, string package, SafeFreeCredentials credentialsHandle, TokenImpersonationLevel impersonationLevel, string servicePrincipalName, bool doMutualAuth, bool interactiveLogonEnabled, bool ntlmEnabled)
 {
     this.tokenSize = SspiWrapper.GetVerifyPackageInfo(package).MaxToken;
     this.isServer = isServer;
     this.servicePrincipalName = servicePrincipalName;
     this.securityContext = null;
     if (isServer)
     {
         this.impersonationLevel = TokenImpersonationLevel.Delegation;
         this.doMutualAuth = false;
     }
     else
     {
         this.impersonationLevel = impersonationLevel;
         this.doMutualAuth = doMutualAuth;
         this.interactiveNegoLogonEnabled = interactiveLogonEnabled;
         this.clientPackageName = package;
         this.allowNtlm = ntlmEnabled;
     }
     this.credentialsHandle = credentialsHandle;
 }
コード例 #38
0
 public IpcPort GetConnection(string portName, bool secure, TokenImpersonationLevel level, int timeout)
 {
     PortConnection connection = null;
     lock (_connections)
     {
         bool flag = true;
         if (secure)
         {
             try
             {
                 WindowsIdentity current = WindowsIdentity.GetCurrent(true);
                 if (current != null)
                 {
                     flag = false;
                     current.Dispose();
                 }
             }
             catch (Exception)
             {
                 flag = false;
             }
         }
         if (flag)
         {
             connection = (PortConnection) _connections[portName];
         }
         if ((connection == null) || connection.Port.IsDisposed)
         {
             connection = new PortConnection(IpcPort.Connect(portName, secure, level, timeout)) {
                 Port = { Cacheable = flag }
             };
         }
         else
         {
             _connections.Remove(portName);
         }
     }
     return connection.Port;
 }
コード例 #39
0
        internal NamedPipeClientStream(String serverName, String pipeName, PipeDirection direction,
            PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
            : base(direction, 0)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (serverName == null)
            {
                throw new ArgumentNullException("serverName", SR.ArgumentNull_ServerName);
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if (serverName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyServerName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation)
            {
                throw new ArgumentOutOfRangeException("impersonationLevel", SR.ArgumentOutOfRange_ImpersonationInvalid);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            _normalizedPipePath = GetPipePath(serverName, pipeName);
            _direction = direction;
            _inheritability = inheritability;
            _impersonationLevel = impersonationLevel;
            _pipeOptions = options;
        }
 internal static bool IsGreaterOrEqual(TokenImpersonationLevel x, TokenImpersonationLevel y)
 {
     Validate(x);
     Validate(y);
     if (x == y)
     {
         return true;
     }
     int num = 0;
     int num2 = 0;
     for (int i = 0; i < TokenImpersonationLevelOrder.Length; i++)
     {
         if (x == TokenImpersonationLevelOrder[i])
         {
             num = i;
         }
         if (y == TokenImpersonationLevelOrder[i])
         {
             num2 = i;
         }
     }
     return (num > num2);
 }
コード例 #41
0
        internal KerberosRequestorSecurityToken(string servicePrincipalName, TokenImpersonationLevel tokenImpersonationLevel, NetworkCredential networkCredential, string id)
        {
            if (servicePrincipalName == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("servicePrincipalName");
            if (tokenImpersonationLevel != TokenImpersonationLevel.Identification && tokenImpersonationLevel != TokenImpersonationLevel.Impersonation)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("tokenImpersonationLevel",
                    SR.Format(SR.ImpersonationLevelNotSupported, tokenImpersonationLevel)));
            }
            if (id == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");

            _servicePrincipalName = servicePrincipalName;
            if (networkCredential != null && networkCredential != CredentialCache.DefaultNetworkCredentials)
            {
                if (string.IsNullOrEmpty(networkCredential.UserName))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.ProvidedNetworkCredentialsForKerberosHasInvalidUserName);
                }
                // Note: we don't check the domain, since Lsa accepts
                // FQ userName.
            }
            _id = id;
        }