コード例 #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));
            }
        }
コード例 #2
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            AuditRecord record = new UserAuditRecord(Channel.Id, identity, config.ClientIdentityNameClaimType, Channel.TypeId, $"REST-{method}", "Granted", DateTime.UtcNow);

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

            logger?.LogDebugAsync("REST adapter channel is open.").GetAwaiter();
        }
コード例 #3
0
        private void Adapter_OnObserve(object sender, ObserveMessageEventArgs e)
        {
            logger?.LogDebugAsync("REST adapter received observed message");
            OnObserve?.Invoke(this, new ChannelObserverEventArgs(channel.Id, e.Message.ResourceUri, e.Message.ContentType, e.Message.Message));
            AuditRecord record = new UserAuditRecord(channel.Id, identity, DateTime.UtcNow);

            userAuditor?.UpdateAuditRecordAsync(record).Ignore();
            AuditRecord messageRecord = new MessageAuditRecord(e.Message.MessageId, identity, channel.TypeId, protocolType.ToString(), e.Message.Message.Length, MessageDirectionType.Out, true, DateTime.UtcNow);

            messageAuditor?.WriteAuditRecordAsync(messageRecord);
        }
コード例 #4
0
        private void Channel_OnClose(object sender, ChannelCloseEventArgs e)
        {
            if (!closing)
            {
                closing = true;
                AuditRecord record = new UserAuditRecord(Channel.Id, DateTime.UtcNow);
                userAuditor?.WriteAuditRecordAsync(record).Ignore();

                OnClose?.Invoke(this, new ProtocolAdapterCloseEventArgs(Channel.Id));
            }
        }
コード例 #5
0
        private void Channel_OnClose(object sender, ChannelCloseEventArgs e)
        {
            if (!closing)
            {
                closing = true;

                Trace.TraceInformation("{0} - Channel {1} closing.", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), Channel.Id);

                UserAuditRecord record = new UserAuditRecord(Channel.Id, DateTime.UtcNow);
                userAuditor?.WriteAuditRecordAsync(record).Ignore();

                OnClose?.Invoke(this, new ProtocolAdapterCloseEventArgs(Channel.Id));
            }
        }
コード例 #6
0
        private void Channel_OnClose(object sender, ChannelCloseEventArgs e)
        {
            if (!closing)
            {
                closing = true;

                logger?.LogWarningAsync("CoAP adapter closing channel.");

                UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, DateTime.UtcNow);
                userAuditor?.UpdateAuditRecordAsync(record).Ignore();

                OnClose?.Invoke(this, new ProtocolAdapterCloseEventArgs(Channel.Id));
            }
        }
コード例 #7
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);
            }
        }
コード例 #8
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));
            }
        }
コード例 #9
0
        private void Channel_OnClose(object sender, ChannelCloseEventArgs e)
        {
            try
            {
                if (!closing)
                {
                    closing = true;
                    UserAuditRecord record = new UserAuditRecord(Channel.Id, identity, DateTime.UtcNow);
                    userAuditor?.UpdateAuditRecordAsync(record).IgnoreException();
                }

                OnClose?.Invoke(this, new ProtocolAdapterCloseEventArgs(e.ChannelId));
            }
            catch
            {
            }
        }
コード例 #10
0
        public virtual async Task <PasswordResetResultType> GeneratePasswordResetToken(User user, int expirationInMinutes)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (expirationInMinutes < 1)
            {
                throw new ArgumentException(
                          Strings.TokenExpirationShouldGiveUser1MinuteToChangePassword, nameof(expirationInMinutes));
            }

            if (!user.Confirmed)
            {
                return(PasswordResetResultType.UserNotConfirmed);
            }

            if (!string.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
            {
                return(PasswordResetResultType.Success);
            }

            user.PasswordResetToken = CryptographyService.GenerateToken();
            user.PasswordResetTokenExpirationDate = _dateTimeProvider.UtcNow.AddMinutes(expirationInMinutes);

            var passwordCredential = user.Credentials.FirstOrDefault(
                credential => credential.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase));

            UserAuditRecord auditRecord;

            if (passwordCredential == null)
            {
                auditRecord = new UserAuditRecord(user, AuditedUserAction.RequestPasswordReset);
            }
            else
            {
                auditRecord = new UserAuditRecord(user, AuditedUserAction.RequestPasswordReset, passwordCredential);
            }

            await Auditing.SaveAuditRecordAsync(auditRecord);

            await Entities.SaveChangesAsync();

            return(PasswordResetResultType.Success);
        }
コード例 #11
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);
            }
        }
コード例 #12
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs e)
        {
            try
            {
                CoapMessage message = CoapMessage.DecodeMessage(e.Message);

                if (!session.IsAuthenticated || forcePerReceiveAuthn)
                {
                    session.EnsureAuthentication(message, forcePerReceiveAuthn);

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

                OnObserve?.Invoke(this,
                                  new ChannelObserverEventArgs(Channel.Id, message.ResourceUri.ToString(),
                                                               MediaTypeConverter.ConvertFromMediaType(message.ContentType), message.Payload));

                Task task = Task.Factory.StartNew(async() =>
                {
                    CoapMessageHandler handler = CoapMessageHandler.Create(session, message, dispatcher);
                    CoapMessage msg            = await handler.ProcessAsync();

                    if (msg != null)
                    {
                        byte[] payload = msg.Encode();
                        await Channel.SendAsync(payload);
                    }
                });

                task.LogExceptions();
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"CoAP adapter receiveing on channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
                Channel.CloseAsync().Ignore();
            }
        }
コード例 #13
0
        public void FiltersOutUnsupportedCredentials()
        {
            // Arrange
            var credentialBuilder = new CredentialBuilder();
            var credentials       = new List <Credential> {
                credentialBuilder.CreatePasswordCredential("v3"),
                TestCredentialHelper.CreatePbkdf2Password("pbkdf2"),
                TestCredentialHelper.CreateSha1Password("sha1"),
                TestCredentialHelper.CreateV1ApiKey(Guid.NewGuid(), Fakes.ExpirationForApiKeyV1),
                TestCredentialHelper.CreateV2ApiKey(Guid.NewGuid(), Fakes.ExpirationForApiKeyV1),
                TestCredentialHelper.CreateV2VerificationApiKey(Guid.NewGuid()),
                credentialBuilder.CreateExternalCredential("MicrosoftAccount", "blarg", "Bloog"),
                new Credential {
                    Type = "unsupported"
                }
            };

            var user = new User
            {
                Username    = "******",
                Credentials = credentials
            };

            // Act
            var userAuditRecord = new UserAuditRecord(user, AuditedUserAction.AddCredential);

            // Assert
            var auditRecords = userAuditRecord.Credentials.ToDictionary(c => c.Type);

            Assert.Equal(7, auditRecords.Count);
            Assert.True(auditRecords.ContainsKey(credentials[0].Type));
            Assert.True(auditRecords.ContainsKey(credentials[1].Type));
            Assert.True(auditRecords.ContainsKey(credentials[2].Type));
            Assert.True(auditRecords.ContainsKey(credentials[3].Type));
            Assert.True(auditRecords.ContainsKey(credentials[4].Type));
            Assert.True(auditRecords.ContainsKey(credentials[5].Type));
            Assert.True(auditRecords.ContainsKey(credentials[6].Type));
        }
コード例 #14
0
        private async Task DeleteUser(dynamic user, SqlConnection conn)
        {
            var userRecord = await conn.QueryDatatable(
                "SELECT * FROM [Users] WHERE [Key] = @key",
                new SqlParameter("@key", user.Key));

            var auditRecord = new UserAuditRecord(
                user.Username,
                user.EmailAddress ?? user.UnconfirmedEmailAddress + " (unconfirmed)",
                userRecord,
                UserAuditAction.Deleted,
                Reason);

            await Console.WriteInfoLine(Strings.User_WritingAuditRecord, auditRecord.GetPath());

            if (!WhatIf)
            {
                await auditRecord.WriteAuditRecord("user", StorageAccount);
            }

            await DeleteUserData(user, conn);

            await Console.WriteInfoLine(Strings.User_DeleteCommand_DeletionCompleted);
        }
コード例 #15
0
        private async Task DeleteUser(dynamic user, SqlConnection conn)
        {
            var userRecord = await conn.QueryDatatable(
                "SELECT * FROM [Users] WHERE [Key] = @key",
                new SqlParameter("@key", user.Key));

            var auditRecord = new UserAuditRecord(
                user.Username,
                user.EmailAddress ?? user.UnconfirmedEmailAddress + " (unconfirmed)",
                userRecord,
                UserAuditAction.Deleted,
                Reason);

            await Console.WriteInfoLine(Strings.User_WritingAuditRecord, auditRecord.GetPath());
            if (!WhatIf)
            {
                await auditRecord.WriteAuditRecord("user", StorageAccount);
            }

            await DeleteUserData(user, conn);

            await Console.WriteInfoLine(Strings.User_DeleteCommand_DeletionCompleted);
        }
コード例 #16
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();
            }
        }