Esempio n. 1
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            try
            {
                session.IsAuthenticated = Channel.IsAuthenticated;
                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context,
                                                                  session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity,
                                                                 session.Config.IdentityClaimType, Channel.TypeId, "MQTT", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }

                adapter            = new OrleansAdapter(session.Identity, Channel.TypeId, "MQTT", graphManager, logger);
                adapter.OnObserve += Adapter_OnObserve;
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Channel_OnOpen error on channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
        }
        public WsnProtocolAdapter(PiraeusConfig config, GraphManager graphManager, IChannel channel, HttpContext context, ILog logger = null)
        {
            this.config       = config;
            this.graphManager = graphManager;
            this.Channel      = channel;
            this.logger       = logger;

            IdentityDecoder decoder = new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity     = decoder.Id;
            localIndexes = decoder.Indexes;

            MessageUri messageUri = new MessageUri(context.Request);

            this.contentType   = messageUri.ContentType;
            this.cacheKey      = messageUri.CacheKey;
            this.resource      = messageUri.Resource;
            this.subscriptions = messageUri.Subscriptions != null ? new List <string>(messageUri.Subscriptions) : null;
            this.indexes       = messageUri.Indexes != null ? new List <KeyValuePair <string, string> >(messageUri.Indexes) : null;

            auditFactory = AuditFactory.CreateSingleton();
            if (config.AuditConnectionString != null && config.AuditConnectionString.Contains("DefaultEndpointsProtocol"))
            {
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "messageaudit"), AuditType.Message);
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "useraudit"), AuditType.User);
            }
            else if (config.AuditConnectionString != null)
            {
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.Message);
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.User);
            }

            messageAuditor = auditFactory.GetAuditor(AuditType.Message);
            userAuditor    = auditFactory.GetAuditor(AuditType.User);
        }
Esempio n. 3
0
        public void EnsureAuthentication(CoapMessage message, bool force = false)
        {
            if (!IsAuthenticated || force)
            {
                CoapUri coapUri = new CoapUri(message.ResourceUri.ToString());
                if (!Authenticate(coapUri.TokenType, coapUri.SecurityToken))
                {
                    throw new SecurityException("CoAP session not authenticated.");
                }

                IdentityDecoder decoder = new IdentityDecoder(Config.IdentityClaimType, context, Config.Indexes);
                Identity = decoder.Id;
                Indexes  = decoder.Indexes;
            }
        }
Esempio n. 4
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            session.IsAuthenticated = Channel.IsAuthenticated;
            logger?.LogDebugAsync(
                $"CoAP protocol channel opening with session authenticated '{session.IsAuthenticated}'.").GetAwaiter();

            try
            {
                if (!Channel.IsAuthenticated && e.Message != null)
                {
                    CoapMessage msg     = CoapMessage.DecodeMessage(e.Message);
                    CoapUri     coapUri = new CoapUri(msg.ResourceUri.ToString());
                    session.IsAuthenticated = session.Authenticate(coapUri.TokenType, coapUri.SecurityToken);
                    logger?.LogDebugAsync(
                        $"CoAP protocol channel opening session authenticated '{session.IsAuthenticated}' by authenticator.")
                    .GetAwaiter();
                }

                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context,
                                                                  session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;
                    logger?.LogDebugAsync($"CoAP protocol channel opening with session identity '{session.Identity}'.")
                    .GetAwaiter();

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity,
                                                                 session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"CoAP adapter opening channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            if (!session.IsAuthenticated && e.Message != null)
            {
                logger?.LogWarningAsync("CoAP adpater closing due to unauthenticated user.");
                Channel.CloseAsync().Ignore();
            }
            else
            {
                dispatcher = new CoapRequestDispatcher(session, Channel, config, graphManager, logger);
            }
        }
Esempio n. 5
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs e)
        {
            try
            {
                MqttMessage msg = MqttMessage.DecodeMessage(e.Message);
                OnObserve?.Invoke(this, new ChannelObserverEventArgs(Channel.Id, null, null, e.Message));

                if (!session.IsAuthenticated)
                {
                    if (!(msg is ConnectMessage message))
                    {
                        throw new SecurityException("Connect message not first message");
                    }

                    if (session.Authenticate(message.Username, message.Password))
                    {
                        IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context,
                                                                      session.Config.Indexes);
                        session.Identity = decoder.Id;
                        session.Indexes  = decoder.Indexes;
                        adapter.Identity = decoder.Id;

                        UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity,
                                                                     session.Config.IdentityClaimType, Channel.TypeId, "MQTT", "Granted", DateTime.UtcNow);
                        userAuditor?.WriteAuditRecordAsync(record).Ignore();
                    }
                    else
                    {
                        throw new SecurityException("Session could not be authenticated.");
                    }
                }
                else if (forcePerReceiveAuthn)
                {
                    if (!session.Authenticate())
                    {
                        throw new SecurityException("Per receive authentication failed.");
                    }
                }

                ProcessMessageAsync(msg).GetAwaiter();
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"MQTT adapter Channel_OnReceive error on channel '{Channel.Id}'.")
                .GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }
        }
Esempio n. 6
0
        public RestProtocolAdapter(PiraeusConfig config, GraphManager graphManager, IChannel channel,
                                   HttpContext context, ILog logger = null)
        {
            this.config  = config;
            this.channel = channel;
            this.logger  = logger;
            method       = context.Request.Method.ToUpperInvariant();
            messageUri   = new MessageUri(context.Request);

            IdentityDecoder decoder =
                new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity = decoder.Id;
            indexes  = decoder.Indexes;
            adapter  = new OrleansAdapter(identity, channel.TypeId, "REST", graphManager, logger);
            if (method == "GET")
            {
                adapter.OnObserve += Adapter_OnObserve;
            }

            protocolType  = ProtocolType.REST;
            contentType   = messageUri.ContentType;
            resource      = messageUri.Resource;
            subscriptions = messageUri.Subscriptions;

            auditFactory = AuditFactory.CreateSingleton();
            if (config.AuditConnectionString != null &&
                config.AuditConnectionString.Contains("DefaultEndpointsProtocol"))
            {
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "messageaudit"),
                                 AuditType.Message);
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "useraudit"), AuditType.User);
            }
            else if (config.AuditConnectionString != null)
            {
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.Message);
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.User);
            }

            messageAuditor = auditFactory.GetAuditor(AuditType.Message);
            userAuditor    = auditFactory.GetAuditor(AuditType.User);
        }
Esempio n. 7
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            session.IsAuthenticated = Channel.IsAuthenticated;

            try
            {
                if (!Channel.IsAuthenticated && e.Message != null)
                {
                    CoapMessage msg     = CoapMessage.DecodeMessage(e.Message);
                    CoapUri     coapUri = new CoapUri(msg.ResourceUri.ToString());
                    session.IsAuthenticated = session.Authenticate(coapUri.TokenType, coapUri.SecurityToken);
                }

                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context, session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, $"CoAP adapter opening channel '{Channel.Id}'.");
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            if (!session.IsAuthenticated && e.Message != null)
            {
                //close the channel
                logger?.LogInformation($"CoAP adapter user not authenticated; must close channel '{Channel.Id}'.");
                Channel.CloseAsync().Ignore();
            }
            else
            {
                dispatcher = new CoapRequestDispatcher(session, Channel);
            }
        }
Esempio n. 8
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            if (!Channel.IsAuthenticated)  //requires channel authentication
            {
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, new SecurityException("Not authenticated.")));
                Channel.CloseAsync().Ignore();
                return;
            }

            if (e.Message.Method != HttpMethod.Post && e.Message.Method != HttpMethod.Get)
            {
                Channel.CloseAsync().Ignore();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, new SecurityException("Rest protocol adapter requires GET or POST only.")));
            }

            MessageUri      uri     = new MessageUri(e.Message);
            IdentityDecoder decoder = new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity = decoder.Id;

            adapter            = new OrleansAdapter(decoder.Id, "HTTP", "REST");
            adapter.OnObserve += Adapter_OnObserve;
            HttpRequestMessage request = (HttpRequestMessage)e.Message;

            AuditRecord record = new UserAuditRecord(Channel.Id, identity, config.ClientIdentityNameClaimType, Channel.TypeId, String.Format("REST-{0}", request.Method.ToString()), "Granted", DateTime.UtcNow);

            userAuditor?.WriteAuditRecordAsync(record).Ignore();

            if (request.Method == HttpMethod.Get)
            {
                foreach (var item in uri.Subscriptions)
                {
                    Task t = Task.Factory.StartNew(async() =>
                    {
                        await SubscribeAsync(item, decoder.Id, decoder.Indexes);
                    });

                    t.LogExceptions();
                }
            }

            if (request.Method == HttpMethod.Post)
            {
                byte[] buffer = request.Content.ReadAsByteArrayAsync().Result;
                Task   t      = Task.Factory.StartNew(async() =>
                {
                    EventMetadata metadata = await GraphManager.GetPiSystemMetadataAsync(uri.Resource);
                    EventMessage message   = new EventMessage(uri.ContentType, uri.Resource, ProtocolType.REST, buffer, DateTime.UtcNow, metadata.Audit);

                    if (!string.IsNullOrEmpty(uri.CacheKey))
                    {
                        message.CacheKey = uri.CacheKey;
                    }

                    List <KeyValuePair <string, string> > indexList = uri.Indexes == null ? null : new List <KeyValuePair <string, string> >(uri.Indexes);

                    await PublishAsync(decoder.Id, message, indexList);
                    await Channel.CloseAsync();
                });

                t.LogExceptions();
            }
        }