Sending email with smtp authentication via telnet or openssl | windows os hub

Generic options for authenticators

When Exim is authenticating as a client, it skips any authenticator whose
client_condition expansion yields “0”, “no”, or “false”. This can be
used, for example, to skip plain text authenticators when the connection is not
encrypted by a setting such as:

client_condition = ${if !eq{$tls_out_cipher}{}}

The AUTH parameter on MAIL commands

When a client supplied an AUTH= item on a MAIL command, Exim applies
the following checks before accepting it as the authenticated sender of the
message:

  • If the connection is not using extended SMTP (that is, HELO was used rather
    than EHLO), the use of AUTH= is a syntax error.

  • If the value of the AUTH= parameter is “<>”, it is ignored.

  • If acl_smtp_mailauth is defined, the ACL it specifies is run. While it is
    running, the value of $authenticated_sender is set to the value obtained
    from the AUTH= parameter. If the ACL does not yield “accept”, the value of
    $authenticated_sender is deleted. The acl_smtp_mailauth ACL may not
    return “drop” or “discard”. If it defers, a temporary error code (451) is
    given for the MAIL command.

  • If acl_smtp_mailauth is not defined, the value of the AUTH= parameter
    is accepted and placed in $authenticated_sender only if the client has
    authenticated.

  • If the AUTH= value was accepted by either of the two previous rules, and
    the client has authenticated, and the authenticator has a setting for the
    server_mail_auth_condition, the condition is checked at this point. The
    valued that was saved from the authenticator is expanded. If the expansion
    fails, or yields an empty string, “0”, “no”, or “false”, the value of
    $authenticated_sender is deleted. If the expansion yields any other value,
    the value of $authenticated_sender is retained and passed on with the
    message.

Похожее:  Чек-лист для мобильных форм регистрации и авторизации | UX Guru

When $authenticated_sender is set for a message, it is passed on to other
hosts to which Exim authenticates as a client. Do not confuse this value with
$authenticated_id, which is a string obtained from the authentication
process, and which is not usually a complete email address.

Whenever an AUTH= value is ignored, the incident is logged. The ACL for
MAIL, if defined, is run after AUTH= is accepted or ignored. It can
therefore make use of $authenticated_sender. The converse is not true: the
value of $sender_address is not yet set up when the acl_smtp_mailauth
ACL is run.

Authentication on an Exim server

When Exim receives an EHLO command, it advertises the public names of those
authenticators that are configured as servers, subject to the following
conditions:


The order in which the authenticators are defined controls the order in which
the mechanisms are advertised.

Testing server authentication

Exim’s -bh option can be useful for testing server authentication
configurations. The data for the AUTH command has to be sent using base64
encoding. A quick way to produce such data for testing is the following Perl
script:

use MIME::Base64;
printf ("%s", encode_base64(eval ""$ARGV[0]""));

This interprets its argument as a Perl string, and then encodes it. The
interpretation as a Perl string allows binary zeros, which are required for
some kinds of authentication, to be included in the data. For example, a
command line to run this script on such data might be


Note the use of single quotes to prevent the shell interpreting the
backslashes, so that they can be interpreted by Perl to specify characters
whose code value is zero.

Authentication by an Exim client

The smtp transport has two options called hosts_require_auth and
hosts_try_auth. When the smtp transport connects to a server that
announces support for authentication, and the host matches an entry in either
of these options, Exim (as a client) tries to authenticate as follows:

  • For each authenticator that is configured as a client, in the order in which
    they are defined in the configuration, it searches the authentication
    mechanisms announced by the server for one whose name matches the public name
    of the authenticator.

  • When it finds one that matches, it runs the authenticator’s client code. The
    variables $host and $host_address are available for any string expansions
    that the client might do. They are set to the server’s name and IP address. If
    any expansion is forced to fail, the authentication attempt is abandoned, and
    Exim moves on to the next authenticator. Otherwise an expansion failure causes
    delivery to be deferred.

  • If the result of the authentication attempt is a temporary error or a timeout,
    Exim abandons trying to send the message to the host for the moment. It will
    try again later. If there are any backup hosts available, they are tried in the
    usual way.

  • If the response to authentication is a permanent error (5xx code), Exim
    carries on searching the list of authenticators and tries another one if
    possible. If all authentication attempts give permanent errors, or if there are
    no attempts because no mechanisms match (or option expansions force failure),
    what happens depends on whether the host matches hosts_require_auth or
    hosts_try_auth. In the first case, a temporary error is generated, and
    delivery is deferred. The error can be detected in the retry rules, and thereby
    turned into a permanent error if you wish. In the second case, Exim tries to
    deliver the message unauthenticated.

Note that the hostlist test for whether to do authentication can be
confused if name-IP lookups change between the time the peer is decided
upon and the time that the transport runs. For example, with a manualroute
router given a host name, and with DNS “round-robin” used by that name: if
the local resolver cache times out between the router and the transport
running, the transport may get an IP for the name for its authentication
check which does not match the connection peer IP.
No authentication will then be done, despite the names being identical.


For such cases use a separate transport which always authenticates.

When Exim has authenticated itself to a remote server, it adds the AUTH
parameter to the MAIL commands it sends, if it has an authenticated sender for
the message. If the message came from a remote host, the authenticated sender
is the one that was receiving on an incoming MAIL command, provided that the
incoming connection was authenticated and the server_mail_auth condition
allowed the authenticated sender to be retained.

If a local process calls Exim
to send a message, the sender address that is built from the login name and
qualify_domain is treated as authenticated. However, if the
authenticated_sender option is set on the smtp transport, it overrides
the authenticated sender that was received with the message.

Using authenticated smtp over tls/ssl

Most SMTP providers don’t allow plain text SMTP sessions. Only SMTP connections encrypted with TLS are allowed. You can authenticate to the SMTP server using the LOGIN and PLAIN methods only after initializing the TLS connection. Telnet doesn’t support SSL or TLS, so you need to use the OpenSSL tool to connect to the SMTP server via TLS.

Let’s look at how to use OpenSSL to connect to the SMTP server via TLS and authenticate using AUTH LOGIN.

Download and install OpenSSL:

In order to connect to the SMTP host from the command line with the SSL/TLS encryption, use the following command:

Аутентификация на smtp сервере из командной строки telnet

Для аутентификации на SMTP сервере через telnet в его настройках должна быть разрешена Basic Authentication. Basic Authentication обычно включена по-умолчанию на серверах Exchange в корпоративной сети. Такой тип аутентификации предполагает отправку имени и пароля пользователя по сети в закодированном виде по алгоритму base64.

В Exchange Server вы можете включить/отключить базовую аутентификацию в настройках принимающего коннектора.

Можно включить базовую аутентификацию из консоли PowerShell (нужно установить EMS на компьютер или подключиться к Exchange Server удаленно):

Get-ReceiveConnector “ConnectorName” | Set-ReceiveConnector -AuthMechanism Tls, Integrated, BasicAuth, ExchangeServer

Для аутентификации на SMTP сервере через AUTH LOGIN, нужно преобразовать в формат Base64 имя и пароль пользователя, из-под которого будет отправляться письмо. Для преобразования данных в Base64 можно воспользоваться функцией PowerShell:

Выполняем smtp аутентификацию через tls/ssl

Большинство SMTP провайдеров не разрешают подключение к серверу в открытом виде. Разрешаются только SMTP подключения, зашифрованные с помощью TLS. Только после этого можно выполнить аутентификацию с помощью методов LOGIN и PLAIN. Telnet не поддерживает SSL или TLS, поэтому для подключению к SMTP серверу по TLS нужно использовать утилиту OpenSSL.

Рассмотрим, как подключиться к SMTP серверу через TLS и выполнить аутентификацию с помощью OpenSSL.

Отправка по smtp с авторизацией

  1. Введение.
  2. SMTP. Теория
  3. SMTP. Практика
  4. Заключение

1. Введение.

Практически каждый, кто сталкивается с работой в инете на низком уровне при создании какой-либо почтовой программы, оповещалки, либо троя или кейлогера, напарывается на такой неприятный облом, как авторизация. Ведь многие SMTP-серверы не дают пользователю нормально отправить письмо, а требуют какие-то логин и пароль.

В этой статье я попытаюсь раскрыть эту проблему, простыми словами написать то, что написано в более “расплывчатом” виде в rfc, который почему-то всем лень читать. И, конечно, данная статья будет ориентирована на “низкоуровневых” программистов. Я буду писать под фасм, но думаю, что для Вас не составит особого труда переделать примеры под более удобный для Вас компилятор.

2. SMTP. Теория

Итак, теперь кратко, что такое SMTP – Simple Mail Transfer Protocol. Задача протокола – это удобная передача электронной почты. Но если не делать отступлений и не вдаваться в подробности, то это просто некоторое количество команд и “спецсимволов”, позволяющих отправлять письма. Для того, чтоб собственноручно пообщаться с сервером, можно взять обычный телнет (Пуск-Выполнить-telnet) и зайти на 25 порт сервера.

Делается это командой open smtp.servak.net 25. И ,если всё пройдёт удачно, Вы получите ответ от сервера.

Далее следует начать работу с сервером, а для этого его надо поприветствовать. так как сервер нормальных слов не понимает, сделать это надо командой
EHLO someword[CRLF].

[CRLF]=Enter=13,10 (каждая команда завершается этой последовательностью байт). После утвердительного ответа можно приступать непосредственно к отправке писем.

Задать отправителя письма можно командой MAIL FROM:<[email protected]>[CRLF],
а получателя RCPT TO:<[email protected]>[CRLF].

После того как эти параметры заданы, можно приступать к написанию письма. Для этого надо послать команду
DATA[CRLF].
Теперь то можно набрать тело письма. Чтоб завершить письмо, следует отправить последовательность вида
[CRLF].[CRLF]
на сервер. Если все пройдёт удачно, то письмо будет отправлено адресату.
Завершить работу с сервером следует командой QUIT[CRLF].

Так просто было общаться с сервером не слишком долгое время. Теперь, прежде чем отправить письмо, следует авторизироваться. Есть несколько способов авторизации, но я опишу самый простой, который поддерживается большинством SMTP-серверов. Чтоб начать авторизацию, следует послать на сервер команду
AUTH LOGIN[CRLF], но прежде убедитесь, что данный сервер поддерживает эту команду.

В случае принятия команды сервер запросит у Вас логин и пароль (запросы будут зашифрованы в Base64). следовательно логин и пароль надо отправлять, предварительно зашифровав их в Base64. При удачной аутентификации будет выведено соответствующее сообщение. После этого Вы можете задать адрес отправителя (должен быть привязан к логину), получателя и отправить письмо.

Но лучше раз увидеть, чем 100 раз услышать, поэтому я приведу пример диалога с сервером (s – server, u – user):

3. SMTP. Практика.

Приступим непосредственно к практике. Напишем небольшую программку, которая будет посылать небольшое сообщение на заданный почтовый ящик с авторизацией. Я предполагаю, что Вы уже знакомы с WinSocks, и не буду на этом останавливаться.
Вы можете скачать полную версию программы, а я разъясню только ключевые моменты. А именно работу процедуры Send_Mail

proc Send_Mail pszmess,pszfrom,pszto,pszlog,pszpass,pszserv,pszsubj

pszMess – само сообщение.
pszfrom – адрес отправителя
pszto – адрес получателя
pszlog, szpass – логин и пароль для авторизации
pszserv – сервер
pszsubj – тема письма

  1. stdcall Base64Encode, dword [pszlog],ebx,eax
  2. stdcall Base64Encode, dword [pszpass],ebx,eax

Тут шифруется логин и пароль в Base64, используется алгоритм by RT Fishel без использования алфавита.
Далее идёт работа с WinSocks

Создается сокет

Тут в качестве параметра gethostbyname передаётся указатель на строку с именем сервера, а потом из структуры hostent извлекается sin_addr.

Коннект на 25 порт, только нужно учитывать порядок байт.

После коннекта прочитаем ответ сервера.

Следует отметить, что все ответы сервера начинаются с определенного кода. Несложно увидеть, что в случае успеха код начинается либо с цифры 2, либо с 3. На этом основана проверка ошибок в процедуре get_data.

Теперь немного о вспомогательных процедурах:

sendNrecv – передаёт строку, указатель на которую следует поместить в еах, на сервер, получает ответ сервера.
Send_String – просто передает строку, адрес которой передан как параметр, на сервер.

Я не считаю, что следует рассматривать работу каждой из них, если Вы знакомы с WinSocks, то без проблем сделаете это сами.

Отсылка логина и пароля на сервер. szEnd 3 – указатель на [CRLF]. Получается, что мы передаем строку, а после этого [CRLF] и читаем ответ. Далее все по порядку, описанному в начале статьи.

Программа отсылает строки примерно таким образом:

s

Чтоб передать файл, нужно в теле сообщения создать заголовок вида

После чего просто передать файл, зашифрованный в Base64.

4. Заключение

Думаю, что эта статья хоть кому-нибудь пригодится. Или хотя бы облегчит жизнь, так как готовой информации для “низкоуровнего” программиста достаточно мало, а искать в интернете крохи информации и исходники, а потом в них разбираться порой нет времени, а иногда и желания.

Благодарность:

  1. Ct757 за помощь и утилиту pfcode, которая придала моему ужасному коду ровный и красивый вид.
  2. Bill Prisoner за идею написания статьи.
  3. revers я б вообще не трогал этот СМТП.

Использованная литература:

  1. Использование сокетов/взаимодействие с SMTP-сеpвеpами [Billy Belcebu/IKX, пер. Aquila]
  2. Руководство Beej по сетевому программированию, используя интернет-сокеты [Брайан “Beej” Холл, пер. varnie]
  3. INFECTED VOICE #15 – Введение … в Интернет. Диалог с SMTP сервером на Assembler
  4. Исходный код Xinch.
  5. RFC #821 #2554

Программа smtp.rar© Freeman

Тестирование отправки писем через smtp в office 365

В конце октября 2020 Microsoft запретила использовать basic authentication для подключения к почтовым ящикам. SMTP Auth к серверам в Office 365 (Microsoft 365/ Exchange Online) все еще поддерживается, но считается небезопасной. Microsoft отключила SMTP AUTH для новых тенантов. Это означает, что вы не сможете подключиться к SMTP хостам в Office 365 из командной строки telnet или openssl.

Для отправки письма через SMTP сервера в Office 365 нужно использовать PowerShell командлет Send-MailMessage.

$MailMessage = @{To = $emailtoFrom = $emailfromSubject = “Test email O365″Body = “Some text”Smtpserver = $smtpserver#ErrorAction = “SilentlyContinue”Port=”587”}Send-MailMessage @MailMessage -UseSsl -Credential $cred

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *