internal SecurityPackageContextConnectionInformation (
			CipherAlgorithmType algorithmIdentifier,
			int cipherStrength,
			int exchangeStrength,
			HashAlgorithmType hash,
			int hashStrength,
			int keyExchangeAlgorithm,
			SecurityProtocol protocol)
		{
			AlgorithmIdentifier = algorithmIdentifier;
			CipherStrength = cipherStrength;
			ExchangeStrength = exchangeStrength;
			Hash = hash;
			HashStrength = hashStrength;
			KeyExchangeAlgorithm = keyExchangeAlgorithm;
			Protocol = protocol;
		}
Exemplo n.º 2
0
        public void StartProcess(
            Guid remoteSessionId,
            HostType hostType,
            SecurityProtocol securityProtocol,
            string serverAddress,
            string vmGuid,
            string userDomain,
            string userName,
            string startProgram,
            int clientWidth,
            int clientHeight,
            bool allowRemoteClipboard,
            bool allowPrintDownload,
            bool allowAudioPlayback)
        {
            Trace.TraceInformation("Calling service start process, remote session {0}, server {1}, domain {2}, user {3}, program {4}", remoteSessionId, serverAddress, string.IsNullOrEmpty(userDomain) ? "(none)" : userDomain, userName, string.IsNullOrEmpty(startProgram) ? "(none)" : startProgram);

            lock (_processStartLock)
            {
                try
                {
                    Channel.StartProcess(
                        remoteSessionId,
                        hostType,
                        securityProtocol,
                        serverAddress,
                        vmGuid,
                        userDomain,
                        userName,
                        startProgram,
                        clientWidth,
                        clientHeight,
                        allowRemoteClipboard,
                        allowPrintDownload,
                        allowAudioPlayback);

                    _processStarted = true;
                }
                catch (Exception exc)
                {
                    Trace.TraceError("Failed to call service start process, remote session {0} ({1})", _remoteSessionManager.RemoteSession.Id, exc);
                    throw;
                }
            }
        }
            protected internal override async Task OnOpenAsync(TimeSpan timeout)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

                EnableChannelBindingSupport();

                SecurityProtocol securityProtocol = SecurityProtocolFactory.CreateSecurityProtocol(
                    RemoteAddress,
                    Via,
                    null,
                    typeof(TChannel) == typeof(IRequestChannel),
                    timeoutHelper.RemainingTime());

                OnProtocolCreationComplete(securityProtocol);
                await SecurityProtocol.OpenAsync(timeoutHelper.RemainingTime());

                await base.OnOpenAsync(timeoutHelper.RemainingTime());
            }
Exemplo n.º 4
0
        public void run(ChocolateyConfiguration config, Container container, bool isConsole, Action <ICommand> parseArgs)
        {
            var tasks = container.GetAllInstances <ITask>();

            foreach (var task in tasks)
            {
                task.initialize();
            }

            fail_when_license_is_missing_or_invalid_if_requested(config);

            SecurityProtocol.set_protocol(config, provideWarning: true);

            EventManager.publish(new PreRunMessage(config));

            var command = find_command(config, container, isConsole, parseArgs);

            if (command != null)
            {
                if (config.Noop)
                {
                    if (config.RegularOutput)
                    {
                        this.Log().Info("_ {0}:{1} - Noop Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                    }

                    command.noop(config);
                }
                else
                {
                    this.Log().Debug("_ {0}:{1} - Normal Run Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                    command.run(config);
                }
            }

            EventManager.publish(new PostRunMessage(config));

            foreach (var task in tasks.or_empty_list_if_null())
            {
                task.shutdown();
            }

            remove_nuget_cache(container);
        }
        private void update_website(FinalResultMessage message)
        {
            SecurityProtocol.set_protocol();
            if (string.IsNullOrWhiteSpace(_configurationSettings.PackagesApiKey))
            {
                return;
            }

            this.Log().Info(() => "Updating website for {0} v{1} with cleanup ({2}).".format_with(message.PackageId, message.PackageVersion, message.Reject ? "rejecting stale package" : "sending reminder"));
            try
            {
                var        url    = string.Join("/", SERVICE_ENDPOINT, message.PackageId, message.PackageVersion);
                HttpClient client = _nugetService.get_client(_configurationSettings.PackagesUrl, url, "POST", "application/x-www-form-urlencoded");

                var postData = new StringBuilder();
                postData.Append("apikey=" + HttpUtility.UrlEncode(_configurationSettings.PackagesApiKey));
                postData.Append("&reject=" + HttpUtility.UrlEncode(message.Reject.to_string().to_lower()));
                postData.Append("&cleanupComments=" + HttpUtility.UrlEncode(message.ResultMessage));
                var form = postData.ToString();
                var data = Encoding.ASCII.GetBytes(form);

                client.SendingRequest += (sender, e) =>
                {
                    SendingRequest(this, e);
                    var request = (HttpWebRequest)e.Request;
                    request.Timeout = 30000;
                    request.Headers.Add(_nugetService.ApiKeyHeader, _configurationSettings.PackagesApiKey);

                    request.ContentLength = data.Length;

                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                };

                _nugetService.ensure_successful_response(client);
            }
            catch (Exception ex)
            {
                Bootstrap.handle_exception(ex);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sets up the request options.
        /// </summary>
        /// <param name="settings">The RuriLib settings</param>
        /// <param name="securityProtocol">The security protocol to use</param>
        /// <param name="autoRedirect">Whether to perform automatic redirection</param>
        /// <param name="acceptEncoding"></param>
        /// <param name="maxRedirects"></param>
        /// <returns></returns>
        public Request Setup(RLSettingsViewModel settings = null, SecurityProtocol securityProtocol = SecurityProtocol.SystemDefault,
                             bool autoRedirect            = true, int maxRedirects = 8, bool acceptEncoding = true)
        {
            // Setup options
            if (settings != null)
            {
                timeout = settings.General.RequestTimeout * 1000;
            }
            request.IgnoreProtocolErrors         = true;
            request.AllowAutoRedirect            = autoRedirect;
            request.EnableEncodingContent        = acceptEncoding;
            request.ReadWriteTimeout             = timeout;
            request.ConnectTimeout               = timeout;
            request.KeepAlive                    = true;
            request.MaximumAutomaticRedirections = maxRedirects;
            request.SslProtocols                 = securityProtocol.ToSslProtocols();

            return(this);
        }
Exemplo n.º 7
0
        public KafkaSink(
            string bootstrapServers,
            int batchSizeLimit,
            int period,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            Func <LogEvent, string> topicDecider,
            string saslUsername,
            string saslPassword,
            string sslCaLocation,
            ITextFormatter formatter = null) : base(batchSizeLimit, TimeSpan.FromSeconds(period))
        {
            ConfigureKafkaConnection(bootstrapServers, securityProtocol, saslMechanism, saslUsername,
                                     saslPassword, sslCaLocation);

            this.formatter = formatter ?? new Formatting.Json.JsonFormatter(renderMessage: true);

            this._topicDecider = topicDecider;
        }
        protected override IAsyncResult OnBeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            Fx.Assert(message.Headers.Action != message.Version.Addressing.DefaultFaultAction, "fault action in duplex.send");

            if (this.securityProtocol == null)
            {
                lock (ThisLock)
                {
                    if (this.securityProtocol == null)
                    {
                        this.securityProtocol = ((IPeerFactory)channelManager).SecurityManager.CreateSecurityProtocol <IDuplexChannel>(this.to, timeoutHelper.RemainingTime());
                    }
                }
            }
            return(this.peerNode.InnerNode.BeginSend(this, message, this.via, (ITransportFactorySettings)Manager,
                                                     timeoutHelper.RemainingTime(), callback, state, this.securityProtocol));
        }
Exemplo n.º 9
0
        public IEnumerable <T> list <T>(ChocolateyConfiguration config, Container container, bool isConsole, Action <ICommand> parseArgs)
        {
            var tasks = container.GetAllInstances <ITask>();

            foreach (var task in tasks)
            {
                task.initialize();
            }

            fail_when_license_is_missing_or_invalid_if_requested(config);
            SecurityProtocol.set_protocol(config, provideWarning: true);
            EventManager.publish(new PreRunMessage(config));

            try
            {
                var command = find_command(config, container, isConsole, parseArgs) as IListCommand <T>;
                if (command == null)
                {
                    if (!string.IsNullOrWhiteSpace(config.CommandName))
                    {
                        throw new Exception("The implementation of '{0}' does not support listing '{1}'".format_with(config.CommandName, typeof(T).Name));
                    }
                    return(new List <T>());
                }
                else
                {
                    this.Log().Debug("_ {0}:{1} - Normal List Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                    return(command.list(config));
                }
            }
            finally
            {
                EventManager.publish(new PostRunMessage(config));

                foreach (var task in tasks.or_empty_list_if_null())
                {
                    task.shutdown();
                }

                remove_nuget_cache(container, config);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///   The main entry point for the application.
        /// </summary>
        /// <param name="args">The args.</param>
        private static void Main(string[] args)
        {
            // Ensure that the correct Security Protocol is being used.  Do this as early
            // as possible, rather than having to do it in multiple places in the code
            // base.
            // Use TLS1.2, TLS1.1, TLS1.0, SSLv3
            SecurityProtocol.set_protocol();

            if ((args.Length > 0) && (Array.IndexOf(args, "/console") != -1))
            {
                var service = new Service();
                service.run_as_console(args);
            }
            else
            {
                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                var servicesToRun = new ServiceBase[] { new Service() };
                ServiceBase.Run(servicesToRun);
            }
        }
Exemplo n.º 11
0
        private void ConfigureKafkaConnection(string bootstrapServers, SecurityProtocol securityProtocol,
                                              SaslMechanism saslMechanism, string saslUsername, string saslPassword, string sslCaLocation)
        {
            var config = new ProducerConfig()
                         .SetValue("ApiVersionFallbackMs", 0)
                         .SetValue("EnableDeliveryReports", false)
                         .LoadFromEnvironmentVariables()
                         .SetValue("BootstrapServers", bootstrapServers)
                         .SetValue("SecurityProtocol", securityProtocol)
                         .SetValue("SaslMechanism", saslMechanism)
                         .SetValue("SslCaLocation",
                                   string.IsNullOrEmpty(sslCaLocation)
                        ? null
                        : Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), sslCaLocation))
                         .SetValue("SaslUsername", saslUsername)
                         .SetValue("SaslPassword", saslPassword);

            producer = new ProducerBuilder <Null, byte[]>(config)
                       .Build();
        }
Exemplo n.º 12
0
        public int count(ChocolateyConfiguration config, Container container, bool isConsole, Action <ICommand> parseArgs)
        {
            SecurityProtocol.set_protocol(config, provideWarning: true);

            var command = find_command(config, container, isConsole, parseArgs) as IListCommand;

            if (command == null)
            {
                if (!string.IsNullOrWhiteSpace(config.CommandName))
                {
                    throw new Exception("The implementation of '{0}' does not support listing.".format_with(config.CommandName));
                }
                return(0);
            }
            else
            {
                this.Log().Debug("_ {0}:{1} - Normal Count Mode _".format_with(ApplicationParameters.Name, command.GetType().Name));
                return(command.count(config));
            }
        }
Exemplo n.º 13
0
        //Reference OnAcceptChannel/SecurityChannelListner
        private async Task <IServiceChannelDispatcher> GetInnerChannelDispatcherAsync(IChannel outerChannel)
        {
            IServiceChannelDispatcher securityChannelDispatcher = null;
            SecurityProtocol          securityProtocol          = SecurityProtocolFactory.CreateSecurityProtocol(null, null,
                                                                                                                 (outerChannel is IReplyChannel || outerChannel is IReplySessionChannel), TimeSpan.Zero);
            await securityProtocol.OpenAsync(TimeSpan.Zero);

            /* TODO once we add more features
             * if (outerChannel is IInputChannel)
             * {
             *  securityChannel = new SecurityInputChannel(listener, (IInputChannel)innerChannel, securityProtocol, listener.settingsLifetimeManager);
             * }
             * else if (outerChannel is IInputSessionChannel))
             * {
             *  securityChannel = new SecurityInputSessionChannel(listener, (IInputSessionChannel)innerChannel, securityProtocol, listener.settingsLifetimeManager);
             * }
             * else if (outerChannel is IDuplexChannel))
             * {
             *  securityChannel = new SecurityDuplexChannel(listener, (IDuplexChannel)innerChannel, securityProtocol, listener.settingsLifetimeManager);
             * }
             * else if (outerChannel is IDuplexSessionChannel))
             * {
             *  securityChannel = new SecurityDuplexSessionChannel(listener, (IDuplexSessionChannel)innerChannel, securityProtocol, listener.settingsLifetimeManager);
             * }
             * else*/
            if (outerChannel is IReplyChannel replyChannel)
            {
                securityChannelDispatcher = new SecurityReplyChannelDispatcher(this, replyChannel, securityProtocol, _settingsLifetimeManager);
            }

            /* else if (listener.SupportsRequestReply && typeof(TChannel) == typeof(IReplySessionChannel))
             * {
             *   securityChannel = new SecurityReplySessionChannel(listener, (IReplySessionChannel)innerChannel, securityProtocol, listener.settingsLifetimeManager);
             * }
             * else
             * {
             *   throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.UnsupportedChannelInterfaceType, typeof(TChannel))));
             * }*/

            return(securityChannelDispatcher);
        }
Exemplo n.º 14
0
        public void Init(string notificationSettingsString)
        {
            var dict = ParseValue(notificationSettingsString);

            if (!dict.TryGetValue("groupid", out var _groupId))
            {
                throw new ArgumentException($"Не указан groupid для подключения к Kafka", "groupid");
            }
            GroupId = _groupId;

            dict.TryGetValue("clientid", out var _clientId);
            ClientId = _clientId;

            string server = string.Empty;

            if (dict.TryGetValue("servers", out server))
            {
                Servers = server.Split(',').Select(n => n.Trim());
            }
            else
            {
                throw new ArgumentException($"Не указан servers для подключения к Kafka", "servers");
            }

            if (!Servers.Any())
            {
                throw new ArgumentException($"Не удалось распарсить servers для подключения к Kafka (формат поля: 'servername1:port1, servername2:port2, servername3:port3.....')");
            }

            dict.TryGetValue("securityprotocol", out var _securityProtocol);
            SecurityProtocol = _securityProtocol;

            switch (SecurityProtocol?.ToUpper())
            {
            case "SASL_PLAINTEXT":
                SaslConfig = new SaslConfig();
                SaslConfig.Init(dict);
                break;
            }
        }
Exemplo n.º 15
0
            public async Task <Message> RequestAsync(Message message, TimeSpan timeout)
            {
                ThrowIfFaulted();
                ThrowIfDisposedOrNotOpen(message);
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                SecurityProtocolCorrelationState correlationState;

                (correlationState, message) = await SecurityProtocol.SecureOutgoingMessageAsync(message, timeoutHelper.RemainingTime(), null);

                Message reply;

                if (InnerChannel is IAsyncRequestChannel asyncRequestChannel)
                {
                    reply = await asyncRequestChannel.RequestAsync(message, timeoutHelper.RemainingTime());
                }
                else
                {
                    reply = await Task.Factory.FromAsync(InnerChannel.BeginRequest, InnerChannel.EndRequest, message, timeoutHelper.RemainingTime(), null);
                }

                return(ProcessReply(reply, correlationState, timeoutHelper.RemainingTime()));
            }
        private static LoggerConfiguration Kafka(
            this LoggerSinkConfiguration loggerConfiguration,
            string bootstrapServers,
            int batchSizeLimit,
            int period,
            SecurityProtocol securityProtocol,
            SaslMechanism saslMechanism,
            string saslUsername,
            string saslPassword,
            string sslCaLocation,
            string topic,
            Func <LogEvent, string> topicDecider,
            ITextFormatter formatter)
        {
            var kafkaSink = new KafkaSink(
                bootstrapServers,
                securityProtocol,
                saslMechanism,
                saslUsername,
                saslPassword,
                sslCaLocation,
                topic,
                topicDecider,
                formatter);

            var batchingOptions = new PeriodicBatchingSinkOptions
            {
                BatchSizeLimit = batchSizeLimit,
                Period         = TimeSpan.FromSeconds(period)
            };

            var batchingSink = new PeriodicBatchingSink(
                kafkaSink,
                batchingOptions);

            return(loggerConfiguration
                   .Sink(batchingSink));
        }
        /// <summary>
        /// Converts the SecurityProtocol to an SslProtocols enum. Multiple protocols are not supported and SystemDefault is None.
        /// </summary>
        /// <param name="protocol">The SecurityProtocol</param>
        /// <returns>The converted SslProtocols.</returns>
        public static SslProtocols ToSslProtocols(this SecurityProtocol protocol)
        {
            switch (protocol)
            {
            case SecurityProtocol.SystemDefault:
                return(SslProtocols.None);

            case SecurityProtocol.SSL3:
                return(SslProtocols.Ssl3);

            case SecurityProtocol.TLS10:
                return(SslProtocols.Tls);

            case SecurityProtocol.TLS11:
                return(SslProtocols.Tls11);

            case SecurityProtocol.TLS12:
                return(SslProtocols.Tls12);

            default:
                throw new Exception("Protocol not supported");
            }
        }
Exemplo n.º 18
0
        public PeerMessageDispatcher(PeerMessageQueueAdapter queueHandler, PeerNodeImplementation peerNode, ChannelManagerBase channelManager, EndpointAddress to, Uri via)
        {
            PeerNodeImplementation.ValidateVia(via);

            this.queueHandler   = queueHandler;
            this.peerNode       = peerNode;
            this.to             = to;
            this.via            = via;
            this.channelManager = channelManager;
            EndpointAddress filterTo = null;

            this.securityProtocol = ((IPeerFactory)channelManager).SecurityManager.CreateSecurityProtocol <ChannelInterfaceType>(to, ServiceDefaults.SendTimeout);

            if (typeof(IDuplexChannel).IsAssignableFrom(typeof(ChannelInterfaceType)))
            {
                filterTo = to;
            }

            //Register this handler
            PeerMessageFilter[] filters = new PeerMessageFilter[] { new PeerMessageFilter(via, filterTo) };
            peerNode.RegisterMessageFilter(this, this.via, filters, (ITransportFactorySettings)this.channelManager,
                                           new PeerNodeImplementation.MessageAvailableCallback(OnMessageAvailable), securityProtocol);
            registered = true;
        }
Exemplo n.º 19
0
        /// <inheritdoc />
        public override BlockBase FromLS(string line)
        {
            // Trim the line
            var input = line.Trim();

            // Parse the label
            if (input.StartsWith("#"))
            {
                Label = LineParser.ParseLabel(ref input);
            }

            /*
             * Syntax
             * BYPASSCF "URL" SECPROTO PROTOCOL ["UA"]
             * */

            Url = LineParser.ParseLiteral(ref input, "URL");

            if (input != "" && LineParser.Lookahead(ref input) == TokenType.Literal)
            {
                UserAgent = LineParser.ParseLiteral(ref input, "UA");
            }

            if (input != "" && LineParser.ParseToken(ref input, TokenType.Parameter, false, false) == "SECPROTO")
            {
                LineParser.ParseToken(ref input, TokenType.Parameter, true);
                SecurityProtocol = LineParser.ParseEnum(ref input, "Security Protocol", typeof(SecurityProtocol));
            }

            while (input != "")
            {
                LineParser.SetBool(ref input, this);
            }

            return(this);
        }
 public void SecureOutgoingMessage(ref Message message, Uri via, TimeSpan timeout, SecurityProtocol securityProtocol)
 {
     if (securityProtocol != null)
     {
         securityProtocol.SecureOutgoingMessage(ref message, timeout);
     }
 }
 // internal message filtering
 internal void RegisterMessageFilter(object registrant, Uri via, PeerMessageFilter[] filters,
     ITransportFactorySettings settings, MessageAvailableCallback callback, SecurityProtocol securityProtocol)
 {
     MessageFilterRegistration registration = new MessageFilterRegistration();
     registration.registrant = registrant;
     registration.via = via;
     registration.filters = filters;
     registration.settings = settings;
     registration.callback = callback;
     registration.securityProtocol = securityProtocol;
     lock (ThisLock)
     {
         messageFilters.Add(registrant, registration);
         RefCountedSecurityProtocol protocolWrapper = null;
         if (!this.uri2SecurityProtocol.TryGetValue(via, out protocolWrapper))
         {
             protocolWrapper = new RefCountedSecurityProtocol(securityProtocol);
             this.uri2SecurityProtocol.Add(via, protocolWrapper);
         }
         else
             protocolWrapper.AddRef();
     }
 }
 public RefCountedSecurityProtocol(SecurityProtocol securityProtocol)
 {
     this.Protocol = securityProtocol;
     this.refCount = 1;
 }
Exemplo n.º 23
0
        public static async Task Run_Consumer <TKey, TValue>(string brokerList, List <string> consumerTopics, string producerTopic,
                                                             SecurityProtocol securityProtocol, SaslMechanism saslMechanism, string saslUsername, string saslPassword,
                                                             string schemaRegistryUrl, string basicAuthUserInfo, CancellationToken cancellationToken)
            where TKey : class, IMessage <TKey>, new()
            where TValue : class, IMessage <TValue>, new()
        {
            var config = new ConsumerConfig
            {
                BootstrapServers     = brokerList,
                GroupId              = "csharp-consumer",
                EnableAutoCommit     = false,
                StatisticsIntervalMs = 5000,
                SessionTimeoutMs     = 6000,
                AutoOffsetReset      = AutoOffsetReset.Earliest,
                EnablePartitionEof   = true,
            };

            const int commitPeriod = 5;

            using (var consumer = new ConsumerBuilder <Ignore, TValue>(config)
                                  .SetErrorHandler((_, e) => Console.WriteLine($"Error: {e.Reason}"))
                                  .SetPartitionsAssignedHandler((c, partitions) =>
            {
                Console.WriteLine($"Assigned partitions: [{string.Join(", ", partitions)}]\n");
            })
                                  .SetPartitionsRevokedHandler((c, partitions) =>
            {
                Console.WriteLine($"Revoking assignment: [{string.Join(", ", partitions)}]");
            })
                                  // Set value Protobuf deserializer
                                  .SetValueDeserializer(new ProtobufDeserializer <TValue>().AsSyncOverAsync())
                                  .Build())
            {
                consumer.Subscribe(consumerTopics);

                try
                {
                    while (true)
                    {
                        try
                        {
                            var consumeResult = consumer.Consume(cancellationToken);

                            if (consumeResult.IsPartitionEOF)
                            {
                                Console.WriteLine(
                                    $"Reached end of topic {consumeResult.Topic}, partition {consumeResult.Partition}, offset {consumeResult.Offset}.");

                                continue;
                            }

                            PrintConsumeResult(consumeResult);

                            if (consumeResult.Offset % commitPeriod == 0)
                            {
                                try
                                {
                                    consumer.Commit(consumeResult);
                                }
                                catch (KafkaException e)
                                {
                                    Console.WriteLine($"Commit error: {e.Error.Reason}");
                                }
                            }

                            await Run_Producer <TKey, TValue>(brokerList, producerTopic, securityProtocol, saslMechanism,
                                                              saslUsername, saslPassword, schemaRegistryUrl, basicAuthUserInfo, consumeResult.Message);
                        }
                        catch (ConsumeException e)
                        {
                            Console.WriteLine($"Consume error: {e.Error.Reason}");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("Closing consumer.");
                    consumer.Close();
                }
            }
        }
Exemplo n.º 24
0
 public virtual void AuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);
     _sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation);
     _sslState.ProcessAuthentication(null);
 }
Exemplo n.º 25
0
#pragma warning restore CS0067

        public SecurityReplyChannelDispatcher(SecurityServiceDispatcher securityServiceDispatcher, IReplyChannel innerChannel, SecurityProtocol securityProtocol, SecurityListenerSettingsLifetimeManager settingsLifetimeManager)
            : base(securityServiceDispatcher, innerChannel, securityProtocol, settingsLifetimeManager)
        {
            _sendUnsecuredFaults      = securityServiceDispatcher.SendUnsecuredFaults;
            SecurityServiceDispatcher = securityServiceDispatcher;
        }
Exemplo n.º 26
0
        public void StartProcess(
            Guid remoteSessionId,
            HostType hostType,
            SecurityProtocol securityProtocol,
            string serverAddress,
            string vmGuid,
            string userDomain,
            string userName,
            string startProgram,
            int clientWidth,
            int clientHeight,
            bool allowRemoteClipboard,
            bool allowPrintDownload,
            bool allowAudioPlayback)
        {
            Trace.TraceInformation("Connecting remote session {0}, type {1}, security {2}, server (:port) {3}, vm {4}, domain {5}, user {6}, program {7}",
                                   remoteSessionId,
                                   hostType,
                                   hostType == HostType.RDP ? securityProtocol.ToString().ToUpper() : "N/A",
                                   serverAddress,
                                   hostType == HostType.RDP ? (string.IsNullOrEmpty(vmGuid) ? "(none)" : vmGuid) : "N/A",
                                   hostType == HostType.RDP ? (string.IsNullOrEmpty(userDomain) ? "(none)" : userDomain) : "N/A",
                                   userName,
                                   hostType == HostType.RDP ? (string.IsNullOrEmpty(startProgram) ? "(none)" : startProgram) : "N/A");

            try
            {
                // set the remote session id
                // the wcf service binding "wsDualHttpBinding" is "perSession" by default (maintain 1 service instance per client)
                // as there is 1 client per remote session, the remote session id is set for the current service instance
                _remoteSessionId = remoteSessionId;

                _process = new Process();

                // select the host client executable based on the host type
                var clientFilePath = string.Empty;
                var clientFileName = string.Empty;
                switch (hostType)
                {
                // see https://github.com/cedrozor/myrtille/blob/master/DOCUMENTATION.md#build for information and steps to build FreeRDP along with myrtille
                case HostType.RDP:
                    clientFilePath = @"Myrtille.RDP\FreeRDP";
                    clientFileName = "wfreerdp.exe";
                    break;

                case HostType.SSH:
                    clientFilePath = @"Myrtille.SSH\bin";
                    clientFileName = "Myrtille.SSH.exe";
                    break;
                }

                if (Environment.UserInteractive)
                {
                    _process.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.Replace(@"Myrtille.Services\bin", clientFilePath), clientFileName);
                }
                else
                {
                    _process.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, clientFileName);
                }

                // ensure the host client executable does exists
                if (!File.Exists(_process.StartInfo.FileName))
                {
                    var msg = string.Format("The host client executable ({0}) is missing. Please read documentation for steps to build it", _process.StartInfo.FileName);
                    if (Environment.UserInteractive)
                    {
                        MessageBox.Show(msg);
                    }
                    Trace.TraceError(msg);
                    return;
                }

                // log remote session events into a file (located into <Myrtille folder>\log)
                bool remoteSessionLog;
                if (!bool.TryParse(ConfigurationManager.AppSettings["RemoteSessionLog"], out remoteSessionLog))
                {
                    remoteSessionLog = false;
                }

                #region RDP

                if (hostType == HostType.RDP)
                {
                    // color depth
                    int bpp;
                    if (!int.TryParse(ConfigurationManager.AppSettings["FreeRDPBpp"], out bpp))
                    {
                        bpp = 16;
                    }

                    // gdi mode (sw: software, hw: hardware). default software because there is a palette issue with windows server 2008; also, the performance gain is small and even null on most virtual machines, when hardware isn't available
                    var gdi = "sw";
                    if (ConfigurationManager.AppSettings["FreeRDPGdi"] != null)
                    {
                        gdi = ConfigurationManager.AppSettings["FreeRDPGdi"];
                    }

                    // wallpaper
                    bool wallpaper;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPWallpaper"], out wallpaper))
                    {
                        wallpaper = false;
                    }

                    // desktop composition
                    bool aero;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPAero"], out aero))
                    {
                        aero = false;
                    }

                    // window drag
                    bool windowDrag;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPWindowDrag"], out windowDrag))
                    {
                        windowDrag = false;
                    }

                    // menu animations
                    bool menuAnims;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPMenuAnims"], out menuAnims))
                    {
                        menuAnims = false;
                    }

                    // themes
                    bool themes;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPThemes"], out themes))
                    {
                        themes = false;
                    }

                    // smooth fonts (requires ClearType enabled on the remote server)
                    bool smoothFonts;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPSmoothFonts"], out smoothFonts))
                    {
                        smoothFonts = true;
                    }

                    // ignore certificate warning (when using NLA); may happen, for example, with a self-signed certificate (not trusted) or if the server joined a domain after the certificate was issued (name mismatch). more details here: http://www.vkernel.ro/blog/configuring-certificates-in-2012r2-remote-desktop-services-rds
                    bool certIgnore;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPCertIgnore"], out certIgnore))
                    {
                        certIgnore = true;
                    }

                    // the params below have optimal (performance oriented) values and shouldn't be changed (except in case of any issue)
                    bool compression;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPCompression"], out compression))
                    {
                        compression = true;
                    }

                    bool mouseMotion;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPMouseMotion"], out mouseMotion))
                    {
                        mouseMotion = false;
                    }

                    bool bitmapCache;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPBitmapCache"], out bitmapCache))
                    {
                        bitmapCache = true;
                    }

                    bool offscreenCache;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPOffscreenCache"], out offscreenCache))
                    {
                        offscreenCache = false;
                    }

                    bool glyphCache;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPGlyphCache"], out glyphCache))
                    {
                        glyphCache = true;
                    }

                    bool asyncInput;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPAsyncInput"], out asyncInput))
                    {
                        asyncInput = false;
                    }

                    bool asyncUpdate;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPAsyncUpdate"], out asyncUpdate))
                    {
                        asyncUpdate = false;
                    }

                    bool asyncChannels;
                    if (!bool.TryParse(ConfigurationManager.AppSettings["FreeRDPAsyncChannels"], out asyncChannels))
                    {
                        asyncChannels = false;
                    }

                    // pdf virtual printer redirection

                    // TOCHECK: for some reason, using the exact pdf virtual printer driver name ("PDF Scribe Virtual Printer") doesn't work (the printer doesn't show into the remote session) with wfreerdp, while it works with mstsc (!)
                    // it may have something to do with the driver not being installed on the remote server, but as the underlying driver is the standard "Microsoft Postscript Printer Driver (v3)" (pscript5.dll), it should have worked...
                    // as a workaround for now, the same way freerdp does in CUPS mode (printer redirection under Linux), it's possible to use the "MS Publisher Imagesetter" driver; it's also based on pscript5.dll and support basic print features (portrait/landscape orientation, custom fonts, color mode, etc.)

                    // as the rdp server uses the client numlock state, ensure it's off
                    // server side, ensure that HKEY_USERS\.DEFAULT\Control Panel\Keyboard: InitialKeyboardIndicators is set to 0 (numlock off)
                    SetNumLock(false);

                    // https://github.com/FreeRDP/FreeRDP/wiki/CommandLineInterface
                    // Syntax: /flag enables flag, +toggle or -toggle enables or disables toggle. /toggle and +toggle are the same. Options with values work like this: /option:<value>
                    // as the process command line can be displayed into the task manager / process explorer, the connection settings (including user credentials) are now passed to the rdp client through the inputs pipe
                    _process.StartInfo.Arguments =
                        "/myrtille-sid:" + _remoteSessionId +                                                                   // session id
                        (!Environment.UserInteractive ? string.Empty : " /myrtille-window") +                                   // session window
                        (!remoteSessionLog ? string.Empty : " /myrtille-log") +                                                 // session log
                        " /w:" + clientWidth +                                                                                  // display width
                        " /h:" + clientHeight +                                                                                 // display height
                        " /bpp:" + bpp +                                                                                        // color depth
                        " /gdi:" + gdi +                                                                                        // gdi mode (sw: software, hw: hardware)
                        (wallpaper ? " +" : " -") + "wallpaper" +                                                               // wallpaper
                        (aero ? " +" : " -") + "aero" +                                                                         // desktop composition
                        (windowDrag ? " +" : " -") + "window-drag" +                                                            // window drag
                        (menuAnims ? " +" : " -") + "menu-anims" +                                                              // menu animations
                        (themes ? " +" : " -") + "themes" +                                                                     // themes
                        (smoothFonts ? " +" : " -") + "fonts" +                                                                 // smooth fonts (requires ClearType enabled on the remote server)
                        (compression ? " +" : " -") + "compression" +                                                           // bulk compression (level is autodetected from the rdp version)
                        (certIgnore ? " /cert-ignore" : string.Empty) +                                                         // ignore certificate warning (when using NLA)
                        (allowPrintDownload ? " /printer:\"Myrtille PDF\",\"MS Publisher Imagesetter\"" : string.Empty) +       // pdf virtual printer
                        (mouseMotion ? " +" : " -") + "mouse-motion" +                                                          // mouse motion
                        (bitmapCache ? " +" : " -") + "bitmap-cache" +                                                          // bitmap cache
                        (offscreenCache ? " +" : " -") + "offscreen-cache" +                                                    // offscreen cache
                        (glyphCache ? " +" : " -") + "glyph-cache" +                                                            // glyph cache
                        (asyncInput ? " +" : " -") + "async-input" +                                                            // async input
                        (asyncUpdate ? " +" : " -") + "async-update" +                                                          // async update
                        (asyncChannels ? " +" : " -") + "async-channels" +                                                      // async channels
                        (allowRemoteClipboard ? " +" : " -") + "clipboard" +                                                    // clipboard support
                        (securityProtocol != SecurityProtocol.auto ? " /sec:" + securityProtocol.ToString() : string.Empty) +   // security protocol
                        (allowAudioPlayback ? " /sound" : string.Empty) +                                                       // sound support
                        " /audio-mode:" + (allowAudioPlayback ? "0" : "2");                                                     // audio mode (0: redirect, 1: play on server, 2: do not play)
                }

                #endregion

                #region SSH

                else
                {
                    _process.StartInfo.Arguments =
                        "/myrtille-sid:" + _remoteSessionId +                                                                       // session id
                        (!Environment.UserInteractive ? string.Empty : " /myrtille-window") +                                       // session window
                        (!remoteSessionLog ? string.Empty : " /myrtille-log") +                                                     // session log
                        " /w:" + clientWidth +                                                                                      // display width
                        " /h:" + clientHeight;                                                                                      // display height
                }

                #endregion

                if (!Environment.UserInteractive)
                {
                    _process.StartInfo.UseShellExecute        = false;
                    _process.StartInfo.RedirectStandardError  = true;
                    _process.StartInfo.RedirectStandardInput  = true;
                    _process.StartInfo.RedirectStandardOutput = true;
                    _process.StartInfo.CreateNoWindow         = true;
                    _process.StartInfo.ErrorDialog            = false;
                    _process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                }

                _process.EnableRaisingEvents = true;
                _process.Exited += ProcessExited;

                // set the callback instance
                // the wcf service binding "wsDualHttpBinding" allows for duplex communication
                _callback = OperationContext.Current.GetCallbackChannel <IRemoteSessionProcessCallback>();

                _process.Start();
            }
            catch (Exception exc)
            {
                Trace.TraceError("Failed to start the host client process, remote session {0} ({1})", _remoteSessionId, exc);
            }
        }
Exemplo n.º 27
0
 private void OnProtocolCreationComplete(SecurityProtocol securityProtocol)
 {
     base.SecurityProtocol = securityProtocol;
     base.SecurityProtocol.ChannelParameters = this.channelParameters;
 }
 internal bool TryGetSecurityProtocol(Uri via, out SecurityProtocol protocol)
 {
     lock (this.ThisLock)
     {
         RefCountedSecurityProtocol protocol2 = null;
         bool flag = false;
         protocol = null;
         if (this.uri2SecurityProtocol.TryGetValue(via, out protocol2))
         {
             protocol = protocol2.Protocol;
             flag = true;
         }
         return flag;
     }
 }
Exemplo n.º 29
0
        public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
        {
            SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);

            return(Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsClient, null));
        }
 private void OnProtocolCreationComplete(SecurityProtocol securityProtocol)
 {
     SecurityProtocol = securityProtocol;
     SecurityProtocol.ChannelParameters = _channelParameters;
 }
Exemplo n.º 31
0
        public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
        {
            SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);

            return(Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsServer, null));
        }
        public IAsyncResult BeginSend(object registrant, Message message, Uri via,
            ITransportFactorySettings settings, TimeSpan timeout, AsyncCallback callback, object state, SecurityProtocol securityProtocol)
        {
            PeerFlooder localFlooder;
            int factoryMaxReceivedMessageSize;
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);

            MessageBuffer messageBuffer = null;
            Message securedMessage = null;
            ulong hopcount = PeerTransportConstants.MaxHopCount;
            PeerMessagePropagation propagateFlags = PeerMessagePropagation.LocalAndRemote;
            int messageSize = (int)-1;
            byte[] id;
            SendAsyncResult result = new SendAsyncResult(callback, state);
            AsyncCallback onFloodComplete = Fx.ThunkCallback(new AsyncCallback(result.OnFloodComplete));

            try
            {
                lock (ThisLock)
                {
                    ThrowIfNotOpen();
                    localFlooder = flooder;
                }

                // we know this will fit in an int because of our MaxReceivedMessageSize restrictions
                factoryMaxReceivedMessageSize = (int)Math.Min(maxReceivedMessageSize, settings.MaxReceivedMessageSize);
                Guid guid = ProcessOutgoingMessage(message, via);
                SecureOutgoingMessage(ref message, via, timeout, securityProtocol);
                if ((message is SecurityAppliedMessage))
                {
                    ArraySegment<byte> buffer = encoder.WriteMessage(message, int.MaxValue, bufferManager);
                    securedMessage = encoder.ReadMessage(buffer, bufferManager);
                    id = (message as SecurityAppliedMessage).PrimarySignatureValue;
                    messageSize = (int)buffer.Count;
                }
                else
                {
                    securedMessage = message;
                    id = guid.ToByteArray();
                }

                messageBuffer = securedMessage.CreateBufferedCopy(factoryMaxReceivedMessageSize);
                string contentType = settings.MessageEncoderFactory.Encoder.ContentType;
                if (this.messagePropagationFilter != null)
                {
                    using (Message filterMessage = messageBuffer.CreateMessage())
                    {
                        propagateFlags = ((IPeerNodeMessageHandling)this).DetermineMessagePropagation(filterMessage, PeerMessageOrigination.Local);
                    }
                }

                if ((propagateFlags & PeerMessagePropagation.Remote) != PeerMessagePropagation.None)
                {
                    if (hopcount == 0)
                        propagateFlags &= ~PeerMessagePropagation.Remote;
                }

                // flood it out
                IAsyncResult ar = null;
                if ((propagateFlags & PeerMessagePropagation.Remote) != 0)
                {
                    ar = localFlooder.BeginFloodEncodedMessage(id, messageBuffer, timeoutHelper.RemainingTime(), onFloodComplete, null);
                    if (DiagnosticUtility.ShouldTraceVerbose)
                    {
                        TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerChannelMessageSent, SR.GetString(SR.TraceCodePeerChannelMessageSent), this, message);
                    }
                }
                else
                {
                    ar = new CompletedAsyncResult(onFloodComplete, null);
                }
                if (ar == null)
                {
                    Fx.Assert("SendAsyncResult must have an Async Result for onFloodComplete");
                }

                // queue up the pre-encoded message for local channels
                if ((propagateFlags & PeerMessagePropagation.Local) != 0)
                {
                    using (Message msg = messageBuffer.CreateMessage())
                    {
                        int i = msg.Headers.FindHeader(SecurityJan2004Strings.Security, SecurityJan2004Strings.Namespace);
                        if (i >= 0)
                        {
                            msg.Headers.AddUnderstood(i);
                        }
                        using (MessageBuffer clientBuffer = msg.CreateBufferedCopy(factoryMaxReceivedMessageSize))
                        {
                            DeliverMessageToClientChannels(registrant, clientBuffer, via, message.Headers.To, contentType, messageSize, -1, null);
                        }
                    }
                }
                result.OnLocalDispatchComplete(result);
            }
            finally
            {
                message.Close();
                if (securedMessage != null)
                    securedMessage.Close();
                if (messageBuffer != null)
                    messageBuffer.Close();
            }

            return result;
        }
Exemplo n.º 33
0
 public RequestChannelSendAsyncResult(Message message, SecurityProtocol protocol, IRequestChannel channel, SecurityChannelFactory <TChannel> .SecurityRequestChannel securityChannel, TimeSpan timeout, AsyncCallback callback, object state) : base(protocol, channel, timeout, callback, state)
 {
     this.securityChannel = securityChannel;
     base.Begin(message, null);
 }
 internal bool TryGetSecurityProtocol(Uri via, out SecurityProtocol protocol)
 {
     lock (ThisLock)
     {
         RefCountedSecurityProtocol wrapper = null;
         bool result = false;
         protocol = null;
         if (uri2SecurityProtocol.TryGetValue(via, out wrapper))
         {
             protocol = wrapper.Protocol;
             result = true;
         }
         return result;
     }
 }
 public IAsyncResult BeginSend(object registrant, Message message, Uri via, ITransportFactorySettings settings, TimeSpan timeout, AsyncCallback callback, object state, SecurityProtocol securityProtocol)
 {
     TimeoutHelper helper = new TimeoutHelper(timeout);
     MessageBuffer encodedMessage = null;
     Message message2 = null;
     ulong maxValue = ulong.MaxValue;
     PeerMessagePropagation localAndRemote = PeerMessagePropagation.LocalAndRemote;
     int messageSize = -1;
     SendAsyncResult result = new SendAsyncResult(callback, state);
     AsyncCallback callback2 = Fx.ThunkCallback(new AsyncCallback(result.OnFloodComplete));
     try
     {
         PeerFlooder flooder;
         byte[] primarySignatureValue;
         lock (this.ThisLock)
         {
             this.ThrowIfNotOpen();
             flooder = this.flooder;
         }
         int maxBufferSize = (int) Math.Min(this.maxReceivedMessageSize, settings.MaxReceivedMessageSize);
         Guid guid = this.ProcessOutgoingMessage(message, via);
         this.SecureOutgoingMessage(ref message, via, timeout, securityProtocol);
         if (message is SecurityAppliedMessage)
         {
             ArraySegment<byte> buffer = this.encoder.WriteMessage(message, 0x7fffffff, this.bufferManager);
             message2 = this.encoder.ReadMessage(buffer, this.bufferManager);
             primarySignatureValue = (message as SecurityAppliedMessage).PrimarySignatureValue;
             messageSize = buffer.Count;
         }
         else
         {
             message2 = message;
             primarySignatureValue = guid.ToByteArray();
         }
         encodedMessage = message2.CreateBufferedCopy(maxBufferSize);
         string contentType = settings.MessageEncoderFactory.Encoder.ContentType;
         if (this.messagePropagationFilter != null)
         {
             using (Message message3 = encodedMessage.CreateMessage())
             {
                 localAndRemote = ((IPeerNodeMessageHandling) this).DetermineMessagePropagation(message3, PeerMessageOrigination.Local);
             }
         }
         if (((localAndRemote & PeerMessagePropagation.Remote) != PeerMessagePropagation.None) && (maxValue == 0L))
         {
             localAndRemote &= ~PeerMessagePropagation.Remote;
         }
         IAsyncResult result2 = null;
         if ((localAndRemote & PeerMessagePropagation.Remote) != PeerMessagePropagation.None)
         {
             result2 = flooder.BeginFloodEncodedMessage(primarySignatureValue, encodedMessage, helper.RemainingTime(), callback2, null);
             if (System.ServiceModel.DiagnosticUtility.ShouldTraceVerbose)
             {
                 TraceUtility.TraceEvent(TraceEventType.Verbose, 0x4003e, System.ServiceModel.SR.GetString("TraceCodePeerChannelMessageSent"), this, message);
             }
         }
         else
         {
             result2 = new CompletedAsyncResult(callback2, null);
         }
         if ((localAndRemote & PeerMessagePropagation.Local) != PeerMessagePropagation.None)
         {
             using (Message message4 = encodedMessage.CreateMessage())
             {
                 int i = message4.Headers.FindHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
                 if (i >= 0)
                 {
                     message4.Headers.AddUnderstood(i);
                 }
                 using (MessageBuffer buffer3 = message4.CreateBufferedCopy(maxBufferSize))
                 {
                     this.DeliverMessageToClientChannels(registrant, buffer3, via, message.Headers.To, contentType, messageSize, -1, null);
                 }
             }
         }
         result.OnLocalDispatchComplete(result);
     }
     finally
     {
         message.Close();
         if (message2 != null)
         {
             message2.Close();
         }
         if (encodedMessage != null)
         {
             encodedMessage.Close();
         }
     }
     return result;
 }
Exemplo n.º 36
0
 protected ServerSecurityChannelDispatcher(SecurityServiceDispatcher securityServiceDispatcher, UChannel innerChannel, SecurityProtocol securityProtocol, SecurityListenerSettingsLifetimeManager settingsLifetimeManager)
 {
     SecurityProtocol = securityProtocol;
     OuterChannel     = (IReplyChannel)innerChannel;
     _serviceProvider = OuterChannel.GetProperty <IServiceScopeFactory>().CreateScope().ServiceProvider;
     _secureConversationCloseAction = securityProtocol.SecurityProtocolFactory.StandardsManager.SecureConversationDriver.CloseAction.Value;
 }
 internal void RegisterMessageFilter(object registrant, Uri via, PeerMessageFilter[] filters, ITransportFactorySettings settings, MessageAvailableCallback callback, SecurityProtocol securityProtocol)
 {
     MessageFilterRegistration registration = new MessageFilterRegistration {
         registrant = registrant,
         via = via,
         filters = filters,
         settings = settings,
         callback = callback,
         securityProtocol = securityProtocol
     };
     lock (this.ThisLock)
     {
         this.messageFilters.Add(registrant, registration);
         RefCountedSecurityProtocol protocol = null;
         if (!this.uri2SecurityProtocol.TryGetValue(via, out protocol))
         {
             protocol = new RefCountedSecurityProtocol(securityProtocol);
             this.uri2SecurityProtocol.Add(via, protocol);
         }
         else
         {
             protocol.AddRef();
         }
     }
 }
Exemplo n.º 38
0
        public void prepare_powershell_environment(IPackage package, ChocolateyConfiguration configuration, string packageDirectory)
        {
            if (package == null)
            {
                return;
            }

            EnvironmentSettings.update_environment_variables();
            EnvironmentSettings.set_environment_variables(configuration);

            Environment.SetEnvironmentVariable("chocolateyPackageName", package.Id);
            Environment.SetEnvironmentVariable("packageName", package.Id);
            Environment.SetEnvironmentVariable("chocolateyPackageTitle", package.Title);
            Environment.SetEnvironmentVariable("packageTitle", package.Title);
            Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Version.to_string());
            Environment.SetEnvironmentVariable("packageVersion", package.Version.to_string());
            Environment.SetEnvironmentVariable("chocolateyPackageVersionPrerelease", package.Version.SpecialVersion.to_string());
            Environment.SetEnvironmentVariable("chocolateyPackageVersionPackageRelease", package.Version.PackageReleaseVersion.to_string());

            Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory);
            Environment.SetEnvironmentVariable("packageFolder", packageDirectory);

            // unset variables that may not be updated so they don't get passed again
            Environment.SetEnvironmentVariable("installArguments", null);
            Environment.SetEnvironmentVariable("installerArguments", null);
            Environment.SetEnvironmentVariable("chocolateyInstallArguments", null);
            Environment.SetEnvironmentVariable("packageParameters", null);
            Environment.SetEnvironmentVariable("chocolateyPackageParameters", null);
            Environment.SetEnvironmentVariable("chocolateyInstallOverride", null);
            Environment.SetEnvironmentVariable("chocolateyChecksum32", null);
            Environment.SetEnvironmentVariable("chocolateyChecksumType32", null);
            Environment.SetEnvironmentVariable("chocolateyChecksum64", null);
            Environment.SetEnvironmentVariable("chocolateyChecksumType64", null);

            // we only want to pass the following args to packages that would apply.
            // like choco install git -params '' should pass those params to git.install,
            // but not another package unless the switch apply-install-arguments-to-dependencies is used
            if (!package_is_a_dependency_not_a_virtual(configuration, package.Id) || configuration.ApplyInstallArgumentsToDependencies)
            {
                this.Log().Debug(ChocolateyLoggers.Verbose, "Setting installer args for {0}".format_with(package.Id));
                Environment.SetEnvironmentVariable("installArguments", configuration.InstallArguments);
                Environment.SetEnvironmentVariable("installerArguments", configuration.InstallArguments);
                Environment.SetEnvironmentVariable("chocolateyInstallArguments", configuration.InstallArguments);

                if (configuration.OverrideArguments)
                {
                    Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true");
                }
            }

            // we only want to pass package parameters to packages that would apply.
            // but not another package unless the switch apply-package-parameters-to-dependencies is used
            if (!package_is_a_dependency_not_a_virtual(configuration, package.Id) || configuration.ApplyPackageParametersToDependencies)
            {
                this.Log().Debug(ChocolateyLoggers.Verbose, "Setting package parameters for {0}".format_with(package.Id));
                Environment.SetEnvironmentVariable("packageParameters", configuration.PackageParameters);
                Environment.SetEnvironmentVariable("chocolateyPackageParameters", configuration.PackageParameters);
            }

            if (!string.IsNullOrWhiteSpace(configuration.DownloadChecksum))
            {
                Environment.SetEnvironmentVariable("chocolateyChecksum32", configuration.DownloadChecksum);
                Environment.SetEnvironmentVariable("chocolateyChecksum64", configuration.DownloadChecksum);
            }

            if (!string.IsNullOrWhiteSpace(configuration.DownloadChecksumType))
            {
                Environment.SetEnvironmentVariable("chocolateyChecksumType32", configuration.DownloadChecksumType);
                Environment.SetEnvironmentVariable("chocolateyChecksumType64", configuration.DownloadChecksumType);
            }

            if (!string.IsNullOrWhiteSpace(configuration.DownloadChecksum64))
            {
                Environment.SetEnvironmentVariable("chocolateyChecksum64", configuration.DownloadChecksum64);
            }

            if (!string.IsNullOrWhiteSpace(configuration.DownloadChecksumType64))
            {
                Environment.SetEnvironmentVariable("chocolateyChecksumType64", configuration.DownloadChecksumType64);
            }

            if (configuration.ForceX86)
            {
                Environment.SetEnvironmentVariable("chocolateyForceX86", "true");
            }

            if (configuration.NotSilent)
            {
                Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true");
            }

            //todo:if (configuration.NoOutput)
            //{
            //    Environment.SetEnvironmentVariable("ChocolateyEnvironmentQuiet","true");
            //}

            if (package.IsDownloadCacheAvailable)
            {
                Environment.SetEnvironmentVariable("DownloadCacheAvailable", "true");

                foreach (var downloadCache in package.DownloadCache.or_empty_list_if_null())
                {
                    var urlKey = CryptoHashProvider.hash_value(downloadCache.OriginalUrl, CryptoHashProviderType.Sha256).Replace("=", string.Empty);
                    Environment.SetEnvironmentVariable("CacheFile_{0}".format_with(urlKey), downloadCache.FileName);
                    Environment.SetEnvironmentVariable("CacheChecksum_{0}".format_with(urlKey), downloadCache.Checksum);
                    Environment.SetEnvironmentVariable("CacheChecksumType_{0}".format_with(urlKey), "sha512");
                }
            }

            SecurityProtocol.set_protocol(configuration, provideWarning: false);
        }
Exemplo n.º 39
0
 public virtual void AuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
 {
     SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);
     _sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation);
     _sslState.ProcessAuthentication(null);
 }