public bool IsAuthMechanismEnabled(IConnection connection, IAuthMechanism authMechanism)
        {
            if (Settings.Default.OnlyAllowClearTextAuthOverSecureConnection)
            {
                return((!authMechanism.IsPlainText) || connection.Session.SecureConnection);
            }

            return(true);
        }
示例#2
0
 public bool IsAuthMechanismEnabled(IConnection connection, IAuthMechanism authMechanism)
 {
     return(true);
 }
示例#3
0
 public virtual bool IsAuthMechanismEnabled(IConnection connection, IAuthMechanism authMechanism)
 {
     return(false);
 }
示例#4
0
        public void Process(IConnection connection, SmtpCommand command)
        {
            if (command.Arguments.Length > 0)
            {
                if (connection.Session.Authenticated)
                {
                    throw new SmtpServerException(new SmtpResponse(StandardSmtpResponseCode.BadSequenceOfCommands,
                                                                   "Already authenticated"));
                }

                string         mechanismId = command.Arguments[0];
                IAuthMechanism mechanism   = AuthExtensionProcessor.MechanismMap.Get(mechanismId);

                if (mechanism == null)
                {
                    throw new SmtpServerException(
                              new SmtpResponse(StandardSmtpResponseCode.CommandParameterNotImplemented,
                                               "Specified AUTH mechanism not supported"));
                }

                if (!AuthExtensionProcessor.IsMechanismEnabled(mechanism))
                {
                    throw new SmtpServerException(
                              new SmtpResponse(StandardSmtpResponseCode.AuthenticationFailure,
                                               "Specified AUTH mechanism not allowed right now (might require secure connection etc)"));
                }

                IAuthMechanismProcessor authMechanismProcessor =
                    mechanism.CreateAuthMechanismProcessor(connection);

                AuthMechanismProcessorStatus status =
                    authMechanismProcessor.ProcessResponse(string.Join(" ", command.Arguments.Skip(1).ToArray()));
                while (status == AuthMechanismProcessorStatus.Continue)
                {
                    string response = connection.ReadLine();

                    if (response == "*")
                    {
                        connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.SyntaxErrorInCommandArguments, "Authentication aborted"));
                        return;
                    }

                    status = authMechanismProcessor.ProcessResponse(response);
                }

                if (status == AuthMechanismProcessorStatus.Success)
                {
                    connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.AuthenitcationOK,
                                                              "Authenticated OK"));
                    connection.Session.Authenticated             = true;
                    connection.Session.AuthenticationCredentials = authMechanismProcessor.Credentials;
                }
                else
                {
                    connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.AuthenticationFailure,
                                                              "Authentication failure"));
                }
            }
            else
            {
                throw new SmtpServerException(new SmtpResponse(StandardSmtpResponseCode.SyntaxErrorInCommandArguments,
                                                               "Must specify AUTH mechanism as a parameter"));
            }
        }
 /// <inheritdoc/>
 public virtual Task <bool> IsAuthMechanismEnabled(IConnection connection, IAuthMechanism authMechanism)
 {
     return(Task.FromResult(true));
 }
示例#6
0
        public bool IsAuthMechanismEnabled(IConnection connection, IAuthMechanism authMechanism)
        {
            if (Settings.Default.OnlyAllowClearTextAuthOverSecureConnection)
            {
                return (!authMechanism.IsPlainText) || connection.Session.SecureConnection;
            }

            return true;
        }
示例#7
0
        /// <inheritdoc/>
        public async Task Process(IConnection connection, SmtpCommand command)
        {
            ArgumentsParser argumentsParser = new ArgumentsParser(command.ArgumentsText);

            if (argumentsParser.Arguments.Count > 0)
            {
                if (connection.Session.Authenticated)
                {
                    throw new SmtpServerException(new SmtpResponse(
                                                      StandardSmtpResponseCode.BadSequenceOfCommands,
                                                      "Already authenticated"));
                }

                string         mechanismId = argumentsParser.Arguments.First();
                IAuthMechanism mechanism   = this.AuthExtensionProcessor.MechanismMap.Get(mechanismId);

                if (mechanism == null)
                {
                    throw new SmtpServerException(
                              new SmtpResponse(
                                  StandardSmtpResponseCode.CommandParameterNotImplemented,
                                  "Specified AUTH mechanism not supported"));
                }

                if (!await this.AuthExtensionProcessor.IsMechanismEnabled(mechanism).ConfigureAwait(false))
                {
                    throw new SmtpServerException(
                              new SmtpResponse(
                                  StandardSmtpResponseCode.AuthenticationFailure,
                                  "Specified AUTH mechanism not allowed right now (might require secure connection etc)"));
                }

                IAuthMechanismProcessor authMechanismProcessor =
                    mechanism.CreateAuthMechanismProcessor(connection);

                string initialData = null;
                if (argumentsParser.Arguments.Count > 1)
                {
                    initialData = string.Join(" ", argumentsParser.Arguments.Skip(1).ToArray());
                }

                AuthMechanismProcessorStatus status =
                    await authMechanismProcessor.ProcessResponse(initialData).ConfigureAwait(false);

                while (status == AuthMechanismProcessorStatus.Continue)
                {
                    string response = await connection.ReadLine().ConfigureAwait(false);

                    if (response == "*")
                    {
                        await connection.WriteResponse(new SmtpResponse(StandardSmtpResponseCode.SyntaxErrorInCommandArguments, "Authentication aborted")).ConfigureAwait(false);

                        return;
                    }

                    status = await authMechanismProcessor.ProcessResponse(response).ConfigureAwait(false);
                }

                if (status == AuthMechanismProcessorStatus.Success)
                {
                    await connection.WriteResponse(new SmtpResponse(
                                                       StandardSmtpResponseCode.AuthenticationOK,
                                                       "Authenticated OK")).ConfigureAwait(false);

                    connection.Session.Authenticated             = true;
                    connection.Session.AuthenticationCredentials = authMechanismProcessor.Credentials;
                }
                else
                {
                    await connection.WriteResponse(new SmtpResponse(
                                                       StandardSmtpResponseCode.AuthenticationFailure,
                                                       "Authentication failure")).ConfigureAwait(false);
                }
            }
            else
            {
                throw new SmtpServerException(new SmtpResponse(
                                                  StandardSmtpResponseCode.SyntaxErrorInCommandArguments,
                                                  "Must specify AUTH mechanism as a parameter"));
            }
        }
示例#8
0
 public bool IsMechanismEnabled(IAuthMechanism mechanism)
 {
     return(_processor.Server.Behaviour.IsAuthMechanismEnabled(_processor, mechanism));
 }
示例#9
0
        private void StartAndTune()
        {
            var connectionStartCell = new BlockingCell <ConnectionStartDetails>();

            _model0.m_connectionStartCell        = connectionStartCell;
            _model0.HandshakeContinuationTimeout = _config.HandshakeContinuationTimeout;
            _frameHandler.ReadTimeout            = _config.HandshakeContinuationTimeout;
            _frameHandler.SendHeader();

            ConnectionStartDetails connectionStart = connectionStartCell.WaitForValue();

            if (connectionStart is null)
            {
                throw new IOException("connection.start was never received, likely due to a network timeout");
            }

            ServerProperties = connectionStart.m_serverProperties;

            var serverVersion = new AmqpVersion(connectionStart.m_versionMajor, connectionStart.m_versionMinor);

            if (!serverVersion.Equals(Protocol.Version))
            {
                TerminateMainloop();
                FinishClose();
                throw new ProtocolVersionMismatchException(Protocol.MajorVersion, Protocol.MinorVersion, serverVersion.Major, serverVersion.Minor);
            }

            // FIXME: parse out locales properly!
            ConnectionTuneDetails connectionTune = default;
            bool tuned = false;

            try
            {
                string mechanismsString = Encoding.UTF8.GetString(connectionStart.m_mechanisms);
                IAuthMechanismFactory mechanismFactory = GetAuthMechanismFactory(mechanismsString);
                IAuthMechanism        mechanism        = mechanismFactory.GetInstance();
                byte[]? challenge = null;
                do
                {
                    byte[] response = mechanism.handleChallenge(challenge, _config);
                    ConnectionSecureOrTune res;
                    if (challenge is null)
                    {
                        res = _model0.ConnectionStartOk(ClientProperties,
                                                        mechanismFactory.Name,
                                                        response,
                                                        "en_US");
                    }
                    else
                    {
                        res = _model0.ConnectionSecureOk(response);
                    }

                    if (res.m_challenge is null)
                    {
                        connectionTune = res.m_tuneDetails;
                        tuned          = true;
                    }
                    else
                    {
                        challenge = res.m_challenge;
                    }
                }while (!tuned);
            }
            catch (OperationInterruptedException e)
            {
                if (e.ShutdownReason != null && e.ShutdownReason.ReplyCode == Constants.AccessRefused)
                {
                    throw new AuthenticationFailureException(e.ShutdownReason.ReplyText);
                }
                throw new PossibleAuthenticationFailureException(
                          "Possibly caused by authentication failure", e);
            }

            ushort channelMax = (ushort)NegotiatedMaxValue(_config.MaxChannelCount, connectionTune.m_channelMax);

            _sessionManager = new SessionManager(this, channelMax);

            uint frameMax = NegotiatedMaxValue(_config.MaxFrameSize, connectionTune.m_frameMax);

            FrameMax       = frameMax;
            MaxPayloadSize = frameMax == 0 ? int.MaxValue : (int)frameMax - Client.Impl.Framing.BaseFrameSize;

            uint heartbeatInSeconds = NegotiatedMaxValue((uint)_config.HeartbeatInterval.TotalSeconds, (uint)connectionTune.m_heartbeatInSeconds);

            Heartbeat = TimeSpan.FromSeconds(heartbeatInSeconds);

            _model0.ConnectionTuneOk(channelMax, frameMax, (ushort)Heartbeat.TotalSeconds);

            // now we can start heartbeat timers
            MaybeStartHeartbeatTimers();
        }
示例#10
0
 /// <summary>
 /// Updates the UserStore with this UserData. Basically a shortcut for Authentication.UserStore.UpdateByID
 /// </summary>
 /// <returns>
 /// true if user updated successfully
 /// </returns>
 public bool Update(IAuthMechanism auth)
 {
     if(string.IsNullOrEmpty(UniqueID)){
         return false;
     }
     return auth.UserStore.UpdateUserByID(this);
 }
示例#11
0
 /// <summary>
 /// Inserts this UserData into the UserStore, generating the password in the process. Basically a shortcut for Authentication.AddUser
 /// </summary>
 /// <param name="password">
 /// The password to use for this user
 /// </param>
 /// <returns>
 /// true if successfully inserted
 /// </returns>
 public bool SaveNew(IAuthMechanism auth, string password)
 {
     if(!string.IsNullOrEmpty(UniqueID)){ //UniqueID can't already be set
         return false;
     }
     if(!auth.UserStore.AddUser(this))
     {
         return false;
     }
     auth.ComputePasswordHash(this, password);
     return auth.UserStore.UpdateUserByID(this);
 }
示例#12
0
 /// <summary>
 /// Resets the password for this UserData, as well as updating the password for it in the UserStore. 
 /// </summary>
 /// <returns>
 /// The generated password. Returns null on error.
 /// </returns>
 public string ResetPassword(IAuthMechanism auth)
 {
     if(string.IsNullOrEmpty(UniqueID)){
         return null;
     }
     return auth.ResetPassword(this);
 }
示例#13
0
 /// <summary>
 /// Deletes this UserData from the UserStore. Note, if successful, UniqueID will be set to null as well.
 /// </summary>
 /// <returns>
 /// true if successfully deleted
 /// </returns>
 public bool Delete(IAuthMechanism auth)
 {
     bool res=auth.UserStore.DeleteUserByID(this);
     if(res){
         UniqueID=null;
     }
     return res;
 }
示例#14
0
 public TestController(RequestContext c, IAuthMechanism auth=null)
     : base(c)
 {
     Authentication=auth;
 }
示例#15
0
 public void Add(IAuthMechanism mechanism)
 {
     _map[mechanism.Identifier] = mechanism;
 }
示例#16
0
 public virtual bool IsAuthMechanismEnabled(IConnection connection, IAuthMechanism authMechanism)
 {
     return false;
 }
示例#17
0
 /// <summary>
 /// Adds an auth mechanism to the map.
 /// </summary>
 /// <param name="mechanism">The mechanism<see cref="IAuthMechanism"/>.</param>
 public void Add(IAuthMechanism mechanism)
 {
     this.map[mechanism.Identifier] = mechanism;
 }
 public bool IsMechanismEnabled(IAuthMechanism mechanism)
 {
     return _processor.Server.Behaviour.IsAuthMechanismEnabled(_processor, mechanism);
 }
示例#19
0
 /// <summary>
 /// Determines whether the specified auth mechanism is enabled for the current connection.
 /// </summary>
 /// <param name="mechanism">The mechanism.</param>
 /// <returns>A <see cref="Task{T}"/> representing the async operation which yields true if enabled.</returns>
 public async Task <bool> IsMechanismEnabled(IAuthMechanism mechanism)
 {
     return(await this.connection.Server.Behaviour.IsAuthMechanismEnabled(this.connection, mechanism).ConfigureAwait(false));
 }
示例#20
0
        protected void StartAndTune()
        {
            var connectionStartCell = new BlockingCell();

            m_model0.m_connectionStartCell        = connectionStartCell;
            m_model0.HandshakeContinuationTimeout = m_factory.HandshakeContinuationTimeout;
            m_frameHandler.ReadTimeout            = (int)m_factory.HandshakeContinuationTimeout.TotalMilliseconds;
            m_frameHandler.SendHeader();

            var connectionStart = (ConnectionStartDetails)
                                  connectionStartCell.Value;

            if (connectionStart == null)
            {
                throw new IOException("connection.start was never received, likely due to a network timeout");
            }

            ServerProperties = connectionStart.m_serverProperties;

            var serverVersion = new AmqpVersion(connectionStart.m_versionMajor,
                                                connectionStart.m_versionMinor);

            if (!serverVersion.Equals(Protocol.Version))
            {
                TerminateMainloop();
                FinishClose();
                throw new ProtocolVersionMismatchException(Protocol.MajorVersion,
                                                           Protocol.MinorVersion,
                                                           serverVersion.Major,
                                                           serverVersion.Minor);
            }

            ClientProperties = new Dictionary <string, object>(m_factory.ClientProperties)
            {
                ["capabilities"]    = Protocol.Capabilities,
                ["connection_name"] = ClientProvidedName
            };

            // FIXME: parse out locales properly!
            ConnectionTuneDetails connectionTune = default;
            bool tuned = false;

            try
            {
                string   mechanismsString = Encoding.UTF8.GetString(connectionStart.m_mechanisms, 0, connectionStart.m_mechanisms.Length);
                string[] mechanisms       = mechanismsString.Split(' ');
                IAuthMechanismFactory mechanismFactory = m_factory.AuthMechanismFactory(mechanisms);
                if (mechanismFactory == null)
                {
                    throw new IOException("No compatible authentication mechanism found - " +
                                          "server offered [" + mechanismsString + "]");
                }
                IAuthMechanism mechanism = mechanismFactory.GetInstance();
                byte[]         challenge = null;
                do
                {
                    byte[] response = mechanism.HandleChallenge(challenge, m_factory);
                    ConnectionSecureOrTune res;
                    if (challenge == null)
                    {
                        res = m_model0.ConnectionStartOk(ClientProperties,
                                                         mechanismFactory.Name,
                                                         response,
                                                         "en_US");
                    }
                    else
                    {
                        res = m_model0.ConnectionSecureOk(response);
                    }

                    if (res.m_challenge == null)
                    {
                        connectionTune = res.m_tuneDetails;
                        tuned          = true;
                    }
                    else
                    {
                        challenge = res.m_challenge;
                    }
                }while (!tuned);
            }
            catch (OperationInterruptedException e)
            {
                if (e.ShutdownReason?.ReplyCode == Constants.AccessRefused)
                {
                    throw new AuthenticationFailureException(e.ShutdownReason.ReplyText);
                }
                throw new PossibleAuthenticationFailureException(
                          "Possibly caused by authentication failure", e);
            }

            var channelMax = (ushort)NegotiatedMaxValue(m_factory.RequestedChannelMax,
                                                        connectionTune.m_channelMax);

            m_sessionManager = new SessionManager(this, channelMax);

            uint frameMax = NegotiatedMaxValue(m_factory.RequestedFrameMax,
                                               connectionTune.m_frameMax);

            FrameMax = frameMax;

            var heartbeat = (ushort)NegotiatedMaxValue(m_factory.RequestedHeartbeat,
                                                       connectionTune.m_heartbeat);

            Heartbeat = heartbeat;

            m_model0.ConnectionTuneOk(channelMax,
                                      frameMax,
                                      heartbeat);

            // now we can start heartbeat timers
            MaybeStartHeartbeatTimers();
        }