I just have a fresh install of Kubuntu 20.04 on an Acer Swift 3 laptop. I ran into problem with transferring files from my Android phone. Here was the steps I went through:
- Plug the phone into USB port. The device shows up on Kubuntu (Dolphin and popup notification)
- Unlock the phone and accept permission.
- Click on the device and got the following error:
No storage media found. Make sure your device is unlocked and has MTP enabled in its USB connection settings.
When I run mtp-detect, I got the following error:
$ mtp-detect
libmtp version: 1.1.17
Listing raw device(s)
Device 0 (VID=04e8 and PID=6860) is a Samsung Galaxy models (MTP).
Found 1 device(s):
Samsung: Galaxy models (MTP) (04e8:6860) @ bus 3, dev 11
Attempting to connect device(s)
error returned by libusb_claim_interface() = -6LIBMTP PANIC: Unable to initialize device
Unable to open raw device 0
OK.
dmesg:
[ 1799.438225] usb 3-1: new high-speed USB device number 16 using xhci_hcd
[ 1799.593572] usb 3-1: New USB device found, idVendor=04e8, idProduct=6860, bcdDevice= c.00
[ 1799.593575] usb 3-1: New USB device strings: Mfr=7, Product=8, SerialNumber=9
[ 1799.593576] usb 3-1: Product: SAMSUNG_Android
[ 1799.593577] usb 3-1: Manufacturer: SAMSUNG
[ 1799.593578] usb 3-1: SerialNumber: 27a0c9216c1c7ece
[ 1799.603905] cdc_acm 3-1:1.1: ttyACM0: USB ACM device
lsusb:
$ lsusb
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID 1c7a:0575 LighTuning Technology Inc. EgisTec EH575
Bus 003 Device 002: ID 0408:a094 Quanta Computer, Inc. HD User Facing
Bus 003 Device 004: ID 8087:0026 Intel Corp.
Bus 003 Device 016: ID 04e8:6860 Samsung Electronics Co., Ltd Galaxy series, misc. (MTP mode)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
But something is really strange. It works if I do the following:
- Plug the phone into laptop.
- Boot the laptop.
- Once Kubuntu loaded, run $ mtp-detect. This time mtp-detect no longer reports any error.
- Access the phone device via Dolphin works now.
Then MTP file transfer will work, until the phone is unplugged. Replugging the phone in will not work anymore.
I really have no idea what is going on. Any help is much appreciated.
The Media Transfer Protocol (MTP) can be used to transfer media files to and from many mobile phones (all Windows Phone 7/8/10 devices, most newer Android devices) and media players (e.g. Creative Zen).
Connecting
To connect your computer to a device via MTP:
- the device needs to be connected to your computer via USB
- MTP needs to be enabled on the device
- the device’s screen needs to be unlocked (for security reasons)
FUSE filesystems
The following programs let you access MTP devices via a FUSE filesystem.
Note: MTP is messy and its implementation varies between devices. Try the below clients and see which one works best with your device.
Tip: It is recommended to reboot your computer after installing MTP related packages.
For the FUSE-based file systems, you might need to create the mount-point directory first. The directory ~/mnt
is used in the examples below.
FUSE mounts can generally be unmounted using fusermount -u mountpoint
.
Android File Transfer
Android File Transfer — MTP client with CLI, Qt UI, and FUSE wrapper which uses a custom MTP implementation
- https://whoozle.github.io/android-file-transfer-linux/ || android-file-transfer
Mount your device on ~/mnt
:
$ aft-mtp-mount ~/mnt
If you want album art to be displayed, it must be named albumart.xxx
and placed first in the destination folder. Then copy other files. Also, note that fuse could be 7-8 times slower than ui/cli file transfer.
If you want to interact with it via the command line interface, run the command:
$ aft-mtp-cli
Type help in order to list all the commands available, exit to quit.
If you want to interact with it via the graphical user interface, start the android-file-transfer application, choose a destination folder and click any button on the toolbar. Available options are: Upload Album, Upload Directory and Upload Files. The latter two are self-explanatory. Upload album searches the source directory for album covers, and sets the best available cover.
MTPfs
MTPfs — based on libmtp, it is a FUSE filesystem that supports reading and writing from any MTP device
- https://www.adebenham.com/mtpfs/ || mtpfs
Note: The following is likely to not work and you might have to resort to libgphoto2 or a file manager with gvfs support like PCManFM.
First edit your /etc/fuse.conf
and uncomment the following line:
user_allow_other
Mount your device on ~/mnt
:
$ mtpfs -o allow_other ~/mnt
jmtpfs
jmtpfs — based on libmtp for accessing MTP (Media Transfer Protocol) devices
- https://github.com/JasonFerrara/jmtpfs || jmtpfsAUR
Mount device on ~/mnt
:
$ jmtpfs ~/mnt
Make this cohere to the rest of Linux (use regular mount/umount commands) by doing two steps
$# ln -s <actual mount command's path/name> <a name consistent with Linux's mount convention> $ ln -s /sbin/jmtpfs /sbin/mount.jmtpfs
add this line to /etc/fstab
;
#jmtpfs <mount path> fuse nodev,allow_other,<other options> 0 0 jmtpfs /home/sam/run/motog fuse nodev,allow_other,rw,user,noauto,noatime,uid=1000,gid=1000 0 0
Now mount the device and see if the options «took»
$ mount /home/sam/run/motog Device 0 (VID=22b8 and PID=2e82) is a Motorola Moto G (ID2). Android device detected, assigning default bug flags $ mount ... jmtpfs on /home/sam/run/motog type fuse.jmtpfs (rw,nosuid,nodev,noexec,noatime,user_id=1000,group_id=1000,allow_other,user=sam)
SIMPLE-MTPFS
SIMPLE-MTPFS — based on libmtp Simple Media Transfer Protocol FileSystem is a file system capable of operating on files on MTP devices attached via USB to local machine
- https://github.com/phatina/simple-mtpfs/ || simple-mtpfsAUR
Run simple-mtpfs -l
to list detected devices.
To mount the first device in the list to ~/mnt
, run simple-mtpfs --device 1 ~/mnt
.
go-mtpfs
go-mtpfs — FUSE filesystem with custom MTP implementation, written in Go
- https://github.com/hanwen/go-mtpfs || go-mtpfs-gitAUR
Install android-udev, which will allow you to edit /etc/udev/rules.d/51-android.rules
and apply to your idVendor
and idProduct
, which you can see after running mtp-detect. To the end of the line, add your user OWNER="<user>"
.
Mount device on ~/mnt
:
$ go-mtpfs ~/mnt
Note:
- When using multiple devices you may want to use the
-d
flag to specify a device (id can be found by runningmtp-detect
- Mounting with
go-mtpfs
might fail if an external SD Card is present. If you try to access your device while having an SD card and go-mtpfs complains, try removing the SD card and mounting again.)
libmtp
libmtp is a library MTP implementation, which also comes with some example command-line tools (which you can list using pacman -Ql libmtp
).
Install the libmtp package.
Run mtp-detect
to detect your device.
If an error is returned, make sure your user is in the adbusers
user group.
You can transfer files using the mtp-connect
command.
Frontends
gMTP — A graphical frontend for libmtp. It lets you connect to Android devices and manage files using a desktop agnostic GUI.
- https://gmtp.sourceforge.io/ || gmtp
Media players
You can also use your MTP device in music players such as Amarok. To achieve this, you might have to edit /etc/udev/rules.d/51-android.rules
(the MTP device used in the following example is a Galaxy Nexus).
Run:
$ lsusb
Search for your device. It should be something like that:
Bus 003 Device 011: ID 04e8:6860 Samsung Electronics Co., Ltd GT-I9100 Phone [Galaxy S II], GT-P7500 [Galaxy Tab 10.1]
And entry to /etc/udev/rules.d/51-android.rules
will be this:
SUBSYSTEM=="usb", ATTR{idVendor}=="04e8", ATTR{idProduct}=="6860", MODE="0666", OWNER="[username]"
Also reload udev rules:
# udevadm control --reload
File manager integration
To view the contents of your Android device’s storage via MTP in your file manager, install the corresponding plugin:
- For file managers that use GVFS (GNOME Files), install gvfs-mtp for MTP or gvfs-gphoto2 for PTP support.
- For file managers that use KIO (KDE’s Dolphin), MTP support is included in kio-extras (dependency of dolphin).
After installing the required package, the device should show up in the file manager automatically and be accessible via an URL, for example mtp://[usb:002,013]/
.
gvfs-mtp
This article or section is a candidate for merging with udev.
Notes: please use the second argument of the template to provide more detailed indications. (Discuss in Talk:Media Transfer Protocol)
The gvfs-mtp is available in the official repositories.
With lsusb
you can get information about your device where Bus and Device numbers can be used with gvfs-mtp
and device ID for creating of an udev rule.
Bus 002 Device 018: ID 04b7:88a9 Compal Electronics, Inc.
To see detected device with enabled MTP
Use gio mount:
gio mount -li | grep -e ^Volume -e activation_root
Volume(0): MT65xx Android Phone activation_root=mtp://[usb:002,018]/
Use lsusb:
lsusb -v 2> /dev/null | grep -e Bus -e iInterface -e bInterfaceProtocol
... Bus 002 Device 018: ID 04b7:88a9 Compal Electronics, Inc. bInterfaceProtocol 0 iInterface 5 MTP ...
To mount all available connected MTP devices use inline script
gio mount -li | awk -F= '{if(index($2,"mtp") == 1)system("gio mount "$2)}'
To mount or dismount from a command with gvfs-mtp use Bus and Device numbers, e.g. to mount gio mount mtp://[usb:001,007]/
and to unmount gio mount -u mtp://[usb:001,007]/
. The mounted device will be available in a directory that begins with mtp:host= and is located under /run/user/$UID/gvfs/.
Disable automount of MTP devices with gvfs you will need to change value true to false for variable AutoMount that is located in /usr/share/gvfs/mounts/mtp.mount
.
Note: The file managers can have own options for automount. On start they checking for all available mountable devices.
If your device is not showing up in the file manager then #libmtp is missing a native support and is not currently available in the list of the supported devices. If you will try to mount by using command line you may also get an error
Device 0 (VID=XXXX and PID=XXXX) is UNKNOWN. Please report this VID/PID and the device model to the libmtp development team
The workaround to make it shown in the file manager is to write an udev rule for the device but it is no guaranty that you will be able to mount it with by using MTP connection.
Use ID number that represents by pattern vendorId:productID,e.g. 04b7:88a9, and make an udev rule by creating a configuration file
/etc/udev/rules.d/51-android.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="04b7", ATTR{idProduct}=="88a9", MODE="0660", GROUP="uucp", ENV{ID_MTP_DEVICE}="1", SYMLINK+="libmtp"
Reload the udev rules.
# udevadm control --reload
The file managers with support for gvfs will be able to show MTP devices and mount them if supported by #libmtp but if has no support and cannot be opened then change settings in the phone to PTP and install gvfs-gphoto2 for having access at least to the photos, command line mounting of PTP is a little similar to mounting of the MTP devices: gio mount gphoto2://[usb:002,019]/
.
Note: If you getting limited access to the device and cannot use standard commands from command line such as e.g. cp
,ls
then look for gvfs own alternatives, ls -1 /usr/bin/gvfs-*
.
Troubleshooting
libmtp (gvfs-mtp): filemanager (nautilus, pcmanfm, vifm and etc) hangs on accessing DCIM/Camera of Android device
Symptoms: everything works fine till moment of entering DCIM/Camera directory. In this case filemanager freezes and even in command line you cannot run even ls
on that directory.
Possible and very probable reason is the bug of libmtp.
It seems that it is caused by file with name like 20180915_180351(0).jpg
. Samsung phones for example like to create files with such names.
There are several tickets (one, two and etc) and questions (one, two) about it.
So possible workaround is to use different mtp option from #FUSE filesystems like go-mtpfs for such directories or somehow change file naming policy of your phone camera (or switch to another camera app like Open Camera for example).
jmtpfs: Input/output error upon first access
Symptoms: jmtpfs successfully mounts, but as soon as one attempts to access files on the device (e.g. via ls
), an error is reported:
cannot access <mount-point>: Input/output error
This appears to be a security feature: MTP does not work when the phone is locked by the lockscreen. Unlock the phone and it should work again as long as the cord remains connected.
kio-mtp: cannot use «Open with File Manager» action
If you are not able to use the action «Open with File Manager», you may work around this problem by editing the file /usr/share/solid/actions/solid_mtp.desktop
.
Change the line Exec=kioclient exec mtp:udi=%i/
to Exec=dolphin "mtp:/"
.
kio-mtp being called simultaneously by different services
Parallel usage of mtpfs and kio-mtp, as well as conflicting services using kio-mtp -music players included- should be avoided, as mentioned in this forum.
Amarok’s plugin for MTP services, for example, might be preventing Dolphin (plasma) to access different phone model’s files. Switching it off was a solution for at least one user.
Android File Transfer: connect failed: no MTP device found
After installing android-file-transfer, while trying to mount any MTP device if you get the following error:
$ aft-mtp-mount /path/to/folder
connect failed: no MTP device found
then install the package: android-udev. This package contains per manufacturer/device udev rules for MTP devices, making it easier to use ADB or MTP.
Код | Описание |
---|---|
1XX | |
101 | The server is unable to connect |
111 | Connection refused or inability to open an SMTP stream |
2XX | |
211 | System status message or help reply |
214 | A response to the HELP command |
220 | The server is ready |
221 | The server is closing its transmission channel, It can come with side messages like «Goodbye» or «Closing connection» |
250 | Its typical side message is «Requested mail action okay completed»: meaning that the server has transmitted a message |
251 | «User not local will forward»: the recipient’s account is not on the present server, so it will be relayed to another |
252 | The server cannot verify the user, but it will try to deliver the message anyway |
3XX | |
354 | The side message can be very cryptic («Start mail input end .»), It’s the typical response to the DATA command |
4XX | |
420 | «Timeout connection problem»: there have been issues during the message transfer |
421 | The service is unavailable due to a connection problem: it may refer to an exceeded limit of simultaneous connections, or a more general temporary problem |
422 | The recipient’s mailbox has exceeded its storage limit |
431 | Not enough space on the disk, or an «out of memory» condition due to a file overload |
432 | Typical side-message: «The recipient’s Exchange Server incoming mail queue has been stopped» |
441 | The recipient’s server is not responding |
442 | The connection was dropped during the transmission |
446 | The maximum hop count was exceeded for the message: an internal loop has occurred |
447 | Your outgoing message timed out because of issues concerning the incoming server |
449 | A routing error |
450 | «Requested action not taken – The user’s mailbox is unavailable», The mailbox has been corrupted or placed on an offline server, or your email hasn’t been accepted for IP problems or blacklisting |
451 | «Requested action aborted – Local error in processing», Your ISP’s server or the server that got a first relay from yours has encountered a connection problem |
452 | Too many emails sent or too many recipients: more in general, a server storage limit exceeded |
471 | An error of your mail server, often due to an issue of the local anti-spam filter |
5XX | |
500 | A syntax error: the server couldn’t recognize the command |
501 | Another syntax error, not in the command but in its parameters or arguments |
502 | The command is not implemented |
503 | The server has encountered a bad sequence of commands, or it requires an authentication |
504 | A command parameter is not implemented, Bad email address, Bad email address, A DNS error: the host server for the recipient’s domain name cannot be found |
513 | «Address type is incorrect»: another problem concerning address misspelling, In few cases, however, it’s related to an authentication issue |
523 | The total size of your mailing exceeds the recipient server’s limits |
530 | Normally, an authentication problem, But sometimes it’s about the recipient’s server blacklisting yours, or an invalid email address |
541 | The recipient address rejected your message: normally, it’s an error caused by an anti-spam filter |
550 | It usually defines a non-existent email address on the remote side |
551 | «User not local or invalid address – Relay denied», Meaning, if both your address and the recipient’s are not locally hosted by the server, a relay can be interrupted, 552 «Requested mail actions aborted – Exceeded storage allocation»: simply put, the recipient’s mailbox has exceeded its limits |
553 | «Requested action not taken – Mailbox name invalid», That is, there’s an incorrect email address into the recipients line |
554 | This means that the transaction has failed, It’s a permanent error and the server will not try to send the message again. |
550 5.1.1 Recipient address rejected: User unknown in virtual alias table
This is the bounce back message that is received by the sender from our server if the destination email address does not exist.
The same error message is received if the recipient has a mail loop. That is, if the recipient has set a forward to another email address and that email address is forwarded back to the original one. In this case, you need to remove the loop in order to receive the emails.
If there is a forward set for an account, and an email is sent to that account, if for some reason the forwarded email is not sent, the original sender may get the above error.
For example, abc@domain.com if forwarded to abc@dom.com, if a third user xyz@dom2.com emails to abc@domain.com, he may get the above error if the forwarded email is bounced.
550 5.1.1 Protocol error
This error code ideally suggests that the sender has used SMTP protocol instead of ESMTP, thus the outbound mail of the sender was rejected. In short, the sending client doesn’t properly communicate and makes errors in the SMTP protocol.
550 5.3.2 Service currently unavailable
The error code 5.3.2 usually means that the system is not accepting network messages. We would thus need to look outside Exchange for a connectivity problem.
The error code ideally occurs ideally for two reasons which are listed below:
-
The sending IP is blacklisted at an RBL or blacklist monitoring site. (You may verify the same by inputting the IP via this link: http://mxtoolbox.com/blacklists.aspx )
-
There is a temporary block on the IP on our Inbound server due to multiple mails from this IP. Feel free to contact our support desk for more information and regarding de-listing the same.
554 5.7.1 Service unavailable; Client host X.X.X.X blocked using zen.spamhaus.org
This is the error message that is received of the IP address of the sender is listed at zen.spamhaus.org
For further details, please check http://www.spamhaus.org/zen
OR check http://www.spamhaus.org/query/bl?ip= and contact zen.spamhaus.org to get the IP De-listed.
550 5.7.1 : Helo command rejected: You aren’t localhost
550 5.7.1 : Helo command rejected: You aren’t localhost.localdomain.
550 5.7.1 : Helo command rejected: You are not me
Our servers do not accept SMTP HELO command as HELO localhost or HELO localhost.localdomain or HELO . We accept HELO from a valid Domain Name or your computer name which is other than your domain name. Please check with your ISP or Mail administrator for this issue.
554 5.7.1 : Relay access denied
There are couple of reasons for this error while sending an email
Please contact support.
551 5.7.1 The message was rejected due to classification as Virus,Spam or high bulk ratio
This is a bounce back message that you receive when an email is classified as spam while sending out. If you feel that a genuine email is rejected as spam, you need to send the same email with the full headers and the content to our support team. That email in question will be reviewed manually.
530 5.7.0 Recipient address rejected: Authentication Required
This error comes when your sending mails to remote domain without using smtp authentication.
550 5.4.5 Recipient address rejected: Hourly domain sending quota exceeded
This is the error message that you get if your domain name exceeds the hourly quota set for the domain name. Here, the term ‘hour’ refers to the last 60 minutes.
550 5.4.6 Recipient address rejected: Hourly sending quota exceeded
This is the error message that you get if the user (that particular email address) exceeds the hourly quota set. Here, the term ‘hour’ refers to the last 60 minutes.
553 5.7.1 Sender address rejected: not owned by user user@domain.com
This is the error message that is received when you are trying to send an email as a different user.
554 5.7.1 : Recipient address rejected: USER IS SUSPENDED
This error comes if user is suspended in Control Panel.
522 5.7.1 : Recipient address rejected: Requested mail action aborted: exceeded storage allocation
This error comes if the user is overquota.
554 5.7.1 : Sender address rejected: Access denied
This error comes when the sender address is blocked on our server. Generally this is done if spam has originated from this user.
450 4.1.8 : Sender address rejected: Domain not found
Our inbound servers require that the hostname for the sender server should have valid MX or A records in order to accept emails from it. You need to contact the sending server’s email admin to add valid DNS records for his server.
450 4.7.1 Client host rejected: cannot find your reverse hostname
Our inbound servers require reverse hostname for the sender server to be present in order to accept the email. You need to contact the reverse hostname’s email admin to add the rDNS to into his server.
450 4.7.1 : Recipient address rejected: Policy Rejection- Quota Exceeded
This error comes from our incoming mail server if user is receiving excessive amounts of mails.
450 4.7.1 Recipient address rejected: Access denied
This occurs when the recipient address is invalid. i.e., not in form of user@domainname OR if the Recipient address is blocked on server.
451 4.3.5 Server configuration problem — try again later
451 4.7.1 Service unavailable — try again later;
This error most likely occurs if there is a configration error with our servers. If you encounter any of the above messages, please contact our support with the details.
452 4.5.3 Error: too many recipients
The error message is encountered when the user is exceeding the limit of more than 50 recipients in an email. The list of recipients is inclusive of To,Cc and Bcc. If you encounter the above error, reduce the number of recipients in the email and try again.
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
Эта статья о методах диагностики почтовых протоколов. Она предназначена для начинающих администраторов, желающих больше узнать об инструментах для быстрого тестирования авторизации/отправки/приема почтовых сообщений как сервером, так и клиентом. Но также может служить хорошей памяткой соответствующих команд и для более опытных администраторов.
Материал разбит следующим образом:
1. Введение
2. Примеры сессий
3. Проверка авторизации на сервере (LOGIN, PLAIN, CRAM-MD5), Base64
4. Проверка шифрования SSL/TLS
5. Анализ почтового трафика при помощи tshark. Расшифровка SSL/TLS
6. Ссылки на материалы
1. Введение
В сети достаточно материалов по отдельным пунктам, но все разбросано по разным местам и, когда возникает необходимость выполнить ту или иную операцию, приходится по разным ресурсам вспоминать нюансы авторизации, способы быстрой кодировки в base64, ключи к openssl и tshark. Здесь все собрано вместе, а также добавлена информация о дешифровке SSL/TLS трафика.
Обозначения
$ — приглашение в обычном шелле, указанная после него команда выполняется от обычного пользователя
# — приглашение в рутовом шелле, указанная после него команда выполняется с правами администратора
## — строка с комментарием
Запрос клиента в почтовых сессиях выделен жирным шрифтом.
Почтовые порты
Основные порты, использующиеся в работе почтовых серверов по RFC (документы, регламентирующие работу сети интернет и ее основных компонентов):
SMTP
- 25/tcp SMTP (стандартный порт)
- 465/tcp SMTPS (устаревший)
- 587/tcp submission (порт для обслуживания клиентов)
POP3
- 110/tcp POP3 (стандартный порт)
- 995/tcp POP3S (порт с предварительной установкой SSL/TLS соединения)
IMAP
- 143/tcp IMAP (стандартный порт)
- 993/tcp IMAPS (порт с предварительной установкой SSL/TLS соединения)
Здесь перечислены только основные, помимо них разные реализации серверов могут использовать другие порты для своих служебных целей, для пользовательского и административного веб-интерфейса, общения узлов кластера и т.д.
Используемые и рекомендуемые утилиты
В статье используются telnet, openssl, tshark. Для наглядности взаимодействия сервера и клиента, использования команд протокола. На регулярной основе и для автоматизации каких-то процессов можно использовать утилиты, которые скрывают от нас все эти детали, но которые проще включаются в скрипты. Из таких утилит могу порекомендовать скрипт на perl smtp-cli (http://www.logix.cz/michal/devel/smtp-cli/), обладающий широкой функциональностью, в том числе и возможностью SMTP авторизации. Также рекомендую утилиту imtest из состава cyrus-clients, которой можно протестировать IMAP протокол. smtp-sink, утилиту из состава postfix, которая эмулирует почтовый сервер. С ее помощью можно отлаживать работу почтового клиента в том случае, если нет ни доступа к существующим почтовым серверам, ни возможности включения в настройках клиента подробного журналирования.
При помощи nmap можно быстро проверить, доступны ли порты снаружи, то есть, слушаются ли они программами и не закрыты ли при этом файерволом:
# nmap -v -p25,110,143,465,587,993,995 127.0.0.1
Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2014-10-31 15:59 MSK
Initiating SYN Stealth Scan against localhost.localdomain (127.0.0.1) [7 ports] at 15:59
Discovered open port 25/tcp on 127.0.0.1
Discovered open port 465/tcp on 127.0.0.1
Discovered open port 143/tcp on 127.0.0.1
Discovered open port 993/tcp on 127.0.0.1
The SYN Stealth Scan took 0.00s to scan 7 total ports.
Host localhost.localdomain (127.0.0.1) appears to be up ... good.
Interesting ports on localhost.localdomain (127.0.0.1):
PORT STATE SERVICE
25/tcp open smtp
110/tcp closed pop3
143/tcp open imap
465/tcp open smtps
587/tcp closed submission
993/tcp open imaps
995/tcp closed pop3s
Nmap finished: 1 IP address (1 host up) scanned in 0.004 seconds
Raw packets sent: 7 (308B) | Rcvd: 17 (724B)
По этому выводу видно, что на сервере доступны SMTP/IMAP порты, но недоступны порты для
POP3 протокола.
Через netstat можно посмотреть не только прослушиваемые и используемые порты, как часто предполагают, но и процессы, связанные с этими портами. Вот вывод netstat для этого же почтового сервера:
# netstat -lnpvut (и -anpvut, если необходимо посмотреть текущие соединения по портам)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 477/dovecot
tcp 0 0 0.0.0.0:2000 0.0.0.0:* LISTEN 477/dovecot
tcp 0 0 0.0.0.0:465 0.0.0.0:* LISTEN 603/master
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN 430/unbound
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 10042/sshd
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 603/master
tcp 0 0 0.0.0.0:1025 0.0.0.0:* LISTEN 603/master
tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 477/dovecot
tcp 0 0 127.0.0.1:1953 0.0.0.0:* LISTEN 430/unbound
tcp 0 0 127.0.0.1:1026 0.0.0.0:* LISTEN 603/master
tcp 0 0 127.0.0.1:2025 0.0.0.0:* LISTEN 603/master
tcp 0 0 :::22 :::* LISTEN 10042/sshd
udp 0 0 127.0.0.1:53 0.0.0.0:* 430/unbound
В этом примере в качестве SMTP сервера используется postfix и dovecot в качестве IMAP. POP3 в списке отсутствует, так как в настройках dovecot этот протокол отключен, как неиспользуемый.
В современных дистрибутивах пакет net-tools уже часто не ставится, считается устаревшим. В качестве замены испольуется утилита ss из состава iproute. Это более узко заточенная и в свой области, вероятно, более функциональная утилита с возможностью настройки фильтров как в tcpdump/tshark. Но мне, например, не нравится, как у нее отформатирован вывод информации. Чтобы чуть это исправить, можно использовать sed:
# ss -lntp | sed -r 's/t/ /g'
Recv-Q Send-Q Local Address:Port Peer Address:Port
0 0 *:143 *:* users:(("dovecot",477,6),("imap-login",14400,4),("imap-login",15370,4),("imap-login",15372,4))
0 0 *:2000 *:* users:(("dovecot",477,8),("managesieve-log",10229,4),("managesieve-log",10230,4),("managesieve-log",21149,4))
0 0 *:465 *:* users:(("master",603,31))
0 0 127.0.0.1:53 *:* users:(("unbound",430,4))
0 0 *:22 *:* users:(("sshd",10042,4))
0 0 *:25 *:* users:(("master",603,19))
0 0 *:1025 *:* users:(("master",603,12))
0 0 *:993 *:* users:(("dovecot",477,7),("imap-login",14400,5),("imap-login",15370,5),("imap-login",15372,5))
0 0 127.0.0.1:1953 *:* users:(("unbound",430,5))
0 0 127.0.0.1:1026 *:* users:(("master",603,16))
0 0 127.0.0.1:2025 *:* users:(("master",603,28))
0 0 :::22 :::* users:(("sshd",10042,3))
*) для удобства использования можно поместить следующую bash функцию в ~/.bashrc
ss() { /sbin/ss $@ | sed -r 's/t/ /g'; }
2. Примеры сессий
Здесь приведены примеры сессий по SMTP/IMAP/POP3 протоколам. Для соединения используется клиент телнет, который либо в системе установлен по-умолчанию, либо устанавливается из репозиториев:
Debian/Ubuntu
# apt-cache search telnet
# apt-get install telnet
RHEL/CentOS/Fedora
# yum search telnet
# yum install telnet
Вводимые команды в тексте выделены жирным шрифтом.
SMTP
$ telnet 127.0.0.1 25
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
220 mailserver at mail.server.net greets you. Make love not war!
HELO localhost.localdomain
250 mail.server.net
MAIL FROM:<>
250 2.1.0 Ok
RCPT TO:<user@mail.server.net>
250 2.1.5 Ok
DATA
354 End data with <CR><LF>.<CR><LF>
FROM: root@localhost.localdomain
TO: user@mail.server.net
SUBJECT: test mail from test subject
test body
.
250 2.0.0 Ok: queued as 1CF5FC0AAE
QUIT
221 2.0.0 Bye
Connection closed by foreign host.
IMAP
$ telnet 127.0.0.1 143
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
* OK IMAP Server at mail.server.net ready
001 LOGIN user@mail.server.net testpass
001 OK completed
002 CAPABILITY
* CAPABILITY IMAP4 IMAP4REV1 ACL NAMESPACE UIDPLUS IDLE LITERAL+ QUOTA ID MULTIAPPEND LISTEXT CHILDREN BINARY LOGIN-REFERRALS STARTTLS AUTH=LOGIN AUTH=PLAIN AUTH=CRAM-MD5 AUTH=DIGEST-MD5 AUTH=MSN
002 OK completed
003 SELECT Inbox
* FLAGS (Answered Flagged Deleted Seen Draft $MDNSent)
* OK [PERMANENTFLAGS (Answered Flagged Deleted Seen Draft $MDNSent)] limited
* 7214 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 306349424] UIDs valid
* OK [UNSEEN 1] message 1 is first unseen
003 OK [READ-WRITE] SELECT completed
004 FETCH 7214 body[header]
* 7214 FETCH (BODY[header] {639}
Return-Path: <>
X-Antispam-passed: yes
X-Antispam: yes
X-Real-To: user@mail.server.net
Received: from [127.0.0.1] (HELO mail.server.net)
by mail.server.net ( SMTP 4.1.8)
with ESMTP id 22561074 for user@mail.server.net; Sat, 01 Nov 2014 03:21:16 +0300
Received: from localhost.localdomain (localhost [127.0.0.1])
by mail.server.net (Postfix) with SMTP id 1CF5FC0AAE
for <user@mail.server.net>; Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
FROM: root@localhost.localdomain
TO: user@mail.server.net
SUBJECT: test mail from test subject
Message-Id: <20141101002009.1CF5FC0AAE@mail.server.net>
Date: Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
FLAGS (Seen))
004 OK completed
004 FETCH 7214 body
* 7214 FETCH (BODY ("text" "plain" NIL NIL NIL "8bit" 13 2))
004 OK completed
004 FETCH 7214 body[]
* 7214 FETCH (BODY[] {652}
Return-Path: <>
X-Antispam-passed: yes
X-Antispam: yes
X-Real-To: user@mail.server.net
Received: from [127.0.0.1] (HELO mail.server.net)
by mail.server.net ( SMTP 4.1.8)
with ESMTP id 22561074 for user@mail.server.net; Sat, 01 Nov 2014 03:21:16 +0300
Received: from localhost.localdomain (localhost [127.0.0.1])
by mail.server.net (Postfix) with SMTP id 1CF5FC0AAE
for <user@mail.server.net>; Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
FROM: root@localhost.localdomain
TO: user@mail.server.net
SUBJECT: test mail from test subject
Message-Id: <20141101002009.1CF5FC0AAE@mail.server.net>
Date: Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
test body
)
004 OK completed
005 LOGOUT
* BYE IMAP closing connection
005 OK completed
Connection closed by foreign host.
POP3
$ telnet 127.0.0.1 110
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
+OK POP3 Server 4.1.8 ready <137.1414802293@mail.server.net>
USER test@mail.server.net
+OK please send the PASS
PASS testpass
+OK 7214 messages (174404489 bytes)
NOOP
+OK cool
TOP 7214
+OK message follows
Return-Path: <>
X-Antispam-passed: yes
X-Antispam: yes
X-Real-To: test@mail.server.net
Received: from [127.0.0.1] (HELO mail.server.net)
by mail.server.net ( SMTP 4.1.8)
with ESMTP id 22561074 for test@mail.server.net; Sat, 01 Nov 2014 03:21:16 +0300
Received: from localhost.localdomain (localhost [127.0.0.1])
by mail.server.net (Postfix) with SMTP id 1CF5FC0AAE
for <test@mail.server.net>; Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
FROM: root@localhost.localdomain
TO: test@mail.server.net
SUBJECT: test mail from test subject
Message-Id: <20141101002009.1CF5FC0AAE@mail.server.net>
Date: Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
.
RETR 7214
+OK 652 bytes will follow
Return-Path: <>
X-Antispam-passed: yes
X-Antispam: yes
X-Real-To: test@mail.server.net
Received: from [127.0.0.1] (HELO mail.server.net)
by mail.server.net ( SMTP 4.1.8)
with ESMTP id 22561074 for test@mail.server.net; Sat, 01 Nov 2014 03:21:16 +0300
Received: from localhost.localdomain (localhost [127.0.0.1])
by mail.server.net (Postfix) with SMTP id 1CF5FC0AAE
for <test@mail.server.net>; Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
FROM: root@localhost.localdomain
TO: test@mail.server.net
SUBJECT: test mail from test subject
Message-Id: <20141101002009.1CF5FC0AAE@mail.server.net>
Date: Sat, 1 Nov 2014 03:20:09 +0300 (MSK)
test body
.
DELE 7214
+OK marked deleted
QUIT
+OK POP3 Server connection closed
Connection closed by foreign host.
3. Проверка авторизации на сервере
Существующие способы авторизации: LOGIN, PLAIN, CRAM-MD5, DIGEST-MD5, GSSAPI, NTLM/MSN, EXTERNAL. Перечень их еще шире, мы же рассмотрим только наиболее распространенные, а именно LOGIN, PLAIN и CRAM-MD5.
В первую очередь необходимо узнать список методов, поддерживаемых сервером. Для каждого из почтовых протоколов есть команды, позволяющие получить эти данные наряду с другой информацией о доступных расширениях протокола. Обратите внимание, что в зависимости от настроек почтового сервера, LOGIN и PLAIN, передающие данные в открытом виде, могут быть недоступны без предварительной инициализации шифрования через SSL/TLS
Итак, вывод доступных способов авторизации:
Протокол SMTP
Команда EHLO domainname
$ telnet 127.0.0.1 25
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
220 mailserver ESMTP ready.
EHLO localhost.localdomain
250-mal.server.net
250-PIPELINING
250-SIZE 104857600
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5
250-AUTH=PLAIN LOGIN DIGEST-MD5 CRAM-MD5
250-ENHANCEDSTATUSCODES
250 8BITMIME
^]
telnet> quit
Connection closed.
Протокол IMAP
Команда 001 CAPABILITY
Какие-то почтовые сервера могут выводить эту информацию в «приветствии сервера», например dovecot.
$ telnet 127.0.0.1 143
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE STARTTLS AUTH=PLAIN AUTH=LOGIN AUTH=DIGEST-MD5 AUTH=CRAM-MD5] Dovecot ready.
001 CAPABILITY
* CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS MULTIAPPEND UNSELECT IDLE CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS XEXEC QUOTA STARTTLS AUTH=PLAIN AUTH=LOGIN AUTH=DIGEST-MD5 AUTH=CRAM-MD5
001 OK Capability completed.
002 LOGOUT
* BYE Logging out
002 OK Logout completed.
Connection closed by foreign host.
Протокол POP3
Команды AUTH или CAPA
$ telnet pop.mail.ru 110
Trying 217.69.139.74...
Connected to pop.mail.ru.
Escape character is '^]'.
+OK
AUTH
+OK methods supported:
LOGIN
PLAIN
.
CAPA
+OK Capability list follows
TOP
USER
LOGIN-DELAY 120
EXPIRE NEVER
UIDL
IMPLEMENTATION Mail.Ru
SASL LOGIN PLAIN
STLS
.
QUIT
+OK POP3 server at signing off
Connection closed by foreign host.
Примеры авторизации и используемый формат
LOGIN
Протокол SMTP
$ telnet 127.0.0.1 25
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
220 mail.server.net ESMTP Server
EHLO client.server.net
250-mail.server.net Hello client.server.net
250-AUTH LOGIN PLAIN CRAM-MD5 DIGEST-MD5 GSSAPI
250-ENHANCEDSTATUSCODES
250 STARTTLS
AUTH LOGIN
334 VXNlcm5hbWU6
dGVzdA==
334 UGFzc3dvcmQ6
dGVzdHBhc3M=
235 2.7.0 Authentication successful
QUIT
221 2.0.0 Bye
Где ‘dGVzdA== ‘ — логин и ‘dGVzdHBhc3M=’ пароль в формате base64. О нем чуть ниже. Обратите внимание, что и логин и пароль должны кодироваться без перевода строки.
PLAIN
Протокол SMTP
$ telnet 127.0.0.1 25
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
220 mail.server.net ESMTP Server
EHLO client.server.net
250-mail.server.net Hello client.server.net
250-AUTH LOGIN PLAIN CRAM-MD5 DIGEST-MD5 GSSAPI
250-ENHANCEDSTATUSCODES
250 STARTTLS
AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz
235 2.7.0 Authentication successful
QUIT
221 2.0.0 Bye
Где ‘dGVzdAB0ZXN0AHRlc3RwYXNz’ это логинпароль в base64 формате. Чуть ниже будут рассмотрены варианты конвертации в base64 формат и обратно.
CRAM-MD5
В отличии от предыдущих способов авторизации CRAM-MD5 пароль не передается в открытом виде, вместо этого используется сравнение хэшей. Ручная проверка этого способа авторизации может быть проблемой, так как нужно будет выполнить несколько преобразований, а время на введение команд ограничено. Для упрощения процесса ниже приведен простой perl скрипт, который принимает на вход имя пользователя, пароль и «кодовое слово» (выдаваемое сервером), и конвертирует их в строку в base64 формате.
Для скрипта понадобится дополнительный модуль perl «Digest-HMAC». В Debian/Ubuntu его можно найти и установить следующим образом:
# apt-cache search perl | grep -i digest
# apt-get install libdigest-hmac-perl
Для RHEL/CentOS/Fedora:
# yum search perl | grep -i digest
# yum install perl-Digest-HMAC
В тех дистрибутивах, в чьих репозиториях нет этого пакета (что маловероятно), можно использовать установку модуля из CPAN.
Скрипт и пример сессии с его использованием:
#!/usr/bin/perl -W
use strict;
use MIME::Base64 qw(encode_base64 decode_base64);
use Digest::HMAC_MD5;
die "Usage: $0 username password ticketn" unless $#ARGV == 2;
my ($username, $password, $ticket64) = @ARGV;
my $ticket = decode_base64($ticket64) or
die ("Unable to decode Base64 encoded string '$ticket64'n");
my $password_md5 = Digest::HMAC_MD5::hmac_md5_hex($ticket, $password);
print encode_base64 ("$username $password_md5", "");
Протокол SMTP
$ telnet 127.0.0.1 25
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
220 mail.server.net ESMTP Server
EHLO client.server.net
250-mail.server.net Hello client.server.net
250-AUTH LOGIN PLAIN CRAM-MD5 DIGEST-MD5 GSSAPI
250-ENHANCEDSTATUSCODES
250 STARTTLS
AUTH CRAM-MD5
## кодовое слово, выдаваемое сервером:
PDMzMjE2NDkzMTA1OTExNDQuMTQxNDc5NTExOUBtYWlsLnNlcnZlci5uZXQ+
dGVzdCAxNTU0YTQwNzA1NTgxZjUwZmI1MmNjZDhlZDhjM2EyYg==
235 2.7.0 Authentication successful
QUIT
221 2.0.0 Bye
# ./md5cram.pl test testpass PDMzMjE2NDkzMTA1OTExNDQuMTQxNDc5NTExOUBtYWlsLnNlcnZlci5uZXQ+
dGVzdCAxNTU0YTQwNzA1NTgxZjUwZmI1MmNjZDhlZDhjM2EyYg==
Протокол IMAP
$ telnet 127.0.0.1 143
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE STARTTLS AUTH=PLAIN AUTH=LOGIN AUTH=DIGEST-MD5 AUTH=CRAM-MD5] Dovecot ready.
01 AUTHENTICATE CRAM-MD5
+ PDgxOTAyMjA2NTYwNzcyMzEuMTQxNDc5NzA3MkBtYWlsLnNlcnZlci5uZXQ+
dGVzdCA1YTZlNjYwMDlmZGJlZWNjYWRlNDY5M2FlMjU5YTA2ZQ==
01 OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS MULTIAPPEND UNSELECT IDLE CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS XEXEC QUOTA] Logged in
02 LOGOUT
* BYE Logging out
02 OK Logout completed.
Connection closed by foreign host.
# ./md5cram.pl test testpass PDgxOTAyMjA2NTYwNzcyMzEuMTQxNDc5NzA3MkBtYWlsLnNlcnZlci5uZXQ+
dGVzdCA1YTZlNjYwMDlmZGJlZWNjYWRlNDY5M2FlMjU5YTA2ZQ==
Cпособы конвертации текста в и из base64
Авторизация предполагает обмен строками, закодированными в base64. Для Linux cуществует много утилит для конвертации в base64 и обратно. Мы укажем несколько, включая способ их запуска. Для Windows можно использовать кроссплатформенные perl, python, php, по ним также будут привидены примеры.
Утилита (пакет)
base64 (coreutils)
$ printf 'testtesttestpass' | base64
dGVzdAB0ZXN0AHRlc3RwYXNz
$ echo dGVzdAB0ZXN0AHRlc3RwYXNz | base64 -d
testtesttestpass
uueencode/uudecode (sharutils)
$ printf 'testtesttestpass' | uuencode -m -
begin-base64 644 -
dGVzdAB0ZXN0AHRlc3RwYXNz
====
Чтобы раскодировать, потребуется добавить первую и последнюю строку. Это можно сделать, например, следующими способами;
printf 'begin-base64 644 -ndGVzdAB0ZXN0AHRlc3RwYXNzn====' | uudecode
или
$ uudecode<<EOF
begin-base64 644 -
dGVzdAB0ZXN0AHRlc3RwYXNz
====
EOF
mmencode (xemacs21-bin)
$ printf 'testtesttestpass' | mmencode
dGVzdAB0ZXN0AHRlc3RwYXNz
$ echo dGVzdAB0ZXN0AHRlc3RwYXNz | mmencode -u
testtesttestpass
python (python)
$ printf 'testtesttestpass' | python -m base64
dGVzdAB0ZXN0AHRlc3RwYXNz
$ echo dGVzdAB0ZXN0AHRlc3RwYXNz | python -m base64 -d
php (php-cli)
$ printf 'testtesttestpass' | php -r 'echo base64_encode(fgets(STDIN));'
dGVzdAB0ZXN0AHRlc3RwYXNz
$ php -r 'echo base64_decode($argv[1]);' dGVzdAB0ZXN0AHRlc3RwYXNz
testtesttestpass
perl (perl)
Модуль MMIME::Base64 стандартно идет в комплекте.
$ perl -MMIME::Base64 -e 'print encode_base64("testtesttestpass")'
dGVzdAB0ZXN0AHRlc3RwYXNz
$ perl -MMIME::Base64 -e 'print decode_base64("dGVzdAB0ZXN0AHRlc3RwYXNz")'
testtesttestpass
openssl (openssl)
$ printf 'testtesttestpass' | openssl base64
dGVzdAB0ZXN0AHRlc3RwYXNz
$ echo dGVzdAB0ZXN0AHRlc3RwYXNz | openssl base64 -d
testtesttestpass
4. Проверка шифрования SSL/TLS.
Для шифрования трафика в почтовых протоколах между клиентом и сервером используется SSL/TLS в двух вариантах. Использование специальных портов, при соединении с которым сначала осуществляется установка SSL/TLS, после чего уже поверх него идет обычный почтовый трафик. Этот метод, кстати, признан устаревшим (deprecated), относительно SMTP точно. Второй вариант, более предпочтительный — соединение с обычным портом для сервиса и переход сессии в зашифрованный вид с использованием расширения STARTTLS.
Для проверки работы почтового сервера поверх SSL/TLS можно использовать утилиту openssl, дальше действуя, как при обычной сессии через telnet.
SMTP
$ openssl s_client -starttls smtp -crlf -connect mail.truevds.ru:25
$ openssl s_client -starttls smtp -crlf -connect mail.truevds.ru:587
$ openssl s_client -crlf -connect mail.truevds.ru:465
POP3
$ openssl s_client -connect mail.truevds.ru:995
$ openssl s_client -starttls pop3 -crlf -connect mail.truevds.ru:110
IMAP
$ openssl s_client -crlf -connect mail.truevds.ru:993
$ openssl s_client -starttls imap -crlf -connect mail.truevds.ru:143
Можно явным образом указать, что использовать для шифрования, ssl3 или tls1, а также конкретные алгоритмы:
$ openssl s_client -ssl3 -starttls smtp -crlf -connect mail.truevds.ru:25
Посмотреть перечень поддерживаемых протоколов в вашей версии openssl:
$ openssl ciphers -ssl3
$ openssl ciphers -tls1
Ниже, в главе про tshark, эта возможность будет использована в практических целях.
5. Анализ почтового трафика при помощи tshark. Расшифровка SSL/TLS
При необходимости более сложной диагностики в том случае, когда журналы не дают достаточно информации о проблемах в работе сервера или клиента, можно использовать tcpdump/wireshark для анализа непосредственно самой сессии между клиентом и сервером. Как в реальном времени, так и сохранив дамп сессии для последующего анализа. Для быстрого анализа удобно использовать консольный вариант wireshark — tshark. Для его работы потребуются права root.
Tshark предоставляет информацию в понятном виде и в использовании довольно прост.
SMTP
# tshark -i eth0 -f "port 25" -R smtp
IMAP
# tshark -i eth0 -f "port 143" -R imap
POP3
# tshark -i eth0 -f "port 110" -R pop
Запись трафика для последующего анализа при помощи утилит tcpdump|dumpcap (из состава wireshark):
# tcpdump -s0 -nn -i eth0 -w smtps.pcap port 465 and host HOSTIP
# dumpcap -s0 -i eth0 -w smtp.pcap -f 'port 25 and host HOSTIP'
где HOSTIP является IP-адресом противоположной стороны, сервера или клиента, сессию с которым мы анализируем. И последующее чтение:
# tshark -n -r smtp.pcap -R smtp
Во многих случаях в почтовых протоколах активно используется шифрование и таким способом сессию уже не посмотреть. Тем не менее, этот вопрос в целом также решаем. tshark может дешифровать SSL/TLS трафик «со стороны сервера» при наличии доступа к приватному ключу сервера (для клиента есть вариант с использованием Master-Key, подробнее wiki.wireshark.org/SSL). К счастью или к сожалению, wireshark с приватным ключем может дешифровать не все использвуемые алгоритмы. Например DHE-* EXP-*,EDH-* не работают. Возможно, какие-то из этих алгоритмов добавлены в более поздних версиях программы.
В процессе тестирования использовалась утилита openssl с явным указанием при соединении с конкретных алгоритмов. Проверенные варианты, с которыми дешифровка трафика прошла успешно:
- ssl3: RC4-SHA, RC4-MD5, DES-CBC-SHA, AES128-SHA
- tls1: RC4-MD5, AES256-SHA, DES-CBC-SHA, DES-CBC3-SHA
Посмотреть перечень поддерживаемых протоколов в вашей версии openssl:
# openssl ciphers -ssl3
# openssl ciphers -tls1
Для анализа реальной сессии можно отключить в конфигурации почтового сервера (только на время тестирования!) всех алгоритмов, кроме заведомо рабочих.
Tshark запускается на сервере, там, где есть ключ, а клиент openssl на локальном компьютере. Но, это, конечно, необязательно, вполне можно tshark запускать на клиенте в другой консоли, просто это потребует копирования приватного ключа на локальный компьютер. А openssl можно запускать в screen в соседнем с tshark окне.
Итак запускаем:
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,25,smtp,/etc/pki/tls/private/server.key" -R smtp
$ printf "EHLO RC4-MD5nEXIT" | openssl s_client -starttls smtp -crlf -tls1 -cipher RC4-MD5 -connect mail.truevds.ru:25
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,465,smtp,/etc/pki/tls/private/server.key" -R smtp
$ printf "EHLO RC4-MD5nEXIT" | openssl s_client -ssl3 -cipher RC4-SHA -connect mail.truevds.ru:465
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,143,imap,/etc/pki/tls/private/server.key" -R imap
$ printf "* CAPABILITYnLOGOUT" | openssl s_client -starttls imap -crlf -tls1 -cipher RC4-MD5 -connect mail.truevds.ru:143
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,993,imap,/etc/pki/tls/private/server.key" -R imap
$ printf "* CAPABILITYnLOGOUT" | openssl s_client -crlf -ssl3 -cipher RC4-MD5 -connect mail.truevds.ru:993
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,110,pop,/etc/pki/tls/private/server.key" -R pop
$ printf "USER RC4-MD5nEXIT" | openssl s_client -starttls pop -crlf -tls1 -cipher RC4-MD5 -connect mail.truevds.ru:110
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,995,pop,/etc/pki/tls/private/server.key" -R pop
$ printf "USER RC4-MD5nEXIT" | openssl s_client -crlf -ssl3 -cipher RC4-MD5 -connect mail.truevds.ru:995
Здесь 94.127.66.53
— ip адрес сервера, с которым соединяется клиент, /etc/pki/tls/private/server.key
— путь до приватного ключа сервера. Приватный ключ, как правило, размещается в /etc/pki
или /etc/ssl
, в зависимости от сервера. Эту информацию можно посмотреть в настройках самого почтового сервера.
Пример для postfix:
$ grep key_file /etc/postfix/main.cf
smtpd_tls_key_file = /etc/pki/tls/private/server.key
smtp_tls_key_file = /etc/pki/tls/private/server.key
Для портов, где используется starttls вместо порта в официальной документации рекомендуется использовать start_tls. Например, ssl.keys_list:94.127.66.53,start_tls,smtp,/etc/pki/tls/private/server.key
вместо ssl.keys_list:94.127.66.53,25,smtp,/etc/pki/tls/private/server.key
. Но у меня этот вариант не сработал, показывался трафик только до инициализации шифрования.
Для отладки процесса SSL/TLS дешифровки используется опция -o "ssl.debug_file: /tmp/debug.log"
Пример вывода дешифрованного трафика:
# tshark -i eth0 -n -o "ssl.keys_list:94.127.66.53,25,smtp,/etc/pki/tls/private/server.key" -R "smtp"
Running as user "root" and group "root". This could be dangerous.
Capturing on eth0
0.178964 94.127.66.21 -> 94.127.66.53 SMTP C: EHLO RC4-MD5 | EXIT
0.179357 94.127.66.53 -> 94.127.66.21 SMTP 250-mail.truevds.ru | 250-PIPELINING | 250-SIZE 104857600 | 250-ETRN |
6. Ссылки на материалы
- Документация по сетевому анализатору wireshark: wiki.wireshark.org
- SMTP: RFC 2821
- Авторизация SMTP: RFC 4954
- POP3: RFC 3501
- IMAP: RFC 1939
- Сайт smtp-cli: www.logix.cz/michal/devel/smtp-cli
Удачи в решении почтовых проблем!
Forum rules
Before you post please read how to get help. Topics in this forum are automatically closed 6 months after creation.
-
-RYknow
Unable to open MTP device
Keep getting this error when I plug my Sony MP3 player in.
I’ve search around, and tried a bunch of different suggestions, but I’m getting no where. Can someone please point me in the right direction?
Thanks,
-RYknow
EDIT: I’m using Mint 16 Cinnamon
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
-
-RYknow
Re: Unable to open MTP device
Post
by -RYknow » Wed Jan 15, 2014 7:56 pm
Yeah I tried that. No luck. While looking around in Synaptic, I also saw mtp-tools… I tried that as well…Still no luck.
Kinda frustrating that mint doesn’t support such a basic thing out of the box? Ubuntu and Xubuntu have never given me an issue… I never thought Mint would. Apparently after googling for awhile, it would appear that I’m not the only one having these issues… although some people have been able to find fixes (mostly people trying to connect their Android to Mint). Seems like people that get this issue with a basic MP3 player however…are left in the dark.
-RYknow
-
-RYknow
Re: Unable to open MTP device
Post
by -RYknow » Fri Jan 17, 2014 9:10 pm
So I’m still fighting this issue… Someone here must be able to assist me?
I still can’t believe the most basic of features…and I’m having to jump through hoops here…
-RYknow
-
eelisajones
Re: Unable to open MTP device
Post
by eelisajones » Fri Jan 24, 2014 1:46 am
Thanks, grimalkin, for sharing your tip on switching the player to MSC. I can connect my second-hand Sansa Fuze with no problem now. I’d be interested in learning about solutions for players that do not have this option. Good luck, RYknow. I hope you find your answer.
-
carl-malone
Re: Unable to open MTP device
Post
by carl-malone » Tue May 12, 2015 8:11 am
In case it helps anyone else, after hours of pulling out my hair I went (on my Samsung Galaxy SII) to
Settings -> Wireless and Network -> USB Utilities -> Connect storage to PC
and it just opens in Caja/Nautilus. I have no idea whether installing any of the MTP or gvfs or whatever helped.
-
Laugh2
- Level 4
- Posts: 236
- Joined: Fri Aug 16, 2013 4:01 am
Re: Unable to open MTP device
Post
by Laugh2 » Mon Jun 01, 2015 6:30 pm
Most directories were immediately accessible using Mint 17.1 Rebecca’s Caja connected to a Samsung Galaxy Tab 8.9 GT-P7300 running Android 3.2 Gingerbread. Connection was via the USB/charging cable. This included access to the SDCard, although it wasn’t labelled as such.
However, the error «Unable to open MTP device ‘[usb:005,002]'» also appears, even after installing mtp-server, mtp-tools, and gigolo/gvfs. Perhaps there is further storage not yet accessible?
-
xinu
- Level 3
- Posts: 111
- Joined: Fri Apr 24, 2015 1:39 am
- Location: Belgium, Flanders, Vlaanderen
Re: Unable to open MTP device
Post
by xinu » Wed Nov 06, 2019 4:53 am
Goodday,
I think the MTP-problem is (Android-)device dependent.
Sth to do with the configuration or the security of the device.
The security paranoia of Google and drive and (un)root access trouble don’t make things easier.
E.g., every one of these devices with different Android versions shows ‘transfer via MTP’ on
the device, but in one case the MTP gives the notorious error (on Linux Mint — should check on other sys). Every device
connected with same usb cable (& rechecked with other cables).
— ZTE Blade Vec 4G, Android 4.4.2: OK.
— Doogee Valencia Y100 pro, Android 5.1: NOK.
— Xiaomi Redmi 6, Android ‘9 PPR1.180610.011etc’: OK.
This ZTE has only Internal Memory. The Doogee has Internal Memory and EXTSD possibility but after having taken the EXTSD out, the device says ‘internal storage’ twice in the settings (it considers the absent EXTSD as Internal Memory). The Xiaomi contains Internal Memory and EXTSD.
Maybe the MTP-thing has sth to do with memory allocation?…
What happened to good old ‘Mass Storage Device’?…
A guess: you are now actually using MTP for accessing your Walkman, and MTP sucks.
Details
The Operation not supported
error could indicate that your Walkman uses an MTP implementation that doesn’t support «direct» access. According to http://intr.overt.org/blog/?p=174 this kind of direct access is an Android-specific extension, so it’s probably not supported by your Walkman.
As result, you can only use a few selected ways to access files on your Walkman using MTP: I guess everything that reads or writes files in one single operation is supported, while access to selected parts of a file is not supported for these MTP implementations. And it appears that cp
and Python always use the latter access method and hence fail.
Possible Workaround
However, you might be able to just replace cp
by gvfs-copy
. In my tests with a Samsung Android phone (which has a crippled MTP implementation as well) gvfs-copy
was able to copy files to the phone where cp
failed.
Background
I couldn’t find much info about these device-dependent MTP limitations; here are some snippets where the situation is explained somewhat:
https://askubuntu.com/a/284831
https://bugs.launchpad.net/ubuntu/+source/gvfs/+bug/1389001/comments/2
https://bugs.launchpad.net/ubuntu/+source/gvfs/+bug/1157583/comments/1
Why did it work before?
As to why your Walkman was accessible with cp
in Mint 14 but not in Mint 17, this might be caused by an internal switch from PTP to MTP as access system. At least that’s what I noticed for the Samsung device when switching from Ubuntu 12.04 to 14.04. The phone supports both PTP and MTP, but Ubuntu 12.04 apparently only supports PTP; so that’s what was used. Since the new Ubuntu version has built-in support for MTP, this is now used instead.
Actually it might even be the case that your Walkman was previously accessed as USB Mass Storage Device, which is what USB hard disks and flash drives use. Maybe for some reason Linux (or your Walkman) decided that MTP was preferable over Mass Storage access.
You can see the access method used by looking at the URL for the Walkman (in Nautilus, go to the Walkman folder, press Ctrl+L and look at the address bar): for MTP the device is found under eg. mtp://[usb:001,004]/
while for PTP it’s something like gphoto2://[usb:001,004]/store_00010001
. For Mass Storage access the URL is just a normal path like /media/WALKMAN
.
I don’t know if MTP has any actual advantages over PTP or Mass Storage, or whether it’s possible to switch back to PTP or Mass Storage. Under Linux, both MTP and PTP implementations have their own set of bugs, so it might depend on your use case which one is better. AFAIK Mass Storage is the most desirable option for the user but device support in phones is waning.