/// <summary>
        ///  The NetrLogonSamLogonWithFlags method Supported in windows_xpwindows_server_2003,
        ///  windows_vista, windows_server_2008, windows_7, and
        ///  windows_server_7. handles logon requests for the SAM
        ///  accounts. Opnum: 45 
        /// </summary>
        /// <param name="LogonServer">
        ///  The custom RPC binding handle, as specified in section
        ///  .
        /// </param>
        /// <param name="ComputerName">
        ///  The Unicode string that contains the NetBIOS name of
        ///  the client computer calling this method.
        /// </param>
        /// <param name="Authenticator">
        ///  A pointer to a NETLOGON_AUTHENTICATOR structure, as
        ///  specified in section , that contains the client authenticator.
        /// </param>
        /// <param name="ReturnAuthenticator">
        ///  A pointer to a NETLOGON_AUTHENTICATOR structure, as
        ///  specified in section , that contains the server return
        ///  authenticator.
        /// </param>
        /// <param name="LogonLevel">
        ///  A NETLOGON_LOGON_INFO_CLASS structure, as specified
        ///  in section , that specifies the type of logon information
        ///  passed in the LogonInformation parameter.
        /// </param>
        /// <param name="LogonInformation">
        ///  A pointer to a NETLOGON_LEVEL structure, as specified
        ///  in section , that describes the logon request information.
        /// </param>
        /// <param name="ValidationLevel">
        ///  A NETLOGON_VALIDATION_INFO_CLASS enumerated type, as
        ///  specified in section , that contains the validation
        ///  level requested by the client.
        /// </param>
        /// <param name="ValidationInformation">
        ///  A pointer to a NETLOGON_VALIDATION structure, as specified
        ///  in section , that describes the user validation information
        ///  returned to the client. The type of the NETLOGON_VALIDATION
        ///  used is determined by the value of the ValidationLevel
        ///  parameter.
        /// </param>
        /// <param name="Authoritative">
        ///  A pointer to a char value representing a Boolean condition.
        ///  FALSE is indicated by the value 0x00; TRUE SHOULD be
        ///  indicated by the value 0x01 and MAY also be indicated
        ///  by any nonzero value. Windows uses the value of 0x01
        ///  as the representation of TRUE and 0x00 for FALSE. This
        ///  Boolean value indicates whether the validation information
        ///  is final. This field is necessary because the request
        ///  might be forwarded through multiple servers. A value
        ///  of TRUE indicates that the validation information is
        ///  final and MUST remain unchanged.
        /// </param>
        /// <param name="ExtraFlags">
        ///  A pointer to a set of bit flags that specify delivery
        ///  settings. A flag is TRUE (or set) if its value is equal
        ///  to 1. The value is constructed from zero or more bit
        ///  flags from the following table.
        /// </param>
        public NtStatus NetrLogonSamLogonWithFlags(
            string LogonServer,
            string ComputerName,
            _NETLOGON_AUTHENTICATOR? Authenticator,
            ref _NETLOGON_AUTHENTICATOR? ReturnAuthenticator,
            _NETLOGON_LOGON_INFO_CLASS LogonLevel,
            _NETLOGON_LEVEL? LogonInformation,
            _NETLOGON_VALIDATION_INFO_CLASS ValidationLevel,
            out _NETLOGON_VALIDATION? ValidationInformation,
            out byte? Authoritative,
            ref uint? ExtraFlags)
        {
            const ushort opnum = 45;

            byte[] requestStub;
            byte[] responseStub;
            Int3264[] paramList;
            int retVal;

            SafeIntPtr pLogonServer = Marshal.StringToHGlobalUni(LogonServer);
            SafeIntPtr pComputerName = Marshal.StringToHGlobalUni(ComputerName);
            SafeIntPtr pAuthenticator = TypeMarshal.ToIntPtr(Authenticator);
            SafeIntPtr pReturnAuthenticatorIn = TypeMarshal.ToIntPtr(ReturnAuthenticator);
            SafeIntPtr pLogonInformation = TypeMarshal.ToIntPtr(LogonInformation, LogonLevel, null, null);
            SafeIntPtr pExtraFlags = TypeMarshal.ToIntPtr(ExtraFlags);

            paramList = new Int3264[] {
                pLogonServer,
                pComputerName,
                pAuthenticator,
                pReturnAuthenticatorIn,
                (uint)LogonLevel,
                pLogonInformation,
                (uint)ValidationLevel,
                IntPtr.Zero,
                IntPtr.Zero,
                pExtraFlags,
                0 // retVal
            };

            requestStub = RpceStubEncoder.ToBytes(
                     RpceStubHelper.GetPlatform(),
                    NrpcRpcStubFormatString.TypeFormatString,
                    new RpceStubExprEval[] { new RpceStubExprEval(logon__NETLOGON_DELTA_USERExprEval_0000) },
                    NrpcRpcStubFormatString.ProcFormatString,
                    NrpcRpcStubFormatString.ProcFormatStringOffsetTable[opnum],
                    true,
                    paramList);

            rpceClientTransport.Call(opnum, requestStub, rpceTimeout, out responseStub);

            using (RpceInt3264Collection outParamList = RpceStubDecoder.ToParamList(
                     RpceStubHelper.GetPlatform(),
                    NrpcRpcStubFormatString.TypeFormatString,
                    new RpceStubExprEval[] { new RpceStubExprEval(logon__NETLOGON_DELTA_USERExprEval_0000) },
                    NrpcRpcStubFormatString.ProcFormatString,
                    NrpcRpcStubFormatString.ProcFormatStringOffsetTable[opnum],
                    true,
                    responseStub,
                    paramList))
            {
                IntPtr pReturnAuthenticatorOut = outParamList[3];
                ReturnAuthenticator = TypeMarshal.ToNullableStruct<_NETLOGON_AUTHENTICATOR>(pReturnAuthenticatorOut);

                IntPtr pValidationInformation = outParamList[7];
                ValidationInformation = TypeMarshal.ToNullableStruct<_NETLOGON_VALIDATION>(
                    pValidationInformation,
                    ValidationLevel,
                    null,
                    null);

                Authoritative = TypeMarshal.ToNullableStruct<byte>(outParamList[8]);

                ExtraFlags = TypeMarshal.ToNullableStruct<uint>(outParamList[9]);

                retVal = outParamList[10].ToInt32();
            }

            pLogonServer.Dispose();
            pComputerName.Dispose();
            pAuthenticator.Dispose();
            pReturnAuthenticatorIn.Dispose();
            pLogonInformation.Dispose();
            pExtraFlags.Dispose();

            return (NtStatus)retVal;
        }
        /// <summary>
        /// Construct Nlmp pass-through network logon information structure 
        /// from client NTLM authenticate response message
        /// </summary>
        /// <param name="parameterControl">
        /// A set of bit flags that contain information pertaining to the logon validation processing.
        /// </param>
        /// <param name="nlmpAuthenticatePacket">
        /// nlmp authenticate response packet sent from client machine
        /// </param>
        /// <param name="lmChallenge">
        /// nlmp challenge sent from server to client
        /// </param>
        /// <returns>
        /// Nlmp pass-through network logon information
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown when nlmpAuthenticatePacket or lmChallenge is null.
        /// </exception>        
        /// <exception cref="ArgumentException">
        /// Thrown when the length of lmChallenge is not equal to 8 bytes
        /// </exception>
        public static _NETLOGON_LEVEL CreateNlmpNetworkLogonInfo(
            NrpcParameterControlFlags parameterControl,
            NlmpAuthenticatePacket nlmpAuthenticatePacket,
            byte[] lmChallenge
            )
        {
            if (nlmpAuthenticatePacket == null)
            {
                throw new ArgumentNullException("nlmpAuthenticatePacket");
            }

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

            // ServerChallenge (8 bytes): A 64-bit value that contains the NTLM challenge.
            // The challenge is a 64-bit nonce. The processing of the
            // ServerChallenge is specified in sections 3.1.5 and 3.2.5.
            if (lmChallenge.Length != NLMP_SERVER_CHALLENGE_LENGTH)
            {
                throw new ArgumentException(
                    "the length of lmChallenge should be 8 bytes",
                    "lmChallenge");
            }

            string domainName;
            string userName;
            string logonWorkStation;

            _NETLOGON_LEVEL netLogonLevel = new _NETLOGON_LEVEL();
            if (nlmpAuthenticatePacket.Payload.DomainName != null)
            {
                domainName = Encoding.Unicode.GetString(nlmpAuthenticatePacket.Payload.DomainName);
            }
            else
            {
                throw new ArgumentException(
                    "DomainName field should not be null",
                    "nlmpAuthenticatePacket");
            }

            if (nlmpAuthenticatePacket.Payload.UserName != null)
            {
                userName = Encoding.Unicode.GetString(nlmpAuthenticatePacket.Payload.UserName);
            }
            else
            {
                throw new ArgumentException(
                    "UserName field should not be null",
                    "nlmpAuthenticatePacket");
            }

            if (nlmpAuthenticatePacket.Payload.Workstation != null)
            {
                logonWorkStation = Encoding.Unicode.GetString(nlmpAuthenticatePacket.Payload.Workstation);
            }
            else
            {
                throw new ArgumentException(
                    "WorkStation field should not be null",
                    "nlmpAuthenticatePacket");
            }

            //Identity: A NETLOGON_LOGON_IDENTITY_INFO structure, as specified in section MS-NRPC 2.2.1.4.15,
            //that contains information about the logon identity.
            _NETLOGON_LOGON_IDENTITY_INFO identityInfo = NrpcUtility.CreateNetlogonIdentityInfo(
                parameterControl,
                domainName,
                userName,
                logonWorkStation);

            netLogonLevel.LogonNetwork = new _NETLOGON_NETWORK_INFO[1];
            netLogonLevel.LogonNetwork[0].Identity = identityInfo;
            netLogonLevel.LogonNetwork[0].LmChallenge = new LM_CHALLENGE();
            netLogonLevel.LogonNetwork[0].LmChallenge.data = lmChallenge;
            netLogonLevel.LogonNetwork[0].LmChallengeResponse =
                NrpcUtility.CreateString(nlmpAuthenticatePacket.Payload.LmChallengeResponse);
            netLogonLevel.LogonNetwork[0].NtChallengeResponse =
                NrpcUtility.CreateString(nlmpAuthenticatePacket.Payload.NtChallengeResponse);

            return netLogonLevel;
        }
        /// <summary>
        ///  Construct Kerberos PAC pass-through logon information
        /// </summary>
        /// <param name="parameterControl">
        /// A set of bit flags that contain information pertaining to the logon validation processing.
        /// </param>
        /// <param name="domainName">domain name</param>
        /// <param name="userName">user name</param>        
        /// <param name="serverName">NetBIOS name of server </param>
        /// <param name="kerbVerifyPacRequest">KERB_VERIFY_PAC_REQUEST packet</param>
        /// <returns>Kerberos PAC netlogon information structure </returns>        
        public static _NETLOGON_LEVEL CreatePacLogonInfo(
            NrpcParameterControlFlags parameterControl,
            string domainName,
            string userName,
            string serverName,
            KERB_VERIFY_PAC_REQUEST kerbVerifyPacRequest)
        {
            _NETLOGON_LEVEL netLogonLevel = new _NETLOGON_LEVEL();
            byte[] logonData = TypeMarshal.ToBytes<KERB_VERIFY_PAC_REQUEST>(kerbVerifyPacRequest);

            //Identity: A NETLOGON_LOGON_IDENTITY_INFO structure, as specified in section MS-NRPC 2.2.1.4.15,
            //that contains information about the logon identity.
            _NETLOGON_LOGON_IDENTITY_INFO identityInfo = NrpcUtility.CreateNetlogonIdentityInfo(
                parameterControl,
                domainName,
                userName,
                serverName);

            netLogonLevel.LogonGeneric = new _NETLOGON_GENERIC_INFO[1];
            netLogonLevel.LogonGeneric[0].Identity = identityInfo;
            netLogonLevel.LogonGeneric[0].PackageName = DtypUtility.ToRpcUnicodeString(KERBEROS_PACKAGENAME);
            netLogonLevel.LogonGeneric[0].LogonData = logonData;
            netLogonLevel.LogonGeneric[0].DataLength = (uint)logonData.Length;

            return netLogonLevel;
        }
        /// <summary>
        /// Create DPSP logon information structure
        /// </summary>
        /// <param name="parameterControl">
        /// A set of bit flags that contain information pertaining to the logon validation processing.
        /// </param>
        /// <param name="digestValidationReq">DIGEST_VALIDATION_REQ structure</param>
        /// <returns>Dpsp netlogon information structure</returns>
        public static _NETLOGON_LEVEL CreateDpspLogonInfo(
            NrpcParameterControlFlags parameterControl,
            DIGEST_VALIDATION_REQ digestValidationReq)
        {
            if (digestValidationReq.Payload == null)
            {
                throw new ArgumentException(
                    "invalid digestValidationReq parameter: the payload field is null",
                    "digestValidationReq");
            }

            _NETLOGON_LEVEL netLogonLevel = new _NETLOGON_LEVEL();

            DIGEST_VALIDATION_REQ_Payload payload =
                DIGEST_VALIDATION_REQ_Payload.Parse(digestValidationReq.Payload);
            byte[] logonData = TypeMarshal.ToBytes<DIGEST_VALIDATION_REQ>(digestValidationReq);

            //Identity: A NETLOGON_LOGON_IDENTITY_INFO structure, as specified in section MS-NRPC 2.2.1.4.15,
            //that contains information about the logon identity.
            _NETLOGON_LOGON_IDENTITY_INFO identityInfo = NrpcUtility.CreateNetlogonIdentityInfo(
                parameterControl,
                payload.Domain,
                payload.Username,
                payload.ServerName);

            netLogonLevel.LogonGeneric = new _NETLOGON_GENERIC_INFO[1];
            netLogonLevel.LogonGeneric[0].Identity = identityInfo;
            netLogonLevel.LogonGeneric[0].PackageName = DtypUtility.ToRpcUnicodeString(DIGEST_PACKAGENAME);
            netLogonLevel.LogonGeneric[0].LogonData = logonData;
            netLogonLevel.LogonGeneric[0].DataLength = (uint)logonData.Length;

            return netLogonLevel;
        }
        /// <summary>
        /// Construct Nlmp pass-through interactive logon information structure 
        /// from client NTLM authenticate response message
        /// </summary>
        /// <param name="parameterControl">A set of bit flags 
        /// that contain information pertaining to the logon validation processing.
        /// </param>
        /// <param name="domainName">domain name</param>
        /// <param name="userName">user name</param>
        /// <param name="password">password</param>
        /// <param name="serverName">NetBIOS name of server </param>
        /// <returns>nlmp interactive logon information structure</returns>        
        public static _NETLOGON_LEVEL CreateNlmpInteractiveLogonInfo(
            NrpcParameterControlFlags parameterControl,
            string domainName,
            string userName,
            string password,
            string serverName
            )
        {
            _NETLOGON_LEVEL netLogonLevel = new _NETLOGON_LEVEL();

            //LmOwfPassword: LM_OWF_PASSWORD structure, as specified in section 2.2.1.1.3,
            //that contains the LMOWFv1 of a password.
            //LMOWFv1 is specified in NTLM v1 Authentication in [MS-NLMP] section 3.3.1.
            byte[] lmOwf = NlmpUtility.LmOWF(NlmpVersion.v1, domainName, userName, password);
            //NtOwfPassword: An NT_OWF_PASSWORD structure, as specified in section 2.2.1.1.4,
            //that contains the NTOWFv1 of a password.
            //NTOWFv1 is specified in NTLM v1 Authentication in [MS-NLMP] section 3.3.1.
            byte[] ntOwf = NlmpUtility.NtOWF(NlmpVersion.v1, domainName, userName, password);

            //Identity: A NETLOGON_LOGON_IDENTITY_INFO structure, as specified in section MS-NRPC 2.2.1.4.15,
            //that contains information about the logon identity.
            _NETLOGON_LOGON_IDENTITY_INFO identityInfo = NrpcUtility.CreateNetlogonIdentityInfo(
                parameterControl,
                domainName,
                userName,
                serverName);

            netLogonLevel.LogonInteractive = new _NETLOGON_INTERACTIVE_INFO[1];
            netLogonLevel.LogonInteractive[0].Identity = identityInfo;
            netLogonLevel.LogonInteractive[0].LmOwfPassword = new _LM_OWF_PASSWORD();
            netLogonLevel.LogonInteractive[0].LmOwfPassword.data = NrpcUtility.CreateCypherBlocks(lmOwf);
            netLogonLevel.LogonInteractive[0].NtOwfPassword = new _NT_OWF_PASSWORD();
            netLogonLevel.LogonInteractive[0].NtOwfPassword.data = NrpcUtility.CreateCypherBlocks(ntOwf);

            return netLogonLevel;
        }
        /// <summary>
        /// Create an instance of NETLOGON_LEVEL structure 
        /// based on logonLevel parameter passed to the method.<para/>
        /// This method only supports logonLevel equals to 
        /// NetlogonInteractiveInformation or 
        /// NetlogonNetworkInformation or 
        /// NetlogonServiceInformation or 
        /// NetlogonInteractiveTransitiveInformation or
        /// NetlogonNetworkTransitiveInformation or
        /// NetlogonServiceTransitiveInformation.
        /// </summary>
        /// <param name="logonLevel">
        /// A NETLOGON_LOGON_INFO_CLASS structure, as specified in section 2.2.1.4.16, 
        /// that specifies the type of the logon information.
        /// This method only supports logonLevel equals to 
        /// NetlogonInteractiveInformation or 
        /// NetlogonNetworkInformation or 
        /// NetlogonServiceInformation or 
        /// NetlogonInteractiveTransitiveInformation or
        /// NetlogonNetworkTransitiveInformation or
        /// NetlogonServiceTransitiveInformation.
        /// </param>
        /// <param name="parameterControl">
        /// A set of bit flags that contain information pertaining 
        /// to the logon validation processing.
        /// </param>
        /// <param name="domainName">
        /// Contains the NetBIOS name of the domain of the account.
        /// </param>
        /// <param name="userName">
        /// Contains the name of the user.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <returns>
        /// Created but not-yet-encrypted NETLOGON_LEVEL structure.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// Thrown when logonLevel is not supported by the method.
        /// </exception>
        public _NETLOGON_LEVEL CreateNetlogonLevel(
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            NrpcParameterControlFlags parameterControl,
            string domainName,
            string userName,
            string password)
        {
            _NETLOGON_LEVEL netlogonLevel = new _NETLOGON_LEVEL();
            byte[] lmOwf;
            byte[] ntOwf;
            byte[] lmChallenge;
            byte[] ntChallengeResponse;
            byte[] lmChallengeResponse;

            //Identity: A NETLOGON_LOGON_IDENTITY_INFO structure, as specified in section 2.2.1.4.15,
            //that contains information about the logon identity.
            _NETLOGON_LOGON_IDENTITY_INFO identityInfo = NrpcUtility.CreateNetlogonIdentityInfo(
                parameterControl,
                domainName,
                userName,
                context.ClientComputerName);

            switch (logonLevel)
            {
                case _NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation:
                    //LmOwfPassword: LM_OWF_PASSWORD structure, as specified in section 2.2.1.1.3,
                    //that contains the LMOWFv1 of a password.
                    //LMOWFv1 is specified in NTLM v1 Authentication in [MS-NLMP] section 3.3.1.
                    lmOwf = NlmpUtility.LmOWF(NlmpVersion.v1, domainName, userName, password);
                    //NtOwfPassword: An NT_OWF_PASSWORD structure, as specified in section 2.2.1.1.4,
                    //that contains the NTOWFv1 of a password.
                    //NTOWFv1 is specified in NTLM v1 Authentication in [MS-NLMP] section 3.3.1.
                    ntOwf = NlmpUtility.NtOWF(NlmpVersion.v1, domainName, userName, password);

                    netlogonLevel.LogonInteractive = new _NETLOGON_INTERACTIVE_INFO[1];
                    netlogonLevel.LogonInteractive[0].Identity = identityInfo;
                    netlogonLevel.LogonInteractive[0].LmOwfPassword = new _LM_OWF_PASSWORD();
                    netlogonLevel.LogonInteractive[0].LmOwfPassword.data = NrpcUtility.CreateCypherBlocks(lmOwf);
                    netlogonLevel.LogonInteractive[0].NtOwfPassword = new _NT_OWF_PASSWORD();
                    netlogonLevel.LogonInteractive[0].NtOwfPassword.data = NrpcUtility.CreateCypherBlocks(ntOwf);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkInformation:
                    //LmChallenge: LM_CHALLENGE structure, as specified in section 2.2.1.4.1,
                    //that contains the network authentication challenge.
                    //For details about challenges, see [MS-NLMP].
                    lmChallenge = NrpcUtility.GenerateNonce(NrpcUtility.NL_CREDENTIAL_LENGTH);
                    //NtChallengeResponse: String that contains the NT response (see [MS-NLMP])
                    //to the network authentication challenge.
                    lmOwf = NlmpUtility.GetResponseKeyLm(NlmpVersion.v1, domainName, userName, password);
                    lmChallengeResponse = NlmpUtility.DESL(lmOwf, lmChallenge);
                    //LmChallengeResponse: String that contains the LAN Manager response
                    //(see [MS-NLMP]) to the network authentication challenge.
                    ntOwf = NlmpUtility.GetResponseKeyNt(NlmpVersion.v1, domainName, userName, password);
                    ntChallengeResponse = NlmpUtility.DESL(ntOwf, lmChallenge);

                    netlogonLevel.LogonNetwork = new _NETLOGON_NETWORK_INFO[1];
                    netlogonLevel.LogonNetwork[0].Identity = identityInfo;
                    netlogonLevel.LogonNetwork[0].LmChallenge = new LM_CHALLENGE();
                    netlogonLevel.LogonNetwork[0].LmChallenge.data = lmChallenge;
                    netlogonLevel.LogonNetwork[0].LmChallengeResponse = NrpcUtility.CreateString(lmChallengeResponse);
                    netlogonLevel.LogonNetwork[0].NtChallengeResponse = NrpcUtility.CreateString(ntChallengeResponse);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonServiceInformation:
                    //LmOwfPassword: LM_OWF_PASSWORD structure, as specified in section 2.2.1.1.3,
                    //that contains the LMOWFv1 of a password.
                    //LMOWFv1 is specified in NTLM v1 Authentication in [MS-NLMP] section 3.3.1.
                    lmOwf = NlmpUtility.LmOWF(NlmpVersion.v1, domainName, userName, password);
                    //NtOwfPassword: NT_OWF_PASSWORD structure, as specified in section 2.2.1.1.4,
                    //that contains the NTOWFv1 of a password.
                    //NTOWFv1 is specified in NTLM v1 Authentication in [MS-NLMP] section 3.3.1.
                    ntOwf = NlmpUtility.NtOWF(NlmpVersion.v1, domainName, userName, password);

                    netlogonLevel.LogonService = new _NETLOGON_SERVICE_INFO[1];
                    netlogonLevel.LogonService[0].Identity = identityInfo;
                    netlogonLevel.LogonService[0].LmOwfPassword = new _LM_OWF_PASSWORD();
                    netlogonLevel.LogonService[0].LmOwfPassword.data = NrpcUtility.CreateCypherBlocks(lmOwf);
                    netlogonLevel.LogonService[0].NtOwfPassword = new _NT_OWF_PASSWORD();
                    netlogonLevel.LogonService[0].NtOwfPassword.data = NrpcUtility.CreateCypherBlocks(ntOwf);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveTransitiveInformation:
                    lmOwf = NlmpUtility.LmOWF(NlmpVersion.v1, domainName, userName, password);
                    ntOwf = NlmpUtility.NtOWF(NlmpVersion.v1, domainName, userName, password);

                    netlogonLevel.LogonInteractiveTransitive = new _NETLOGON_INTERACTIVE_INFO[1];
                    netlogonLevel.LogonInteractiveTransitive[0].Identity = identityInfo;
                    netlogonLevel.LogonInteractiveTransitive[0].LmOwfPassword = new _LM_OWF_PASSWORD();
                    netlogonLevel.LogonInteractiveTransitive[0].LmOwfPassword.data
                        = NrpcUtility.CreateCypherBlocks(lmOwf);
                    netlogonLevel.LogonInteractiveTransitive[0].NtOwfPassword = new _NT_OWF_PASSWORD();
                    netlogonLevel.LogonInteractiveTransitive[0].NtOwfPassword.data
                        = NrpcUtility.CreateCypherBlocks(ntOwf);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation:
                    lmChallenge = NrpcUtility.GenerateNonce(NrpcUtility.NL_CREDENTIAL_LENGTH);
                    lmOwf = NlmpUtility.GetResponseKeyLm(NlmpVersion.v1, domainName, userName, password);
                    lmChallengeResponse = NlmpUtility.DESL(lmOwf, lmChallenge);
                    ntOwf = NlmpUtility.GetResponseKeyNt(NlmpVersion.v1, domainName, userName, password);
                    ntChallengeResponse = NlmpUtility.DESL(ntOwf, lmChallenge);

                    netlogonLevel.LogonNetworkTransitive = new _NETLOGON_NETWORK_INFO[1];
                    netlogonLevel.LogonNetworkTransitive[0].Identity = identityInfo;
                    netlogonLevel.LogonNetworkTransitive[0].LmChallenge = new LM_CHALLENGE();
                    netlogonLevel.LogonNetworkTransitive[0].LmChallenge.data = lmChallenge;
                    netlogonLevel.LogonNetworkTransitive[0].LmChallengeResponse
                        = NrpcUtility.CreateString(lmChallengeResponse);
                    netlogonLevel.LogonNetworkTransitive[0].NtChallengeResponse
                        = NrpcUtility.CreateString(ntChallengeResponse);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonServiceTransitiveInformation:
                    lmOwf = NlmpUtility.LmOWF(NlmpVersion.v1, domainName, userName, password);
                    ntOwf = NlmpUtility.NtOWF(NlmpVersion.v1, domainName, userName, password);

                    netlogonLevel.LogonServiceTransitive = new _NETLOGON_SERVICE_INFO[1];
                    netlogonLevel.LogonServiceTransitive[0].Identity = identityInfo;
                    netlogonLevel.LogonServiceTransitive[0].LmOwfPassword = new _LM_OWF_PASSWORD();
                    netlogonLevel.LogonServiceTransitive[0].LmOwfPassword.data = NrpcUtility.CreateCypherBlocks(lmOwf);
                    netlogonLevel.LogonServiceTransitive[0].NtOwfPassword = new _NT_OWF_PASSWORD();
                    netlogonLevel.LogonServiceTransitive[0].NtOwfPassword.data = NrpcUtility.CreateCypherBlocks(ntOwf);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonGenericInformation:
                default:
                    throw new ArgumentException("logonLevel is not supported by the method.", "logonLevel");
            }

            return netlogonLevel;
        }
        public _NETLOGON_LEVEL CreateNetlogonLevel(
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            string logonDomainName,
            NrpcParameterControlFlags parameterControl,
            string userName,
            string workstation,
            string packageName,
            byte[] logonData)
        {
            if (logonLevel != _NETLOGON_LOGON_INFO_CLASS.NetlogonGenericInformation)
            {
                throw new ArgumentException("logonLevel is not supported by the method.", "logonLevel");
            }

            _NETLOGON_LEVEL netlogonLevel = new _NETLOGON_LEVEL();

            netlogonLevel.LogonGeneric = new _NETLOGON_GENERIC_INFO[1];
            netlogonLevel.LogonGeneric[0].Identity = new _NETLOGON_LOGON_IDENTITY_INFO();
            netlogonLevel.LogonGeneric[0].Identity.LogonDomainName = DtypUtility.ToRpcUnicodeString(logonDomainName);
            netlogonLevel.LogonGeneric[0].Identity.ParameterControl = (uint)parameterControl;
            netlogonLevel.LogonGeneric[0].Identity.UserName = DtypUtility.ToRpcUnicodeString(userName);
            netlogonLevel.LogonGeneric[0].Identity.Workstation = DtypUtility.ToRpcUnicodeString(workstation);
            netlogonLevel.LogonGeneric[0].Identity.Reserved = DtypUtility.ToOldLargeInteger(0);
            netlogonLevel.LogonGeneric[0].PackageName = DtypUtility.ToRpcUnicodeString(packageName);
            netlogonLevel.LogonGeneric[0].DataLength = (uint)logonData.Length;
            netlogonLevel.LogonGeneric[0].LogonData = logonData;

            return netlogonLevel;
        }
        /// <summary>
        ///  The NetrLogonSamLogonWithFlags method Supported in windows_xpwindows_server_2003,
        ///  windows_vista, windows_server_2008, windows_7, and
        ///  windows_server_7. handles logon requests for the SAM
        ///  accounts. Opnum: 45 
        /// </summary>
        /// <param name="logonServer">
        ///  The custom RPC binding handle.
        /// </param>
        /// <param name="computerName">
        ///  The Unicode string that contains the NetBIOS name of
        ///  the client computer calling this method.
        /// </param>
        /// <param name="authenticator">
        ///  A pointer to a NETLOGON_AUTHENTICATOR structure, 
        ///  that contains the client authenticator.
        /// </param>
        /// <param name="returnAuthenticator">
        ///  A pointer to a NETLOGON_AUTHENTICATOR structure, 
        ///  that contains the server return
        ///  authenticator.
        /// </param>
        /// <param name="logonLevel">
        ///  A NETLOGON_LOGON_INFO_CLASS structure, 
        ///  that specifies the type of logon information
        ///  passed in the LogonInformation parameter.
        /// </param>
        /// <param name="logonInformation">
        ///  A pointer to a NETLOGON_LEVEL structure, 
        ///  that describes the logon request information.
        /// </param>
        /// <param name="validationLevel">
        ///  A NETLOGON_VALIDATION_INFO_CLASS enumerated type, 
        ///  that contains the validation
        ///  level requested by the client.
        /// </param>
        /// <param name="validationInformation">
        ///  A pointer to a NETLOGON_VALIDATION structure, 
        ///  that describes the user validation information
        ///  returned to the client. The type of the NETLOGON_VALIDATION
        ///  used is determined by the value of the ValidationLevel
        ///  parameter.
        /// </param>
        /// <param name="authoritative">
        ///  A pointer to a char value representing a Boolean condition.
        ///  FALSE is indicated by the value 0x00; TRUE SHOULD be
        ///  indicated by the value 0x01 and MAY also be indicated
        ///  by any nonzero value. Windows uses the value of 0x01
        ///  as the representation of TRUE and 0x00 for FALSE. This
        ///  Boolean value indicates whether the validation information
        ///  is final. This field is necessary because the request
        ///  might be forwarded through multiple servers. A value
        ///  of TRUE indicates that the validation information is
        ///  final and MUST remain unchanged.
        /// </param>
        /// <param name="extraFlags">
        ///  A pointer to a set of bit flags that specify delivery
        ///  settings. A flag is TRUE (or set) if its value is equal
        ///  to 1. The value is constructed from zero or more bit
        ///  flags from the following table.
        /// </param>
        /// <returns>
        /// The method returns 0x00000000 on success; 
        /// otherwise, it returns a nonzero error code.
        /// </returns>
        public NtStatus NetrLogonSamLogonWithFlags(
            string logonServer,
            string computerName,
            _NETLOGON_AUTHENTICATOR? authenticator,
            ref _NETLOGON_AUTHENTICATOR? returnAuthenticator,
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            _NETLOGON_LEVEL? logonInformation,
            _NETLOGON_VALIDATION_INFO_CLASS validationLevel,
            out _NETLOGON_VALIDATION? validationInformation,
            out byte? authoritative,
            ref NrpcNetrLogonSamLogonExtraFlags? extraFlags)
        {
            uint? flags = (uint?)extraFlags;

            NtStatus status = rpc.NetrLogonSamLogonWithFlags(
                logonServer,
                computerName,
                authenticator,
                ref returnAuthenticator,
                logonLevel,
                logonInformation,
                validationLevel,
                out validationInformation,
                out authoritative,
                ref flags);

            context.ConnectionStatus = status;
            extraFlags = (NrpcNetrLogonSamLogonExtraFlags?)flags;
            return status;
        }
        /// <summary>
        ///  The NetrLogonSamLogonEx method Supported in windows_2000_server,
        ///  windows_xp, windows_server_2003, windows_vista, windows_server_2008,
        ///  windows_7, and windows_server_7. provides an extension
        ///  to NetrLogonSamLogon that accepts an extra flags parameter
        ///  and uses Secure RPC ([MS-RPCE]) instead of
        ///  Netlogon authenticators. This method handles logon
        ///  requests for the SAM accounts and allows for generic
        ///  pass-through authentication.
        ///  For more information about fields and structures
        ///  used by Netlogon pass-through methods.
        ///  Opnum: 39 
        /// </summary>
        /// <param name="contextHandle">
        ///  A primitive RPC handle that identifies a particular
        ///  client/server binding.
        /// </param>
        /// <param name="logonServer">
        ///  The null-terminated Unicode string that contains the
        ///  NetBIOS name of the server that will handle the logon
        ///  request.
        /// </param>
        /// <param name="computerName">
        ///  The null-terminated Unicode string that contains the
        ///  NetBIOS name of the client computer sending the logon
        ///  request.
        /// </param>
        /// <param name="logonLevel">
        ///  A NETLOGON_LOGON_INFO_CLASS structure, 
        ///  that specifies the type of the logon information
        ///  passed in the LogonInformation parameter.
        /// </param>
        /// <param name="logonInformation">
        ///  A pointer to a NETLOGON_LEVEL structure, 
        ///  that describes the logon request information.
        /// </param>
        /// <param name="validationLevel">
        ///  A NETLOGON_VALIDATION_INFO_CLASS enumerated type, 
        ///  that contains the validation
        ///  level requested by the client.
        /// </param>
        /// <param name="validationInformation">
        ///  A pointer to a NETLOGON_VALIDATION structure, 
        ///  that describes the user validation information
        ///  returned to the client. The type of the NETLOGON_VALIDATION
        ///  used is determined by the value of the ValidationLevel
        ///  parameter.
        /// </param>
        /// <param name="authoritative">
        ///  A pointer to a char value that represents a Boolean
        ///  condition. FALSE is indicated by the value 0x00, and
        ///  TRUE SHOULDwindows uses the value 0x01 as the representation
        ///  of TRUE and 0x00 for FALSE. be indicated by the value
        ///  0x01 and MAY also be indicated by any nonzero value.
        ///  This Boolean value indicates whether the validation
        ///  information is final. This field is necessary because
        ///  the request might be forwarded through multiple servers.
        ///  The value TRUE indicates that the validation information
        ///  is final and MUST remain unchanged. The Authoritative
        ///  parameter indicates whether the response to this call
        ///  is final or if the same request can be sent to another
        ///  server. The value SHOULD be set to FALSE if the server
        ///  encounters a transient error, and the client can resend
        ///  the request to another server. If the same request
        ///  is known to fail in all subsequent requests, the server
        ///  SHOULD return TRUE.
        /// </param>
        /// <param name="extraFlags">
        ///  A pointer to a set of bit flags that specify delivery
        ///  settings. A flag is TRUE (or set) if its value is equal
        ///  to 1. Output flags MUST be the same as input. The value
        ///  is constructed from zero or more bit flags from the
        ///  following table.
        /// </param>
        /// <returns>
        /// The method returns 0x00000000 on success; 
        /// otherwise, it returns a nonzero error code.
        /// </returns>
        public NtStatus NetrLogonSamLogonEx(
            IntPtr contextHandle,
            string logonServer,
            string computerName,
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            _NETLOGON_LEVEL? logonInformation,
            _NETLOGON_VALIDATION_INFO_CLASS validationLevel,
            out _NETLOGON_VALIDATION? validationInformation,
            out byte? authoritative,
            ref NrpcNetrLogonSamLogonExtraFlags? extraFlags)
        {
            uint? flags = (uint?)extraFlags;

            NtStatus status = rpc.NetrLogonSamLogonEx(
                contextHandle,
                logonServer,
                computerName,
                logonLevel,
                logonInformation,
                validationLevel,
                out validationInformation,
                out authoritative,
                ref flags);

            context.ConnectionStatus = status;
            extraFlags = (NrpcNetrLogonSamLogonExtraFlags?)flags;
            return status;
        }
        /// <summary>
        ///  The NetrLogonSamLogon method This method was used in
        ///  windows_nt_4_0. It was superseded by the NetrLogonSamLogonWithFlags
        ///  method in windows_2000_server, windows_xp,
        ///  windows_server_2003, windows_vista, and windows_server_2008,
        ///  windows_7, and windows_server_7. is a predecessor to
        ///  the NetrLogonSamLogonWithFlags method. All
        ///  parameters of this method have the same meanings as
        ///  the identically named parameters of the NetrLogonSamLogonWithFlags
        ///  method. Opnum: 2 
        /// </summary>
        /// <param name="logonServer">
        ///  LogonServer parameter.
        /// </param>
        /// <param name="computerName">
        ///  ComputerName parameter.
        /// </param>
        /// <param name="authenticator">
        ///  Authenticator parameter.
        /// </param>
        /// <param name="returnAuthenticator">
        ///  ReturnAuthenticator parameter.
        /// </param>
        /// <param name="logonLevel">
        ///  LogonLevel parameter.
        /// </param>
        /// <param name="logonInformation">
        ///  LogonInformation parameter.
        /// </param>
        /// <param name="validationLevel">
        ///  ValidationLevel parameter.
        /// </param>
        /// <param name="validationInformation">
        ///  ValidationInformation parameter.
        /// </param>
        /// <param name="authoritative">
        ///  Authoritative parameter.
        /// </param>
        /// <returns>
        /// The method returns 0x00000000 on success; 
        /// otherwise, it returns a nonzero error code.
        /// </returns>
        public NtStatus NetrLogonSamLogon(
            string logonServer,
            string computerName,
            _NETLOGON_AUTHENTICATOR? authenticator,
            ref _NETLOGON_AUTHENTICATOR? returnAuthenticator,
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            _NETLOGON_LEVEL? logonInformation,
            _NETLOGON_VALIDATION_INFO_CLASS validationLevel,
            out _NETLOGON_VALIDATION? validationInformation,
            out byte? authoritative)
        {
            NtStatus status = rpc.NetrLogonSamLogon(
                logonServer,
                computerName,
                authenticator,
                ref returnAuthenticator,
                logonLevel,
                logonInformation,
                validationLevel,
                out validationInformation,
                out authoritative);

            //ConnectionStatus: A 4-byte value that contains the most recent
            //connection status return value (section 3.4.5.3.1) last returned
            //during secure channel establishment or by a method requiring
            //session key establishment (section 3.1.4.6).
            context.ConnectionStatus = status;
            return status;
        }
        /// <summary>
        ///  The NetrLogonSamLogoff method handles logoff requests
        ///  for the SAM accounts. Opnum: 3 
        /// </summary>
        /// <param name="logonServer">
        ///  The custom RPC binding handle.
        /// </param>
        /// <param name="computerName">
        ///  The Unicode string that contains the NetBIOS name of
        ///  the client computer calling this method.
        /// </param>
        /// <param name="authenticator">
        ///  A pointer to a NETLOGON_AUTHENTICATOR structure, 
        ///  that contains the client authenticator.
        /// </param>
        /// <param name="returnAuthenticator">
        ///  A pointer to a NETLOGON_AUTHENTICATOR structure, 
        ///  that contains the server return
        ///  authenticator.
        /// </param>
        /// <param name="logonLevel">
        ///  A NETLOGON_LOGON_INFO_CLASS structure, 
        ///  that identifies the type of logon information
        ///  in the LogonInformation union.
        /// </param>
        /// <param name="logonInformation">
        ///  A pointer to a NETLOGON_LEVEL structure, 
        ///  that describes the logon information.
        /// </param>
        /// <returns>
        /// The method returns 0x00000000 on success; 
        /// otherwise, it returns a nonzero error code.
        /// </returns>
        public NtStatus NetrLogonSamLogoff(
            string logonServer,
            string computerName,
            _NETLOGON_AUTHENTICATOR? authenticator,
            ref _NETLOGON_AUTHENTICATOR? returnAuthenticator,
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            _NETLOGON_LEVEL? logonInformation)
        {
            NtStatus status = rpc.NetrLogonSamLogoff(
                logonServer,
                computerName,
                authenticator,
                ref returnAuthenticator,
                logonLevel,
                logonInformation);

            context.ConnectionStatus = status;
            return status;
        }
        /// <summary>
        /// Encrypt a NETLOGON_LEVEL structure based on 
        /// logonLevel parameter passed to the method. 
        /// This method support RC4 encryption only.
        /// </summary>
        /// <param name="logonLevel">
        /// A NETLOGON_LOGON_INFO_CLASS structure, as specified in section 2.2.1.4.16, 
        /// that specifies the type of the logon information.
        /// </param>
        /// <param name="logonInformation">
        /// A NETLOGON_LEVEL structure to be encrypted.
        /// </param>
        /// <returns>The encrypted NETLOGON_LEVEL structure.</returns>
        /// <exception cref="ArgumentException">
        /// Thrown when logonLevel or logonInformation is invalid.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when session key is not negotiated.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when the method is called before establishing a NRPC secure channel. 
        /// Thrown when neither AES nor RC4 is negotiated.
        /// </exception>
        public _NETLOGON_LEVEL EncryptNetlogonLevel(
            _NETLOGON_LOGON_INFO_CLASS logonLevel,
            _NETLOGON_LEVEL logonInformation)
        {
            ValidateSecureChannelExists();

            switch (logonLevel)
            {
                case _NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveInformation:
                    //If the LogonLevel is NetlogonInteractiveInformation or
                    //NetlogonInteractiveTransitiveInformation, then encrypt<102>
                    //the LmOwfPassword and NtOwfPassword members in the
                    //NETLOGON_INTERACTIVE_INFO structure.
                    if (logonInformation.LogonInteractive == null
                        || logonInformation.LogonInteractive.Length != 1)
                    {
                        throw new ArgumentException("logonInformation is invalid.", "logonInformation");
                    }

                    EncryptLmAndNtOwfPassword(
                        ref logonInformation.LogonInteractive[0].LmOwfPassword,
                        ref logonInformation.LogonInteractive[0].NtOwfPassword);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonInteractiveTransitiveInformation:
                    if (logonInformation.LogonInteractiveTransitive == null
                        || logonInformation.LogonInteractiveTransitive.Length != 1)
                    {
                        throw new ArgumentException("logonInformation is invalid.", "logonInformation");
                    }

                    EncryptLmAndNtOwfPassword(
                        ref logonInformation.LogonInteractiveTransitive[0].LmOwfPassword,
                        ref logonInformation.LogonInteractiveTransitive[0].NtOwfPassword);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonServiceInformation:
                    //If the LogonLevel is NetlogonServiceInformation or
                    //NetlogonServiceTransitiveInformation, then encrypt<103>
                    //the LmOwfPassword and NtOwfPassword members in the
                    //NETLOGON_SERVICE_INFO structure.
                    if (logonInformation.LogonService == null
                        || logonInformation.LogonService.Length != 1)
                    {
                        throw new ArgumentException("logonInformation is invalid.", "logonInformation");
                    }

                    EncryptLmAndNtOwfPassword(
                        ref logonInformation.LogonService[0].LmOwfPassword,
                        ref logonInformation.LogonService[0].NtOwfPassword);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonServiceTransitiveInformation:
                    if (logonInformation.LogonServiceTransitive == null
                        || logonInformation.LogonServiceTransitive.Length != 1)
                    {
                        throw new ArgumentException("logonInformation is invalid.", "logonInformation");
                    }

                    EncryptLmAndNtOwfPassword(
                        ref logonInformation.LogonServiceTransitive[0].LmOwfPassword,
                        ref logonInformation.LogonServiceTransitive[0].NtOwfPassword);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonGenericInformation:
                    //If the LogonLevel is NetlogonGenericInformation,
                    //then encrypt<104> the LogonData member in the
                    //NETLOGON_GENERIC_INFO structure.
                    if (logonInformation.LogonGeneric == null
                        || logonInformation.LogonGeneric.Length != 1)
                    {
                        throw new ArgumentException("logonInformation is invalid.", "logonInformation");
                    }

                    //Encrypt the ClearNewPassword parameter using the RC4 algorithm
                    //and the session key established as the encryption key.
                    logonInformation.LogonGeneric[0].LogonData = NrpcUtility.EncryptBuffer(
                        IsAesOrRc4Negotiated(),
                        context.SessionKey,
                        logonInformation.LogonGeneric[0].LogonData);
                    break;

                case _NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkInformation:
                case _NETLOGON_LOGON_INFO_CLASS.NetlogonNetworkTransitiveInformation:
                    //If the LogonLevel is NetlogonNetworkInformation or
                    //NetlogonNetworkTransitiveInformation, then encrypt the
                    //UserSessionKey and the first two elements of the
                    //ExpansionRoom array in the NETLOGON_VALIDATION_SAM_INFO
                    //(section 2.2.1.4.11) or in the NETLOGON_VALIDATION_SAM_INFO2
                    //(section 2.2.1.4.12) structure.

                    //TODO: TDI 48320, there're no UserSessionKey and ExpansionRoom in NETLOGON_INFO class.

                    break;

                default:
                    throw new ArgumentException("logonLevel is invalid.", "logonLevel");
            }

            return logonInformation;
        }