Example #1
0
        public void GetThreadContext(ContextFlags flags, int contextBufferSize, out int contextSize, IntPtr contextBuffer)
        {
            uint uContextSize = 0;

            m_sw.GetContext((uint)flags, (uint)contextBufferSize, out uContextSize, contextBuffer);
            contextSize = (int)uContextSize;
        }
Example #2
0
        // returns the platform-specific Context Flags
        public ContextFlags GetPSFlags(AgnosticContextFlags flags)
        {
            // We know that we need an x86 context
            ContextFlags cFlags = ContextFlags.X86Context;

            if ((flags & AgnosticContextFlags.ContextInteger) == AgnosticContextFlags.ContextInteger)
            {
                // ContextInteger is the same for all platforms, so we can do a blanket |=
                cFlags |= (ContextFlags)AgnosticContextFlags.ContextInteger;
            }
            if ((flags & AgnosticContextFlags.ContextControl) == AgnosticContextFlags.ContextControl)
            {
                cFlags |= (ContextFlags)AgnosticContextFlags.ContextControl;
            }
            if ((flags & AgnosticContextFlags.ContextFloatingPoint) == AgnosticContextFlags.ContextFloatingPoint)
            {
                cFlags |= (ContextFlags)AgnosticContextFlags.ContextFloatingPoint;
            }
            if ((flags & AgnosticContextFlags.ContextAll) == AgnosticContextFlags.ContextAll)
            {
                // ContextAll is the same for all platforms, so we can do a blanket |=
                cFlags |= (ContextFlags)AgnosticContextFlags.ContextAll;
            }

            return(cFlags);
        }
 private void CheckIfFlagWasObtainedIfRequested(ContextFlags flag)
 {
     if ((this.m_RequestedFlags & flag) != (ContextFlags)0 && (this.m_ContextFlags & (int)flag) == 0)
     {
         throw new AdomdConnectionException(XmlaSR.Authentication_Sspi_FlagNotEstablished(flag.ToString()), null, ConnectionExceptionCause.AuthenticationFailed);
     }
 }
 internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ContextAwareResult context, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding)
 {
     if ((credential is SystemNetworkCredential) && ComNetOS.IsWinNt)
     {
         WindowsIdentity identity = (context == null) ? null : context.Identity;
         try
         {
             IDisposable disposable = (identity == null) ? null : identity.Impersonate();
             if (disposable != null)
             {
                 using (disposable)
                 {
                     this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
                     return;
                 }
             }
             ExecutionContext executionContext = (context == null) ? null : context.ContextCopy;
             if (executionContext == null)
             {
                 this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
             }
             else
             {
                 ExecutionContext.Run(executionContext, s_InitializeCallback, new InitializeCallbackContext(this, isServer, package, credential, spn, requestedContextFlags, channelBinding));
             }
             return;
         }
         catch
         {
             throw;
         }
     }
     this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
 }
Example #5
0
 /// <summary>
 /// Create a new instance of the GraphicsAPI struct.
 /// </summary>
 /// <param name="api">The context API to use.</param>
 /// <param name="profile">The context profile to use.</param>
 /// <param name="flags">The context flags to use.</param>
 /// <param name="apiVersion">The API version to use.</param>
 public GraphicsAPI(ContextAPI api, ContextProfile profile, ContextFlags flags, APIVersion apiVersion)
 {
     API     = api;
     Profile = profile;
     Flags   = flags;
     Version = apiVersion;
 }
Example #6
0
 /// <summary>
 /// Populates the given transformation manager with O0 optimizations.
 /// </summary>
 /// <param name="builder">The transformation manager to populate.</param>
 /// <param name="contextFlags">The context flags.</param>
 public static void AddO0Optimizations(
     this Transformer.Builder builder,
     ContextFlags contextFlags)
 {
     builder.AddBasicOptimizations(contextFlags);
     builder.AddAddressSpaceOptimizations();
 }
Example #7
0
        // returns the platform-specific Context Flags
        public ContextFlags GetPSFlags(AgnosticContextFlags flags)
        {
            // We know that we need an ia64 context
            this.m_platform = Platform.IA64;
            ContextFlags cFlags = ContextFlags.IA64Context;

            if ((flags & AgnosticContextFlags.ContextInteger) == AgnosticContextFlags.ContextInteger)
            {
                // ContextInteger is the same for all platforms, so we can do a blanket |=
                cFlags |= (ContextFlags)AgnosticContextFlags.ContextInteger;
            }

            if ((flags & AgnosticContextFlags.ContextControl) == AgnosticContextFlags.ContextControl)
            {
                // IA64 has a different flag for ContextControl
                cFlags |= ContextFlags.IA64ContextControl;
            }

            if ((flags & AgnosticContextFlags.ContextFloatingPoint) == AgnosticContextFlags.ContextFloatingPoint)
            {
                // IA64 has a different flag for ContextFloatingPoint
                cFlags |= ContextFlags.IA64ContextFloatingPoint;
            }

            if ((flags & AgnosticContextFlags.ContextAll) == AgnosticContextFlags.ContextAll)
            {
                // ContextAll is the same for all platforms, so we can do a blanket |=
                cFlags |= (ContextFlags)AgnosticContextFlags.ContextAll;
            }

            return(cFlags);
        }
Example #8
0
        public GPU(ContextFlags flags = ContextFlags.None, OptimizationLevel optimizationLevel = OptimizationLevel.Debug, bool forceCPU = false)
        {
            this.context = new Context(flags, optimizationLevel);
            this.context.EnableAlgorithms();

            this.accelerator = GetGpu(context, forceCPU);
            Console.WriteLine("Device loaded: " + accelerator.Name);
        }
Example #9
0
 public SpanContext(TraceId traceId, SpanId spanId = null, SpanId parentId = null, Dictionary <string, string> baggage = null, ContextFlags flags = ContextFlags.Sampled)
 {
     TraceId  = traceId ?? throw new ArgumentNullException(nameof(traceId));
     ParentId = parentId;
     SpanId   = spanId;
     Flags    = flags;
     _baggage = baggage ?? new Dictionary <string, string>();
 }
Example #10
0
        public Context GetContext(ContextFlags ctxFlags)
        {
            var ctx = new Context(ctxFlags);

            if (!GetThreadContext(Handle, ctx.NativeHandle))
                throw new Win32Exception();

            return ctx;
        }
Example #11
0
        /// <summary>
        /// Gets the thread's context.
        /// </summary>
        /// <returns>A CONTEXT struct.</returns>
        public Context GetContext(ContextFlags flags)
        {
            Context context = new Context();

            context.ContextFlags = flags;
            this.GetContext(ref context);

            return(context);
        }
Example #12
0
 /// <summary>
 /// Constructs a new specializer configuration.
 /// </summary>
 /// <param name="flags">The associated context flags.</param>
 /// <param name="abi">The ABI specification.</param>
 /// <param name="contextData">The global PTX context data.</param>
 public SpecializerConfiguration(
     ContextFlags flags,
     ABI abi,
     PTXContextData contextData)
 {
     ContextFlags           = flags;
     ABI                    = abi;
     ImplementationResolver = contextData.ImplementationResolver;
 }
Example #13
0
 /// <summary>
 /// Populates the given transformation manager with O0 optimizations.
 /// </summary>
 /// <param name="builder">The transformation manager to populate.</param>
 /// <param name="contextFlags">The context flags.</param>
 public static void AddO0Optimizations(
     this Transformer.Builder builder,
     ContextFlags contextFlags)
 {
     builder.AddBasicOptimizations(contextFlags);
     builder.Add(new SSAConstruction());
     builder.Add(new DeadCodeElimination());
     builder.Add(new InferAddressSpaces());
 }
Example #14
0
        /// <summary>
        /// Creates a transformer for the given optimization level.
        /// </summary>
        /// <param name="level">The level.</param>
        /// <param name="configuration">The transformer configuration.</param>
        /// <param name="contextFlags">The context flags.</param>
        /// <returns>The created transformer.</returns>
        public static Transformer CreateTransformer(
            this OptimizationLevel level,
            TransformerConfiguration configuration,
            ContextFlags contextFlags)
        {
            var builder = Transformer.CreateBuilder(configuration);

            builder.AddOptimizations(contextFlags, level);
            return(builder.ToTransformer());
        }
Example #15
0
 internal static unsafe partial int AcceptSecurityContext(
     ref CredHandle credentialHandle,
     void *inContextPtr,
     SecBufferDesc *inputBuffer,
     ContextFlags inFlags,
     Endianness endianness,
     ref CredHandle outContextPtr,
     ref SecBufferDesc outputBuffer,
     ref ContextFlags attributes,
     out long timeStamp);
 internal InitializeCallbackContext(NTAuthentication thisPtr, bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding)
 {
     this.thisPtr               = thisPtr;
     this.isServer              = isServer;
     this.package               = package;
     this.credential            = credential;
     this.spn                   = spn;
     this.requestedContextFlags = requestedContextFlags;
     this.channelBinding        = channelBinding;
 }
Example #17
0
 /// <summary>
 /// Adds basic optimization transformations.
 /// </summary>
 /// <param name="builder">The transformation manager to populate.</param>
 /// <param name="contextFlags">The context flags.</param>
 public static void AddBasicOptimizations(
     this Transformer.Builder builder,
     ContextFlags contextFlags)
 {
     if (!contextFlags.HasFlags(ContextFlags.NoInlining))
     {
         builder.Add(new Inliner());
     }
     builder.Add(new SimplifyControlFlow());
 }
Example #18
0
 /// <summary>
 /// Populates the given transformation manager with O1 optimizations.
 /// </summary>
 /// <param name="builder">The transformation manager to populate.</param>
 /// <param name="contextFlags">The context flags.</param>
 public static void AddO1Optimizations(
     this Transformer.Builder builder,
     ContextFlags contextFlags)
 {
     builder.AddBasicOptimizations(contextFlags);
     builder.AddStructureOptimizations();
     builder.AddLoopOptimizations();
     builder.AddConditionalOptimizations();
     builder.AddAddressSpaceOptimizations();
 }
Example #19
0
 internal static extern unsafe int AcceptSecurityContext(
     ref CredHandle credentialHandle,
     [In] void *inContextPtr,
     [In] SecBufferDesc *inputBuffer,
     [In] ContextFlags inFlags,
     [In] Endianness endianness,
     ref CredHandle outContextPtr,
     [In, Out] ref SecBufferDesc outputBuffer,
     [In, Out] ref ContextFlags attributes,
     out long timeStamp
     );
Example #20
0
 /// <summary>
 /// Populates the given transformation manager with the required
 /// optimization transformations.
 /// </summary>
 /// <param name="builder">The transformation manager to populate.</param>
 /// <param name="contextFlags">The context flags.</param>
 /// <param name="level">The desired optimization level.</param>
 /// <returns>The maximum number of iterations.</returns>
 public static void AddOptimizations(
     this Transformer.Builder builder,
     ContextFlags contextFlags,
     OptimizationLevel level)
 {
     if (level < OptimizationLevel.O0 || level > OptimizationLevel.O2)
     {
         throw new ArgumentOutOfRangeException(nameof(level));
     }
     OptimizationHandlers[(int)level](builder, contextFlags);
 }
Example #21
0
        public void SpanContext_ToString()
        {
            var          traceId  = new TraceId(1, 2);
            var          spanId   = new SpanId(3);
            var          parentId = new SpanId(4);
            ContextFlags flags    = (ContextFlags)3;

            var sc = new SpanContext(traceId, spanId, parentId, null, flags);

            Assert.Equal("10000000000000002:3:4:3", sc.ToString());
        }
Example #22
0
 internal GeneratorArgs(
     PTXBackend backend,
     EntryPoint entryPoint,
     PTXDebugInfoGenerator debugInfoGenerator,
     ContextFlags contextFlags)
 {
     Backend            = backend;
     EntryPoint         = entryPoint;
     DebugInfoGenerator = debugInfoGenerator;
     ContextFlags       = contextFlags;
 }
Example #23
0
 public static Context Create(ContextFlags contextFlags)
 {
     if (IntPtr.Size == 8)
     {
         return(new Context64(contextFlags));
     }
     else
     {
         return(new Context32(contextFlags));
     }
 }
 internal static extern int AcceptSecurityContext_1(
     ref SECURITY_HANDLE phCredential,
     SECURITY_HANDLE phContext,
     ref SecBufferDesc pInput,
     ContextFlags fContextReq,
     uint TargetDataRep,
     out SECURITY_HANDLE phNewContext,
     out SecBufferDesc pOutput,
     out ContextFlags pfContextAttr,    //managed ulong == 64 bits!!!
     out SECURITY_INTEGER ptsTimeStamp
     );
Example #25
0
        /// <summary>
        /// Adds general backend optimizations.
        /// </summary>
        /// <param name="builder">The transformation manager to populate.</param>
        /// <param name="acceleratorSpecializer">
        /// An instance of an <see cref="AcceleratorSpecializer"/> class.
        /// </param>
        /// <param name="contextFlags">The context flags.</param>
        /// <param name="level">The desired optimization level.</param>
        public static void AddBackendOptimizations(
            this Transformer.Builder builder,
            AcceleratorSpecializer acceleratorSpecializer,
            ContextFlags contextFlags,
            OptimizationLevel level)
        {
            // Specialize accelerator properties and views
            builder.Add(new LowerPointerViews());
            builder.Add(acceleratorSpecializer);

            // Perform an additional inlining pass to specialize small device-specific
            // functions that could have been introduced
            if (!contextFlags.HasFlags(ContextFlags.NoInlining))
            {
                builder.Add(new Inliner());
            }

            // Skip further optimizations in debug mode
            if (level < OptimizationLevel.O1)
            {
                return;
            }

            // Use experimental address-space specializer in O2 only
            if (level > OptimizationLevel.O1)
            {
                // Specialize all parameter address spaces
                builder.Add(new InferKernelAddressSpaces(MemoryAddressSpace.Global));
            }

            // Lower all value structures that could have been created during the
            // following passes:
            // LowerPointerViews, AcceleratorSpecializer and AddressSpaceSpecializer
            builder.Add(new LowerStructures());

            // Apply DCE phase in release mode to remove all dead values that
            // could be created in prior passes
            builder.Add(new DeadCodeElimination());

            // Infer all specialized address spaces
            if (level > OptimizationLevel.O1)
            {
                builder.Add(new InferLocalAddressSpaces());
            }
            else
            {
                builder.Add(new InferAddressSpaces());
            }

            // Final cleanup phases to improve performance
            builder.Add(new CleanupBlocks());
            builder.Add(new SimplifyControlFlow());
        }
Example #26
0
        /// <summary>
        /// Constructs a new ILGPU main context
        /// </summary>
        /// <param name="optimizationLevel">The optimization level.</param>
        /// <param name="flags">The context flags.</param>
        public Context(ContextFlags flags, OptimizationLevel optimizationLevel)
        {
            // Enable debug information automatically when a debugger is attached
            if (Debugger.IsAttached)
            {
                flags |= DefaultDebug;
            }

            InstanceId        = InstanceId.CreateNew();
            OptimizationLevel = optimizationLevel;
            Flags             = flags.Prepare();
            TargetPlatform    = Backend.RuntimePlatform;
            RuntimeSystem     = new RuntimeSystem();

            // Initialize enhanced PTX backend feature flags
            if (optimizationLevel > OptimizationLevel.O1 &&
                !Flags.HasFlags(ContextFlags.DefaultPTXBackendFeatures))
            {
                Flags |= ContextFlags.EnhancedPTXBackendFeatures;
            }

            // Initialize verifier
            Verifier = flags.HasFlags(ContextFlags.EnableVerifier)
                ? Verifier.Instance
                : Verifier.Empty;

            // Initialize main contexts
            TypeContext = new IRTypeContext(this);
            IRContext   = new IRContext(this);

            // Create frontend
            DebugInformationManager frontendDebugInformationManager =
                HasFlags(ContextFlags.EnableDebugSymbols)
                ? DebugInformationManager
                : null;

            ILFrontend = HasFlags(ContextFlags.EnableParallelCodeGenerationInFrontend)
                ? new ILFrontend(this, frontendDebugInformationManager)
                : new ILFrontend(this, frontendDebugInformationManager, 1);

            // Create default IL backend
            DefautltILBackend = new DefaultILBackend(this);

            // Initialize default transformer
            ContextTransformer = Optimizer.CreateTransformer(
                OptimizationLevel,
                TransformerConfiguration.Transformed,
                Flags);

            // Intrinsics
            IntrinsicManager = new IntrinsicImplementationManager();
            InitIntrinsics();
        }
Example #27
0
 /// <summary>
 /// Get the thread context.
 /// </summary>
 /// <param name="flags">Flags for context parts to get.</param>
 /// <returns>An instance of an IContext object. Needs to be cast to correct type to access.</returns>
 public IContext GetContext(ContextFlags flags)
 {
     // Really needs to support ARM as well.
     if (Environment.Is64BitProcess)
     {
         return(GetAmd64Context(flags));
     }
     else
     {
         return(GetX86Context(flags));
     }
 }
Example #28
0
        private IContext GetX86Context(ContextFlags flags)
        {
            var context = new ContextX86();

            context.ContextFlags = flags;

            using (var buffer = context.ToBuffer())
            {
                NtSystemCalls.NtGetContextThread(Handle, buffer).ToNtException();
                return(buffer.Result);
            }
        }
Example #29
0
        private NtResult <IContext> GetX86Context(ContextFlags flags, bool throw_on_error)
        {
            var context = new ContextX86
            {
                ContextFlags = flags
            };

            using (var buffer = context.ToBuffer())
            {
                return(NtSystemCalls.NtGetContextThread(Handle, buffer).CreateResult(throw_on_error, () => buffer.Result).Cast <IContext>());
            }
        }
Example #30
0
 /// <summary>
 /// Populates the given transformation manager with the required
 /// debug optimization transformations.
 /// </summary>
 /// <param name="builder">The transformation manager to populate.</param>
 /// <param name="contextFlags">The context flags.</param>
 public static void AddDebugOptimizations(
     this Transformer.Builder builder,
     ContextFlags contextFlags)
 {
     if (!contextFlags.HasFlags(ContextFlags.NoInlining))
     {
         builder.Add(new Inliner());
     }
     builder.Add(new SimplifyControlFlow());
     builder.Add(new SSAConstruction());
     builder.Add(new DeadCodeElimination());
 }
 internal static int AcceptSecurityContext(SSPIInterface SecModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, ContextFlags inFlags, Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
 {
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, string.Concat(new object[] { "AcceptSecurityContext(credential = ", credential.ToString(), ", context = ", ValidationHelper.ToString(context), ", inFlags = ", inFlags, ")" }));
     }
     int num = SecModule.AcceptSecurityContext(ref credential, ref context, inputBuffer, inFlags, datarep, outputBuffer, ref outFlags);
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, SR.GetString("net_log_sspi_security_context_input_buffer", new object[] { "AcceptSecurityContext", (inputBuffer == null) ? 0 : inputBuffer.size, outputBuffer.size, (SecurityStatus) num }));
     }
     return num;
 }
Example #32
0
 internal static unsafe partial int InitializeSecurityContextW(
     ref CredHandle credentialHandle,
     void *inContextPtr,
     byte *targetName,
     ContextFlags inFlags,
     int reservedI,
     Endianness endianness,
     SecBufferDesc *inputBuffer,
     int reservedII,
     ref CredHandle outContextPtr,
     ref SecBufferDesc outputBuffer,
     ref ContextFlags attributes,
     out long timeStamp);
Example #33
0
 internal GeneratorArgs(
     PTXBackend backend,
     EntryPoint entryPoint,
     ContextFlags contextFlags,
     PTXDebugInfoGenerator debugInfoGenerator,
     PointerAlignments pointerAlignments)
 {
     Backend            = backend;
     EntryPoint         = entryPoint;
     ContextFlags       = contextFlags;
     DebugInfoGenerator = debugInfoGenerator;
     PointerAlignments  = pointerAlignments;
 }
 internal NTAuthentication(bool isServer, string package, string spn, ContextFlags requestedContextFlags, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding)
 {
     try
     {
         using (WindowsIdentity.Impersonate(IntPtr.Zero))
         {
             this.Initialize(isServer, package, SystemNetworkCredential.defaultCredential, spn, requestedContextFlags, channelBinding);
         }
     }
     catch
     {
         throw;
     }
 }
        //
        private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) {
            GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor() package:" + ValidationHelper.ToString(package) + " spn:" + ValidationHelper.ToString(spn) + " flags :" + requestedContextFlags.ToString());
            m_TokenSize = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken;
            m_IsServer = isServer;
            m_Spn = spn;
            m_SecurityContext = null;
            m_RequestedContextFlags = requestedContextFlags;
            m_Package = package;
            m_ChannelBinding = channelBinding;

            GlobalLog.Print("Peer SPN-> '" + m_Spn + "'");
            //
            // check if we're using DefaultCredentials
            //
            if (credential is SystemNetworkCredential)
            {
                GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor(): using DefaultCredentials");
                m_CredentialsHandle = SSPIWrapper.AcquireDefaultCredential(
                                                    GlobalSSPI.SSPIAuth,
                                                    package,
                                                    (m_IsServer? CredentialUse.Inbound: CredentialUse.Outbound));
                m_UniqueUserId = "/S"; // save off for unique connection marking ONLY used by HTTP client
            }
            else if (ComNetOS.IsWin7orLater)
            {
                unsafe
                {
                    SafeSspiAuthDataHandle authData = null;
                    try
                    {
                        SecurityStatus result = UnsafeNclNativeMethods.SspiHelper.SspiEncodeStringsAsAuthIdentity(
                            credential.InternalGetUserName(), credential.InternalGetDomain(),
                            credential.InternalGetPassword(), out authData);

                        if (result != SecurityStatus.OK)
                        {
                            if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "SspiEncodeStringsAsAuthIdentity()", String.Format(CultureInfo.CurrentCulture, "0x{0:X}", (int)result)));
                            throw new Win32Exception((int)result);
                        }

                        m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth,
                            package, (m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound), ref authData);
                    }
                    finally
                    {
                        if (authData != null)
                        {
                            authData.Close();
                        }
                    }
                }
            }
            else
            {

                //
                // we're not using DefaultCredentials, we need a
                // AuthIdentity struct to contain credentials
                // SECREVIEW:
                // we'll save username/domain in temp strings, to avoid decrypting multiple times.
                // password is only used once
                //
                string username = credential.InternalGetUserName();

                string domain = credential.InternalGetDomain();
                // ATTN:
                // NetworkCredential class does not differentiate between null and "" but SSPI packages treat these cases differently
                // For NTLM we want to keep "" for Wdigest.Dll we should use null.
                AuthIdentity authIdentity = new AuthIdentity(username, credential.InternalGetPassword(), (object)package == (object)NegotiationInfoClass.WDigest && (domain == null || domain.Length == 0)? null: domain);

                m_UniqueUserId = domain + "/" + username + "/U"; // save off for unique connection marking ONLY used by HTTP client

                GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor(): using authIdentity:" + authIdentity.ToString());

                m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle(
                                                    GlobalSSPI.SSPIAuth,
                                                    package,
                                                    (m_IsServer? CredentialUse.Inbound: CredentialUse.Outbound),
                                                    ref authIdentity
                                                    );
            }
        }
 internal InitializeCallbackContext(NTAuthentication thisPtr, bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding)
 {
     this.thisPtr = thisPtr;
     this.isServer = isServer;
     this.package = package;
     this.credential = credential;
     this.spn = spn;
     this.requestedContextFlags = requestedContextFlags;
     this.channelBinding = channelBinding;
 }
 public int InitializeSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref ContextFlags outFlags) {
     return SafeDeleteContext.InitializeSecurityContext(Library, ref credential, ref context, targetName, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags);
 }
Example #38
0
      private static void prepareContext (SqlConnection connection, string bingo_schema,
         int id, ContextFlags flags)
      {
         BingoCore.setContext(id);

         // Set basic paremeters for every request
         // TODO: cache settings
         BingoCore.setConfigInt("treat-x-as-pseudoatom",
             BingoConfig.getInt(connection, bingo_schema, "treat-x-as-pseudoatom", id));
         BingoCore.setConfigInt("ignore-stereocenter-errors",
             BingoConfig.getInt(connection, bingo_schema, "ignore-stereocenter-errors", id));
         BingoCore.setConfigInt("ignore-cistrans-errors",
             BingoConfig.getInt(connection, bingo_schema, "ignore-cistrans-errors", id));
         BingoCore.setConfigInt("allow-non-unique-dearomatization",
             BingoConfig.getInt(connection, bingo_schema, "allow-non-unique-dearomatization", id));
         BingoCore.setConfigInt("zero-unknown-aromatic-hydrogens",
             BingoConfig.getInt(connection, bingo_schema, "zero-unknown-aromatic-hydrogens", id));
         BingoCore.setConfigInt("stereochemistry-bidirectional-mode",
             BingoConfig.getInt(connection, bingo_schema, "stereochemistry-bidirectional-mode", id));
         BingoCore.setConfigInt("stereochemistry-detect-haworth-projection",
             BingoConfig.getInt(connection, bingo_schema, "stereochemistry-detect-haworth-projection", id));
         BingoCore.setConfigInt("ignore-closing-bond-direction-mismatch",
             BingoConfig.getInt(connection, bingo_schema, "ignore-closing-bond-direction-mismatch", id));
         BingoCore.setConfigInt("reject-invalid-structures",
             BingoConfig.getInt(connection, bingo_schema, "reject-invalid-structures", id));

         if ((flags & ContextFlags.NTHREADS) != 0)
         {
            BingoCore.setConfigInt("nthreads",
                BingoConfig.getInt(connection, bingo_schema, "nthreads", id));
         }

         if ((flags & ContextFlags.TAU_RULES) != 0)
         {
            ArrayList rules = BingoConfig.getTautomerRules(connection, bingo_schema);

            BingoCore.clearTautomerRules();
            foreach (BingoConfig.TautomerRule rule in rules)
            {
               BingoCore.addTautomerRule(rule.n, rule.beg, rule.end);
            }
            BingoCore.tautomerRulesReady();
         }

         if ((flags & ContextFlags.FINGERPRINTS) != 0)
         {
            BingoCore.setConfigInt("FP_ORD_SIZE",
                BingoConfig.getInt(connection, bingo_schema, "FP_ORD_SIZE", id));
            BingoCore.setConfigInt("FP_ANY_SIZE",
                BingoConfig.getInt(connection, bingo_schema, "FP_ANY_SIZE", id));
            BingoCore.setConfigInt("FP_TAU_SIZE",
                BingoConfig.getInt(connection, bingo_schema, "FP_TAU_SIZE", id));
            BingoCore.setConfigInt("FP_SIM_SIZE",
                BingoConfig.getInt(connection, bingo_schema, "FP_SIM_SIZE", id));

            BingoCore.setConfigInt("SUB_SCREENING_MAX_BITS",
                BingoConfig.getInt(connection, bingo_schema, "SUB_SCREENING_MAX_BITS", id));
            BingoCore.setConfigInt("SIM_SCREENING_PASS_MARK",
                BingoConfig.getInt(connection, bingo_schema, "SIM_SCREENING_PASS_MARK", id));
         }
         if ((flags & ContextFlags.CMF) != 0)
         {
            BingoCore.setConfigBin("cmf-dict",
                BingoConfig.getBinary(connection, bingo_schema, "cmf-dict", id));
         }
      }
		public static bool CryptAcquireContext(ref IntPtr hProv, string pszContainer, string pszProvider,
																						CryptProvider prov, ContextFlags flags)
			=> CryptAcquireContext(ref hProv, pszContainer, pszProvider, (uint) prov, (uint) flags);
Example #40
0
        private void ProcessThreadContext(int threadId, ContextFlags flag, ThreadContextHandler handler, bool isReadOnly = false)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            var context = new CONTEXT { ContextFlags = flag };

            if (SuspendThread(hThread) == 0xFFFFFFFF)
                throw new Win32Exception();

            if (!GetThreadContext(hThread, ref context))
                throw new Win32Exception();

            handler(ref context);

            if (!isReadOnly)
            {
                if (!SetThreadContext(hThread, ref context))
                    throw new Win32Exception();
            }

            if (ResumeThread(hThread) == 0xFFFFFFFF)
                throw new Win32Exception();
        }
Example #41
0
		internal static int InitializeSecurityContext (SSPIInterface secModule, ref SafeFreeCredentials credentials, ref SafeDeleteContext safeContext, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
		{
			if (inputBuffer != null)
				throw new InvalidOperationException ();

			if (safeContext == null) {
				secModule.Context.Initialize (secModule.EventSink);
				safeContext = new SafeDeleteContext (secModule.Context);
			}

			return InitializeSecurityContext (secModule, credentials, ref safeContext, targetName, inFlags, endianness, null, outputBuffer, ref outFlags);
		}
        //-------------------------------------------------------------------
        internal unsafe static int AcceptSecurityContext(
            SecurDll                dll,
            ref SafeFreeCredentials inCredentials,
            ref SafeDeleteContext   refContext,
            ContextFlags            inFlags,
            Endianness              endianness,
            SecurityBuffer          inSecBuffer,
            SecurityBuffer[]        inSecBuffers,
            SecurityBuffer          outSecBuffer,
            ref ContextFlags        outFlags) {

#if TRAVE
            GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex");
            GlobalLog.Print("    DLL              = " + dll);
            GlobalLog.Print("    credential       = " + inCredentials.ToString());
            GlobalLog.Print("    refContext       = " + ValidationHelper.ToString(refContext));

            GlobalLog.Print("    inFlags          = " + inFlags);
//            GlobalLog.Print("    endianness       = " + endianness);
//            GlobalLog.Print("    inSecBuffer      = " + SecurityBuffer.ToString(inSecBuffer));
//
            if (inSecBuffers==null)
            {
                GlobalLog.Print("    inSecBuffers     = (null)");
            }
            else
            {
                GlobalLog.Print("    inSecBuffers[]   = length:" + inSecBuffers.Length);
//                for (int index=0; index<inSecBuffers.Length; index++) { GlobalLog.Print("    inSecBuffers[" + index + "]   = " + SecurityBuffer.ToString(inSecBuffers[index])); }
            }
//            GlobalLog.Print("    newContext       = {ref} inContext");
//            GlobalLog.Print("    outSecBuffer     = " + SecurityBuffer.ToString(outSecBuffer));
//            GlobalLog.Print("    outFlags         = {ref} " + outFlags);
//            GlobalLog.Print("    timestamp        = null");
#endif
            GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null");
            GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null");

            if (inCredentials == null)
            {
                throw new ArgumentNullException("inCredentials");
            }

            SecurityBufferDescriptor inSecurityBufferDescriptor = null;
            if (inSecBuffer!=null)
            {
                inSecurityBufferDescriptor = new SecurityBufferDescriptor(1);
            }
            else if (inSecBuffers!=null)
            {
                inSecurityBufferDescriptor = new SecurityBufferDescriptor(inSecBuffers.Length);
            }
            SecurityBufferDescriptor outSecurityBufferDescriptor = new SecurityBufferDescriptor(1);

            // actually this is returned in outFlags
            bool isSspiAllocated = (inFlags & ContextFlags.AllocateMemory) != 0 ? true : false;

            int errorCode = -1;

            SSPIHandle contextHandle = new SSPIHandle();
            if (refContext != null)
                contextHandle = refContext._handle;

            // these are pinned user byte arrays passed along with SecurityBuffers
            GCHandle[] pinnedInBytes = null;
            GCHandle pinnedOutBytes = new GCHandle();
            // optional output buffer that may need to be freed
            SafeFreeContextBuffer outFreeContextBuffer = null;
            try
            {
                pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
                SecurityBufferStruct[] inUnmanagedBuffer = new SecurityBufferStruct[inSecurityBufferDescriptor==null ? 1:inSecurityBufferDescriptor.Count];
                fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer)
                {
                    if (inSecurityBufferDescriptor!=null)
                    {
                        // Fix Descriptor pointer that points to unmanaged SecurityBuffers
                        inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr;
                        pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count];
                        SecurityBuffer securityBuffer;
                        for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index)
                        {
                            securityBuffer = inSecBuffer!=null ? inSecBuffer : inSecBuffers[index];
                            if (securityBuffer!=null)
                            {
                                // Copy the SecurityBuffer content into unmanaged place holder
                                inUnmanagedBuffer[index].count = securityBuffer.size;
                                inUnmanagedBuffer[index].type  = securityBuffer.type;

                                // use the unmanaged token if it's not null; otherwise use the managed buffer
                                if (securityBuffer.unmanagedToken != null)
                                {
                                    inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle();
                                }
                                else if (securityBuffer.token == null || securityBuffer.token.Length == 0)
                                {
                                    inUnmanagedBuffer[index].token = IntPtr.Zero;
                                }
                                else
                                {
                                    pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned);
                                    inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset);
                                }
    #if TRAVE
                                GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size +  " BufferType:" + securityBuffer.type);
    #endif
                            }
                        }
                    }
                    SecurityBufferStruct[] outUnmanagedBuffer = new SecurityBufferStruct[1];
                    fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer)
                    {
                        // Fix Descriptor pointer that points to unmanaged SecurityBuffers
                        outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr;
                        // Copy the SecurityBuffer content into unmanaged place holder
                        outUnmanagedBuffer[0].count = outSecBuffer.size;
                        outUnmanagedBuffer[0].type  = outSecBuffer.type;

                        if (outSecBuffer.token == null || outSecBuffer.token.Length == 0)
                            outUnmanagedBuffer[0].token  = IntPtr.Zero;
                        else
                            outUnmanagedBuffer[0].token  = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);

                        if (isSspiAllocated)
                            outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(dll);

                        switch (dll)
                        {
                        case SecurDll.SECURITY:
                                    if (refContext == null || refContext.IsInvalid)
                                        refContext = new SafeDeleteContext_SECURITY();

                                    errorCode = MustRunAcceptSecurityContext_SECURITY(
                                                    ref inCredentials,
                                                    contextHandle.IsZero? null: &contextHandle,
                                                    inSecurityBufferDescriptor,
                                                    inFlags,
                                                    endianness,
                                                    refContext,
                                                    outSecurityBufferDescriptor,
                                                    ref outFlags,
                                                    outFreeContextBuffer
                                                    );

                                    break;

                        default:  throw new ArgumentException(SR.GetString(SR.net_invalid_enum, "SecurDll"), "Dll");
                        }

                        GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext  Marshalling OUT buffer");
                        // Get unmanaged buffer with index 0 as the only one passed into PInvoke
                        outSecBuffer.size = outUnmanagedBuffer[0].count;
                        outSecBuffer.type = outUnmanagedBuffer[0].type;
                        if (outSecBuffer.size > 0)
                        {
                            outSecBuffer.token = new byte[outSecBuffer.size];
                            Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size);
                        }
                        else
                        {
                            outSecBuffer.token = null;
                        }
                    }
                }
            }
            finally {
                if (pinnedInBytes!=null)
                {
                    for (int index=0; index<pinnedInBytes.Length; index++)
                    {
                        if (pinnedInBytes[index].IsAllocated)
                            pinnedInBytes[index].Free();
                    }
                }

                if (pinnedOutBytes.IsAllocated)
                    pinnedOutBytes.Free();

                if (outFreeContextBuffer != null)
                    outFreeContextBuffer.Close();
            }

            GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + ValidationHelper.ToString(refContext));

            return errorCode;
        }
        //
        // After PINvoke call the method will fix the handleTemplate.handle with the returned value.
        // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned.
        //
        // Since it has a CER, this method can't have any references to imports from DLLs that may not exist on the system.
        //
        private static unsafe int MustRunAcceptSecurityContext_SECURITY(
                                                  ref SafeFreeCredentials     inCredentials,
                                                  void*            inContextPtr,
                                                  SecurityBufferDescriptor inputBuffer,
                                                  ContextFlags     inFlags,
                                                  Endianness       endianness,
                                                  SafeDeleteContext outContext,
                                                  SecurityBufferDescriptor outputBuffer,
                                                  ref ContextFlags outFlags,
                                                  SafeFreeContextBuffer handleTemplate)
        {
            int errorCode = (int) SecurityStatus.InvalidHandle;
            bool b1 = false;
            bool b2 = false;

            // Run the body of this method as a non-interruptible block.
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                inCredentials.DangerousAddRef(ref b1);
                outContext.DangerousAddRef(ref b2);
            }
            catch(Exception e)
            {
                if (b1)
                {
                    inCredentials.DangerousRelease();
                    b1 = false;
                }
                if (b2)
                {
                    outContext.DangerousRelease();
                    b2 = false;
                }
                if (!(e is ObjectDisposedException))
                    throw;
            }
            finally {
                SSPIHandle credentialHandle = inCredentials._handle;
                long timeStamp;

                if (!b1)
                {
                    // caller should retry
                    inCredentials = null;
                }
                else if (b1 && b2)
                {
                    errorCode = UnsafeNclNativeMethods.SafeNetHandles_SECURITY.AcceptSecurityContext(
                                ref credentialHandle,
                                inContextPtr,
                                inputBuffer,
                                inFlags,
                                endianness,
                                ref outContext._handle,
                                outputBuffer,
                                ref outFlags,
                                out timeStamp);

                    //
                    // When a credential handle is first associated with the context we keep credential
                    // ref count bumped up to ensure ordered finalization.
                    // If the credential handle has been changed we de-ref the old one and associate the
                    //  context with the new cred handle but only if the call was successful.
                    if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0)
                    {
                        // Disassociate the previous credential handle
                        if (outContext._EffectiveCredential != null)
                            outContext._EffectiveCredential.DangerousRelease();
                        outContext._EffectiveCredential = inCredentials;
                    }
                    else
                    {
                        inCredentials.DangerousRelease();
                    }

                    outContext.DangerousRelease();

                    // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer.
                    if (handleTemplate != null)
                    {
                        handleTemplate.Set(((SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes
                        if (handleTemplate.IsInvalid)
                        {
                            handleTemplate.SetHandleAsInvalid();
                        }
                    }
                }

                if (inContextPtr == null && (errorCode & 0x80000000) != 0)
                {
                    // an error on the first call, need to set the out handle to invalid value
                    outContext._handle.SetToInvalid();
                }
            }

            return errorCode;
        }
 extern static bool CryptAcquireContext(
                                             [Out]out KeyContainerHandle phProv,
                                             string pszContainer,
                                             string pszProvider,
                                             ProviderType dwProvType,
                                             ContextFlags dwFlags);
        internal static unsafe int AcceptSecurityContext(SecurDll dll, ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, ContextFlags inFlags, Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref ContextFlags outFlags)
        {
            if (inCredentials == null)
            {
                throw new ArgumentNullException("inCredentials");
            }
            SecurityBufferDescriptor inputBuffer = null;
            if (inSecBuffer != null)
            {
                inputBuffer = new SecurityBufferDescriptor(1);
            }
            else if (inSecBuffers != null)
            {
                inputBuffer = new SecurityBufferDescriptor(inSecBuffers.Length);
            }
            SecurityBufferDescriptor outputBuffer = new SecurityBufferDescriptor(1);
            bool flag = (inFlags & ContextFlags.AllocateMemory) != ContextFlags.Zero;
            int num = -1;
            SSPIHandle handle = new SSPIHandle();
            if (refContext != null)
            {
                handle = refContext._handle;
            }
            GCHandle[] handleArray = null;
            GCHandle handle2 = new GCHandle();
            SafeFreeContextBuffer handleTemplate = null;
            try
            {
                handle2 = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
                SecurityBufferStruct[] structArray = new SecurityBufferStruct[(inputBuffer == null) ? 1 : inputBuffer.Count];
                try
                {
                    SecurityBufferStruct[] structArray3;
                    if (((structArray3 = structArray) == null) || (structArray3.Length == 0))
                    {
                        ptrRef = null;
                        goto Label_00A5;
                    }
                    fixed (IntPtr* ptrRef = structArray3)
                    {
                    Label_00A5:
                        if (inputBuffer != null)
                        {
                            inputBuffer.UnmanagedPointer = (void*) ptrRef;
                            handleArray = new GCHandle[inputBuffer.Count];
                            for (int i = 0; i < inputBuffer.Count; i++)
                            {
                                SecurityBuffer buffer2 = (inSecBuffer != null) ? inSecBuffer : inSecBuffers[i];
                                if (buffer2 != null)
                                {
                                    structArray[i].count = buffer2.size;
                                    structArray[i].type = buffer2.type;
                                    if (buffer2.unmanagedToken != null)
                                    {
                                        structArray[i].token = buffer2.unmanagedToken.DangerousGetHandle();
                                    }
                                    else if ((buffer2.token == null) || (buffer2.token.Length == 0))
                                    {
                                        structArray[i].token = IntPtr.Zero;
                                    }
                                    else
                                    {
                                        handleArray[i] = GCHandle.Alloc(buffer2.token, GCHandleType.Pinned);
                                        structArray[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(buffer2.token, buffer2.offset);
                                    }
                                }
                            }
                        }
                        SecurityBufferStruct[] structArray2 = new SecurityBufferStruct[1];
                        try
                        {
                            SecurityBufferStruct[] structArray4;
                            if (((structArray4 = structArray2) == null) || (structArray4.Length == 0))
                            {
                                ptrRef2 = null;
                                goto Label_01CB;
                            }
                            fixed (IntPtr* ptrRef2 = structArray4)
                            {
                            Label_01CB:
                                outputBuffer.UnmanagedPointer = (void*) ptrRef2;
                                structArray2[0].count = outSecBuffer.size;
                                structArray2[0].type = outSecBuffer.type;
                                if ((outSecBuffer.token == null) || (outSecBuffer.token.Length == 0))
                                {
                                    structArray2[0].token = IntPtr.Zero;
                                }
                                else
                                {
                                    structArray2[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
                                }
                                if (flag)
                                {
                                    handleTemplate = SafeFreeContextBuffer.CreateEmptyHandle(dll);
                                }
                                switch (dll)
                                {
                                    case SecurDll.SECURITY:
                                        if ((refContext == null) || refContext.IsInvalid)
                                        {
                                            refContext = new SafeDeleteContext_SECURITY();
                                        }
                                        num = MustRunAcceptSecurityContext_SECURITY(ref inCredentials, handle.IsZero ? null : ((void*) &handle), inputBuffer, inFlags, endianness, refContext, outputBuffer, ref outFlags, handleTemplate);
                                        break;

                                    case SecurDll.SECUR32:
                                        if ((refContext == null) || refContext.IsInvalid)
                                        {
                                            refContext = new SafeDeleteContext_SECUR32();
                                        }
                                        num = MustRunAcceptSecurityContext_SECUR32(ref inCredentials, handle.IsZero ? null : ((void*) &handle), inputBuffer, inFlags, endianness, refContext, outputBuffer, ref outFlags, handleTemplate);
                                        break;

                                    case SecurDll.SCHANNEL:
                                        if ((refContext == null) || refContext.IsInvalid)
                                        {
                                            refContext = new SafeDeleteContext_SCHANNEL();
                                        }
                                        num = MustRunAcceptSecurityContext_SCHANNEL(ref inCredentials, handle.IsZero ? null : ((void*) &handle), inputBuffer, inFlags, endianness, refContext, outputBuffer, ref outFlags, handleTemplate);
                                        break;

                                    default:
                                        throw new ArgumentException(SR.GetString("net_invalid_enum", new object[] { "SecurDll" }), "Dll");
                                }
                                outSecBuffer.size = structArray2[0].count;
                                outSecBuffer.type = structArray2[0].type;
                                if (outSecBuffer.size > 0)
                                {
                                    outSecBuffer.token = new byte[outSecBuffer.size];
                                    Marshal.Copy(structArray2[0].token, outSecBuffer.token, 0, outSecBuffer.size);
                                    return num;
                                }
                                outSecBuffer.token = null;
                                return num;
                            }
                        }
                        finally
                        {
                            ptrRef2 = null;
                        }
                        return num;
                    }
                }
                finally
                {
                    ptrRef = null;
                }
            }
            finally
            {
                if (handleArray != null)
                {
                    for (int j = 0; j < handleArray.Length; j++)
                    {
                        if (handleArray[j].IsAllocated)
                        {
                            handleArray[j].Free();
                        }
                    }
                }
                if (handle2.IsAllocated)
                {
                    handle2.Free();
                }
                if (handleTemplate != null)
                {
                    handleTemplate.Close();
                }
            }
            return num;
        }
Example #46
0
 public static int SetAttribute(ContextAttribute attr, ContextFlags value)
 {
     return SetAttribute(attr, (int)value);
 }
 internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding)
 {
     this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
 }
 public void GetThreadContext(ContextFlags flags, int contextBufferSize, out int contextSize, IntPtr contextBuffer)
 {
     uint uContextSize = 0;
     m_sw.GetContext((uint)flags, (uint)contextBufferSize, out uContextSize, contextBuffer);
         contextSize = (int)uContextSize;
     }
 public int AcceptSecurityContext(SafeFreeCredentials credential, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers, ContextFlags inFlags, Endianness endianness, SecurityBuffer outputBuffer, ref ContextFlags outFlags) {
     return SafeDeleteContext.AcceptSecurityContext(Library, ref credential, ref context, inFlags, endianness, null, inputBuffers, outputBuffer, ref outFlags);
 }
        internal static int AcceptSecurityContext(SSPIInterface SecModule, SafeFreeCredentials credential, ref SafeDeleteContext context, ContextFlags inFlags, Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref ContextFlags outFlags) 
        {
            if (Logging.On) Logging.PrintInfo(Logging.Web, 
                "AcceptSecurityContext(" +
                "credential = " + credential.ToString() + ", " +
                "context = " + ValidationHelper.ToString(context) + ", " +
                "inFlags = " + inFlags + ")");

            int errorCode = SecModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags);

            if (Logging.On) Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_log_sspi_security_context_input_buffers, "AcceptSecurityContext", (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (SecurityStatus) errorCode));
            
            return errorCode;
        }
Example #51
0
		/*
		 * @safecontext is null on the first use, but it will become non-null for invocations 
		 * where the connection is being re-negotiated.
		 * 
		*/
		internal static int AcceptSecurityContext (SSPIInterface secModule, ref SafeFreeCredentials credentials, ref SafeDeleteContext safeContext, ContextFlags inFlags, Endianness endianness, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
		{
			if (endianness != Endianness.Native)
				throw new NotSupportedException ();

			if (safeContext == null) {
				if (credentials == null || credentials.IsInvalid)
					return (int)SecurityStatus.CredentialsNeeded;

				secModule.Context.Initialize (secModule.EventSink);
				safeContext = new SafeDeleteContext (secModule.Context);
			}

			SetCredentials (secModule, credentials);

			var incoming = GetInputBuffer (inputBuffer);
			IBufferOffsetSize outgoing;

			var retval = (int)safeContext.Context.GenerateNextToken (incoming, out outgoing);
			UpdateOutput (outgoing, outputBuffer);
			return retval;
		}
 internal extern static bool CryptAcquireContext(
                                             [Out]out KeyContainerHandle phProv,
                                             [MarshalAs(UnmanagedType.LPWStr)] string pszContainer,
                                             [MarshalAs(UnmanagedType.LPWStr)]string pszProvider,
                                             ProviderType dwProvType,
                                             ContextFlags dwFlags);
Example #53
0
      private static void saveContext (SqlConnection connection, string bingo_schema,
         int id, ContextFlags flags)
      {
         BingoCore.setContext(id);

         if ((flags & ContextFlags.CMF) != 0)
         {
            BingoConfig.setBinary(connection, bingo_schema, "cmf-dict", id, 
               BingoCore.getConfigBin("cmf-dict"));
         }
      }
 //
 // This overload does not attmept to impersonate because the caller either did it already or the original thread context is still preserved
 //
 internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) {
     Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
 }
 private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding)
 {
     this.m_TokenSize = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken;
     this.m_IsServer = isServer;
     this.m_Spn = spn;
     this.m_SecurityContext = null;
     this.m_RequestedContextFlags = requestedContextFlags;
     this.m_Package = package;
     this.m_ChannelBinding = channelBinding;
     if (credential is SystemNetworkCredential)
     {
         this.m_CredentialsHandle = SSPIWrapper.AcquireDefaultCredential(GlobalSSPI.SSPIAuth, package, this.m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound);
         this.m_UniqueUserId = "/S";
     }
     else
     {
         string userName = credential.InternalGetUserName();
         string domain = credential.InternalGetDomain();
         AuthIdentity authdata = new AuthIdentity(userName, credential.InternalGetPassword(), ((package == "WDigest") && ((domain == null) || (domain.Length == 0))) ? null : domain);
         this.m_UniqueUserId = domain + "/" + userName + "/U";
         this.m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth, package, this.m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound, ref authdata);
     }
 }
 internal NTAuthentication(bool isServer, string package, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding)
 {
     try
     {
         using (WindowsIdentity.Impersonate(IntPtr.Zero))
         {
             Initialize(isServer, package, SystemNetworkCredential.defaultCredential, spn, requestedContextFlags, channelBinding);
         }
     }
     catch
     {
         // Avoid exception filter attacks.
         throw;
     }
 }
Example #57
0
        /// <summary>
        /// Set return state of run-time
        /// </summary>
        /// <param name="val">true or false</param>
        public void SetReturn(bool val)
        {
            if (val && IsContinue()) throw new ScriptException("Implementation: Implementation error, consult with developer");
              if (val && IsBreak()) throw new ScriptException("Implementation: Implementation error, consult with developer");

              if (val)
            flags = flags | ContextFlags.Return;
              else
            flags = flags & ~ContextFlags.Return;
        }
        internal static unsafe int InitializeSecurityContext(SecurDll dll, ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref ContextFlags outFlags)
        {
            if (inCredentials == null)
            {
                throw new ArgumentNullException("inCredentials");
            }
            SecurityBufferDescriptor inputBuffer = null;
            if (inSecBuffer != null)
            {
                inputBuffer = new SecurityBufferDescriptor(1);
            }
            else if (inSecBuffers != null)
            {
                inputBuffer = new SecurityBufferDescriptor(inSecBuffers.Length);
            }
            SecurityBufferDescriptor outputBuffer = new SecurityBufferDescriptor(1);
            bool flag = (inFlags & ContextFlags.AllocateMemory) != ContextFlags.Zero;
            int num = -1;
            SSPIHandle handle = new SSPIHandle();
            if (refContext != null)
            {
                handle = refContext._handle;
            }
            GCHandle[] handleArray = null;
            GCHandle handle2 = new GCHandle();
            SafeFreeContextBuffer handleTemplate = null;
            try
            {
                handle2 = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned);
                SecurityBufferStruct[] structArray = new SecurityBufferStruct[(inputBuffer == null) ? 1 : inputBuffer.Count];
                try
                {
                    SecurityBufferStruct[] structArray3;
                    if (((structArray3 = structArray) == null) || (structArray3.Length == 0))
                    {
                        ptrRef = null;
                        goto Label_00A6;
                    }
                    fixed (IntPtr* ptrRef = structArray3)
                    {
                    Label_00A6:
                        if (inputBuffer != null)
                        {
                            inputBuffer.UnmanagedPointer = (void*) ptrRef;
                            handleArray = new GCHandle[inputBuffer.Count];
                            for (int i = 0; i < inputBuffer.Count; i++)
                            {
                                SecurityBuffer buffer2 = (inSecBuffer != null) ? inSecBuffer : inSecBuffers[i];
                                if (buffer2 != null)
                                {
                                    structArray[i].count = buffer2.size;
                                    structArray[i].type = buffer2.type;
                                    if (buffer2.unmanagedToken != null)
                                    {
                                        structArray[i].token = buffer2.unmanagedToken.DangerousGetHandle();
                                    }
                                    else if ((buffer2.token == null) || (buffer2.token.Length == 0))
                                    {
                                        structArray[i].token = IntPtr.Zero;
                                    }
                                    else
                                    {
                                        handleArray[i] = GCHandle.Alloc(buffer2.token, GCHandleType.Pinned);
                                        structArray[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(buffer2.token, buffer2.offset);
                                    }
                                }
                            }
                        }
                        SecurityBufferStruct[] structArray2 = new SecurityBufferStruct[1];
                        try
                        {
                            SecurityBufferStruct[] structArray4;
                            if (((structArray4 = structArray2) == null) || (structArray4.Length == 0))
                            {
                                ptrRef2 = null;
                                goto Label_01CC;
                            }
                            fixed (IntPtr* ptrRef2 = structArray4)
                            {
                                ref byte pinned numRef;
                                ref byte pinned numRef2;
                            Label_01CC:
                                outputBuffer.UnmanagedPointer = (void*) ptrRef2;
                                structArray2[0].count = outSecBuffer.size;
                                structArray2[0].type = outSecBuffer.type;
                                if ((outSecBuffer.token == null) || (outSecBuffer.token.Length == 0))
                                {
                                    structArray2[0].token = IntPtr.Zero;
                                }
                                else
                                {
                                    structArray2[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset);
                                }
                                if (flag)
                                {
                                    handleTemplate = SafeFreeContextBuffer.CreateEmptyHandle(dll);
                                }
                                switch (dll)
                                {
                                    case SecurDll.SECURITY:
                                        if ((refContext == null) || refContext.IsInvalid)
                                        {
                                            refContext = new SafeDeleteContext_SECURITY();
                                        }
                                        if ((targetName == null) || (targetName.Length == 0))
                                        {
                                            targetName = " ";
                                        }
                                        fixed (char* str = ((char*) targetName))
                                        {
                                            char* chPtr = str;
                                            num = MustRunInitializeSecurityContext_SECURITY(ref inCredentials, handle.IsZero ? null : ((void*) &handle), (targetName == " ") ? null : ((byte*) chPtr), inFlags, endianness, inputBuffer, refContext, outputBuffer, ref outFlags, handleTemplate);
                                            goto Label_044B;
                                        }
                                        break;

                                    case SecurDll.SECUR32:
                                        break;

                                    case SecurDll.SCHANNEL:
                                        goto Label_0381;

                                    default:
                                        goto Label_0423;
                                }
                                if ((refContext == null) || refContext.IsInvalid)
                                {
                                    refContext = new SafeDeleteContext_SECUR32();
                                }
                                byte[] dummyBytes = SafeDeleteContext.dummyBytes;
                                if ((targetName != null) && (targetName.Length != 0))
                                {
                                    dummyBytes = new byte[targetName.Length + 2];
                                    Encoding.Default.GetBytes(targetName, 0, targetName.Length, dummyBytes, 0);
                                }
                                try
                                {
                                    byte[] buffer5;
                                    if (((buffer5 = dummyBytes) == null) || (buffer5.Length == 0))
                                    {
                                        numRef = null;
                                    }
                                    else
                                    {
                                        numRef = buffer5;
                                    }
                                    num = MustRunInitializeSecurityContext_SECUR32(ref inCredentials, handle.IsZero ? null : ((void*) &handle), (dummyBytes == SafeDeleteContext.dummyBytes) ? null : numRef, inFlags, endianness, inputBuffer, refContext, outputBuffer, ref outFlags, handleTemplate);
                                    goto Label_044B;
                                }
                                finally
                                {
                                    numRef = null;
                                }
                            Label_0381:
                                if ((refContext == null) || refContext.IsInvalid)
                                {
                                    refContext = new SafeDeleteContext_SCHANNEL();
                                }
                                byte[] bytes = SafeDeleteContext.dummyBytes;
                                if ((targetName != null) && (targetName.Length != 0))
                                {
                                    bytes = new byte[targetName.Length + 2];
                                    Encoding.Default.GetBytes(targetName, 0, targetName.Length, bytes, 0);
                                }
                                try
                                {
                                    byte[] buffer6;
                                    if (((buffer6 = bytes) == null) || (buffer6.Length == 0))
                                    {
                                        numRef2 = null;
                                    }
                                    else
                                    {
                                        numRef2 = buffer6;
                                    }
                                    num = MustRunInitializeSecurityContext_SCHANNEL(ref inCredentials, handle.IsZero ? null : ((void*) &handle), (bytes == SafeDeleteContext.dummyBytes) ? null : numRef2, inFlags, endianness, inputBuffer, refContext, outputBuffer, ref outFlags, handleTemplate);
                                    goto Label_044B;
                                }
                                finally
                                {
                                    numRef2 = null;
                                }
                            Label_0423:;
                                throw new ArgumentException(SR.GetString("net_invalid_enum", new object[] { "SecurDll" }), "Dll");
                            Label_044B:
                                outSecBuffer.size = structArray2[0].count;
                                outSecBuffer.type = structArray2[0].type;
                                if (outSecBuffer.size > 0)
                                {
                                    outSecBuffer.token = new byte[outSecBuffer.size];
                                    Marshal.Copy(structArray2[0].token, outSecBuffer.token, 0, outSecBuffer.size);
                                    return num;
                                }
                                outSecBuffer.token = null;
                                return num;
                            }
                        }
                        finally
                        {
                            ptrRef2 = null;
                        }
                        return num;
                    }
                }
Example #59
0
		internal static int InitializeSecurityContext (SSPIInterface secModule, SafeFreeCredentials credentials, ref SafeDeleteContext safeContext, string targetName, ContextFlags inFlags, Endianness endianness, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref ContextFlags outFlags)
		{
			if (endianness != Endianness.Native)
				throw new NotSupportedException ();

			SetCredentials (secModule, credentials);

			SecurityBuffer inputBuffer = null;
			if (inputBuffers != null) {
				if (inputBuffers.Length != 2 || inputBuffers [1].type != BufferType.Empty)
					throw new NotSupportedException ();
				inputBuffer = inputBuffers [0];
			}

			var incoming = GetInputBuffer (inputBuffer);
			IBufferOffsetSize outgoing = null;

			var retval = (int)safeContext.Context.GenerateNextToken (incoming, out outgoing);
			UpdateOutput (outgoing, outputBuffer);
			return retval;
		}
        internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ContextAwareResult context, ChannelBinding channelBinding)
        {
            //
            // check if we're using DefaultCredentials
            //
            if (credential is SystemNetworkCredential)
            {
                // 
#if DEBUG
                GlobalLog.Assert(context == null || context.IdentityRequested, "NTAuthentication#{0}::.ctor|Authentication required when it wasn't expected.  (Maybe Credentials was changed on another thread?)", ValidationHelper.HashString(this));
#endif

                WindowsIdentity w = context == null ? null : context.Identity;
                try
                {
                    IDisposable ctx = w == null ? null : w.Impersonate();
                    if (ctx != null)
                    {
                        using (ctx)
                        {
                            Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
                        }
                    }
                    else
                    {
                        ExecutionContext x = context == null ? null : context.ContextCopy;
                        if (x == null)
                        {
                            Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
                        }
                        else
                        {
                            ExecutionContext.Run(x, s_InitializeCallback, new InitializeCallbackContext(this, isServer, package, credential, spn, requestedContextFlags, channelBinding));
                        }
                    }
                }
                catch
                {
                    // Prevent the impersonation from leaking to upstack exception filters.
                    throw;
                }
            }
            else
            {
                Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
            }
        }