Contact us in messengers or by phone.

whatsapp telegram viber phone email
+79214188555

Understanding how credit card security systems work.

root

СисАдмин Форума
Staff member
Full members of NP "MOD"
Joined
Feb 17, 2007
Messages
673
Reaction score
1,013
Points
93
Age
57
Close contacts

Your wallet probably contains several cards of international payment systems, such as Visa or MasterCard. Have you ever wondered what algorithms are used in these cards? How secure are payments? We pay with cards every day, but we know very little about them for certain. There are even more myths accompanying card payments. To understand what are the ways to steal money from the card, you must first understand how the payment is made. Let's sort it out together.

Card number​


Historically, payment by card number is the oldest. Previously, there was nothing on the cards except this number. The number was "embossed" - stamped on the map. When paying, the card was "rolled" on a special device, which allowed the seller to quickly enter the number into the ancient replacement of the database, that is, to print it on a sheet of paper.

At the end of the working day or week, this data was collected and transmitted to the acquiring bank. Then the bank sent requests to write off this money from cardholders through issuing banks. It was so long ago that few people know where the three-digit payment verification code written on the back of the card, the so-called CVV2 / CVC2, came from. Information has reached us that this code was used rather as a checksum, necessary so that the cardholder did not make a mistake and correctly entered all the information when paying. Sounds like the truth when you consider how short this code is.

Now the physical card may not participate at all in the payment. This is called a card not present and is most often used when paying online. If the card number is entered when paying in a payment terminal, and this is typical for hotels, businesses doing business by phone, as well as for most terminals in the United States, this subtype of payments is called PAN Key Entry.

Many people still believe that the Cardholder name field on the front of the card must be entered correctly and that it is checked. This is not the case - no bank checks this field.

Magnetic stripe​


Magnetic stripe operations are one of the simplest methods. People associate it with certain types of fraud. Skimming at ATMs, double withdrawals at restaurants - all this is possible due to the disadvantages of the magnetic stripe. The magnetic stripe is easy to copy - all you need is a dedicated magnetic stripe reader / encoder. Further, the cloned magnetic stripe is enough to pay in most supermarkets in the world. To verify the cardholder, it was supposed to use the signature on the check, which the cashier must verify with the signature on the back of the card.

image1.jpg


In the picture above, you can see an example of the information recorded on the card. Black bars are ones, white bars are zeros. There are open source solutions for decoding this data - for example, magstripe ...


In fact, you can see from the image that the card has not one, but two magnetic stripes of different densities (Track1 and Track2). What data does the magnetic stripe contain?
  • Card number, expiration date, cardholder's name - whatever is physically printed on the face of the card.
  • Service code - three digits that help the device interacting with the card (terminal or ATM) to understand what functions the card has and what does not. Can this card be used at an ATM, is the card equipped with a chip.
  • Verification code (CVV, CVC, CID - terminology depends on the payment system) - a code similar to the one written on the back of the card. It is calculated using the cryptographic check-sum algorithm (MDK MAC) using a 128-bit key from the information recorded on the magnetic stripe. Using a calculated CVV instead of a random one helps against attacks, when, for example, an attacker replaces the service code and tries to convince the payment terminal that the card is not equipped with a chip. The issuing bank will receive the magnetic stripe data, verify it, and the checksum will not converge with the transmitted value in the CVV field. Verifications take place in a secure key store - the so-called HSM (hardware secure module).

Chip / EMV​


The magnetic stripe was replaced in the nineties by smart cards, which were popularized by the EMV consortium (Europay, MasterCard, Visa). The consortium's idea was simple: using smart card features, symmetric cryptography and public key cryptography, solve all the problems associated with magnetic stripe. Smart card transactions provide three levels of protection:
  1. Card authentication. Verification by the payment terminal that the card is genuine and was indeed issued by bank N, and was not created by hackers at home.
  2. Payer verification. Verification that this card belongs to the customer standing in front of the payment terminal.
  3. Transaction authorization. There is a long way from the card to the issuing bank. The bank must make sure that these transactions have not been tampered with anywhere by cybercriminals. That the amount has remained unchanged, that the date of the transaction is correct, that this transaction is unique, and was not already posted in the last month.
Let's go over the methods used.

Card authentication​


The card is authenticated using RSA public key cryptography. The current minimum key length requirement is 1024 bits. A limited number of certification authorities issue keys for banks, and banks are already linking them to the cards themselves. The private key is stored on the smart card itself in a non-readable area. Root certificates are installed on the terminal when it is configured. During the transaction, the card provides the public keys to the payment terminal along with information encrypted with the private key in digital signature mode. If the public key is trusted and the information transmitted by the card is successfully decrypted with this key, then the terminal considers the card to be authentic, issued by the bank that signed the private key issued by the certification center.

There are three modes of card authentication in total:
  • SDA - static data authentication;
  • DDA - dynamic data authentication;
  • CDA - combined dynamic data authentication.

The first method used only one static field stored in the map. It was signed with a private key and verified by the terminal. It was an AIP (application interchange profile) EMV field. But the EMV consortium quickly realized that for the then popular offline terminals (they did not go online to verify the cryptogram), this was clearly not enough - anyone could clone the public key and the signed static string to create a fake.

The next method relied on dynamic data coming from the terminal. The terminal generates a field UN - Unique Number, which is signed with the private key of the card. The entropy of this field is 232, which is enough to defend against the first attack.

However, in 2009, researchers at the University of Cambridge presented a paper describing the so-called PIN OK ( PDF ). A special device located between the card and the terminal made a man-in-the-middle attack and changed one of the fields that the card was sending. This substitution could not be detected on the terminal using the methods described above. To protect against such attacks, the EMV consortium provided a new defense mechanism, the CDA scheme, even before the discovery of the researchers. During it, the terminal can check the integrity of most of the fields that the card transmits and that participate in a phase called "risk management".

Offline authentication was created primarily to protect offline payments when the terminal is not constantly connected to the Internet. That is why, if the result of the operation of the DDA or CDA modes does not end with success, in modern terminals connected to the Internet, this will not lead to a failure of the transaction in 99% of cases, since the issuing bank authorizes it using a cryptogram, as described below. However, some payment systems recommend paying attention to persistent unsuccessful authentications, especially if they occur in different terminals.

Payer verification​


There are two main ways to verify the payer: PIN-code and signature. In fact, there are a little more of them - the PIN-code can be checked offline (on the card itself) and online. It can be encrypted (using a 3DES symmetric key) or transmitted in cleartext.

Another possible way to verify NoCVM - that is, no verification. A good example of such operations is those that do not exceed the limits of 3000 rubles and do not require a PIN-code. They are sometimes called Tap & Go.

Another method, which depending on the payment system is called CDCVM or On-Device CVM, makes it possible to verify the cardholder on the mobile phone. As you might have guessed, it is used by Google Pay and Apple Pay.

Transaction authorization​


To authorize a transaction, smart cards create a payment cryptogram. The card sends a list of fields to the terminal - their set depends on the cryptogram version and card settings. As a rule, these are the transaction amount, currency, date and other terminal settings important for the stage of risk management. Further, the card supplements these fields with its own internal fields: the counter of operations, the version of the cryptogram.


The received string is encrypted using the 3DES secret key recorded on the card in the digital signature mode and transmitted to the bank along with all the signed information. The issuing bank uses a hardware security module (HSM) that contains a copy of the card's symmetric key in a read-protected memory area.


HSM also digitally signs data from the payment terminal. If he receives the same cryptogram, then the transaction will be considered authorized. This means that no one changed these operations during their transfer from the card to the issuing bank. At the same stage, the PIN-code of the card is deciphered and verified, if the online PIN-verification is used.


Note that all three of these functions only work well together. For verification to work correctly, it must be controlled using authentication. If there is no authorization, the whole transaction becomes high-risk, and so on.

Contactless payments​


Contactless payments have been gaining popularity since the mid-2010s. Banks and payment systems are promoting them as a fast and convenient way to pay. This is understandable - the more people pay with cards, the more you can earn on commissions! With the development of technology, security must also be developed, but this is far from always the case. And contactless payments are just an example of unsuccessful ones.

When contactless payments were created, chip cards were not yet particularly widespread in the United States, so Visa and MasterCard envisioned an intermediate step when new contactless cards could be used to pay with old, outdated payment terminals that do not support modern cryptography. This step is called Legacy modes, which are much less secure than EMV payments and modern forms of contactless payments.

Legacy modes are more like operations with a magnetic stripe in terms of the degree of protection, only they are carried out via NFC. Despite the fact that these regimes were supposed to be used only in a few countries, and after a while they would be canceled altogether, in 2020 we meet them everywhere - including in Russia, where even the magnetic stripe is prohibited.

A separate problem is how payment systems approached the implementation of contactless payments. Instead of coming up with something new, Visa and MasterCard decided to use EMV here as well, but each did it differently, so de jure they ceased to be part of the EMV standard.

INFO​

What follows from this:
  • First, the protection mechanisms and their problems described in the early 2000s have survived. In most cards, even the cryptographic keys used for EMV and NFC cryptograms are the same.
  • Secondly, the EMV association could no longer influence how the payment process would be structured.

Visa was unhappy with the too long payment processing time. When a chip was used for this, there were no problems - the card was inserted into the terminal. However, Visa considered that keeping the card at the terminal while waiting for all the EMV steps to be completed was not very convenient. The phase that caused the major delay was offline card authentication.

At the same time, MasterCard made a diametrically opposite decision - they recognized that offline authentication is also important for those cards that support the most secure CDA authentication scheme, and made it mandatory. In the EMV specification, if the CDA communication does not succeed, the terminal can still send a cryptogram for online authorization. Whereas for contactless MasterCard payments, a failed CDA authentication always leads to a canceled payment. The difference in transaction times is not significant, but this remains a decisive factor for Visa.

conclusions​


Now that you know how electronic and contactless payments work, you are ready to talk about the vulnerabilities in these schemes. We will discuss this in the following articles, and at the same time we will analyze the most high-profile cases of fraud.

Timur Yunusov

A source
cc-h.jpg
 
Original message
Близкие контакты

В твоем кошельке наверняка есть несколько карт международных платежных систем, таких как Visa или MasterCard. Задумывался ли ты, какие алгоритмы используются в этих картах? Насколько платежи безопасны? Мы расплачиваемся картами каждый день, но достоверно знаем о них крайне мало. Еще больше мифов сопровождает карточные платежи. Чтобы понять, какие есть способы похитить деньги с карты, нужно сначала уяснить, как происходит оплата. Давай разбираться вместе.

Номер карты​


Оплата по номеру карты исторически — самая старшая. Раньше на картах не было ничего, кроме этого номера. Номер был «эмбоссирован» — выдавлен на карте. При оплате карта «прокатывалась» на специальном устройстве, что позволяло продавцу быстро внести номер в древнюю замену базы данных, то есть отпечатать на листе бумаги.

В конце рабочего дня или недели эти данные собирались и передавались в банк‑эквайер. Далее банк отправлял запросы на списание этих денег у владельцев карт через банки‑эмитенты. Это было так давно, что немного людей знают, откуда появился трехзначный код верификации платежей, записанный на обратной стороне карты, так называемый CVV2/CVC2. До нас дошла информация, что этот код использовался скорее как контрольная сумма, нужная, чтобы владелец карты не ошибся и корректно ввел всю информацию при оплате. Похоже на правду, если учесть, насколько короткий этот код.

Сейчас физическая карта может и вовсе не участвовать в оплате. Это называется card not present и чаще всего используется при оплате в интернете. Если номер карты вводится при оплате в платежном терминале, а это характерно для отелей, бизнесов, ведущих дела по телефону, а также для большинства терминалов в США, такой подтип платежей называется PAN Key Entry.

Многие до сих пор считают, что поле Cardholder name с лицевой стороны карты нужно вводить корректно и что оно проверяется. Это не так — ни один банк не проверяет это поле.

Магнитная полоса​


Операции с магнитной полосой — один из самых простых методов. Он ассоциируется у людей с определенными типами мошенничества. Скимминг в банкоматах, двойные снятия в ресторанах — все это возможно благодаря недостаткам магнитной полосы. Магнитную полосу легко скопировать — для этого необходим только специальный ридер/энкодер магнитной полосы. Дальше клонированной магнитной полосы достаточно для того, чтобы расплачиваться в большинстве супермаркетов мира. Для верификации владельца карты предполагалось использовать подпись на чеке, которую кассир должен сверить с подписью на обратной стороне карты.

image1.jpg


На картинке выше ты видишь пример записанной на карту информации. Черные полоски — это единицы, белые — нули. Существуют open source решения для декодирования этих данных — к примеру, magstripe.


На самом деле по изображению видно, что на карте не одна, а целых две магнитные полосы разной плотности (Track1 и Track2). Какие данные содержатся на магнитной полосе?
  • Номер карты, дата окончания действия, имя владельца карты — все, что физически отпечатано на лицевой стороне карты.
  • Сервисный код — три цифры, которые помогают взаимодействующему с картой устройству (терминал или банкомат) понять, какие функции есть у карты, а каких нет. Можно ли использовать эту карту в банкомате, оснащена ли карта чипом.
  • Код верификации (CVV, CVC, CID — терминология зависит от платежной системы) — код, аналогичный тому, что написан на обратной стороне карты. Он рассчитывается по алгоритму криптографической чек‑суммы (MDK MAC) с помощью 128-битного ключа от информации, записанной на магнитной полосе. Использование вычисляемого CVV вместо случайного помогает от атак, когда, например, злоумышленник подменяет сервисный код и пытается убедить платежный терминал, что карта не оснащена чипом. Банк‑эмитент получит данные магнитной полосы, сверит их, и контрольная сумма не сойдется с переданным значением в поле CVV. Сверки проходят в защищенном хранилище ключей — так называемом HSM (hardware secure module).

Чип/EMV​


На смену магнитной полосе в девяностых пришли смарт‑карты, для популяризации которых создали консорциум EMV (Europay, MasterCard, Visa). Продвигаемая консорциумом идея была проста: используя особенности смарт‑карт, симметричную криптографию и криптографию с открытым ключом, решить все проблемы, связанные с магнитной полосой. Операции со смарт‑картой обеспечивают три степени защиты:
  1. Аутентификация карты. Проверка платежным терминалом того, что карта подлинная и действительно была выпущена банком N, а не была создана злоумышленниками в домашних условиях.
  2. Верификация плательщика. Проверка того, что эта карта принадлежит покупателю, стоящему перед платежным терминалом.
  3. Авторизация транзакции. От карты до банка‑эмитента путь долгий. Банк должен убедиться, что данные операции нигде не были искажены злоумышленниками. Что сумма осталась неизменной, что дата операции корректная, что эта операция уникальна, а не была уже проведена в прошлом месяце.
Давай пройдемся по используемым методам.

Аутентификация карты​


Для аутентификации карты используется криптография с открытым ключом по протоколу RSA. Текущие минимальные требования по длине ключа — 1024 бита. Ограниченное число центров сертификации выпускают ключи для банков, а банки их уже привязывают к самим картам. Приватный ключ хранится на самой смарт‑карте в области, недоступной для чтения. Корневые сертификаты устанавливаются на терминал при его настройке. Во время транзакции карта предоставляет публичные ключи платежному терминалу вместе с информацией, зашифрованной приватным ключом в режиме цифровой подписи. Если публичный ключ доверенный и информация, переданная картой, успешно расшифровывается этим ключом, то терминал считает карту аутентичной, выпущенной именно тем банком, который подписал приватный ключ, выданный центром сертификации.

Всего существует три режима аутентификации карты:
  • SDA — static data authentication;
  • DDA — dynamic data authentication;
  • CDA — combined dynamic data authentication.

В первом методе использовалось только одно статическое поле, хранящееся на карте. Оно подписывалось приватным ключом и проверялось терминалом. Это было EMV-поле AIP (application interchange profile). Но консорциум EMV быстро понял, что для популярных в то время офлайновых терминалов (они не выходили в онлайн для сверки криптограммы) этого было явно недостаточно — любой мог клонировать публичный ключ и подписанную статическую строку, чтобы создать подделку.

Следующий метод полагался на динамические данные, приходящие от терминала. Терминал генерирует поле UN — Unique Number, которое подписывается приватным ключом карты. Энтропия этого поля — 232, чего достаточно для защиты от первой атаки.

Однако в 2009 году исследователи из Кембриджского университета представили работу, описывающую так называемую атаку PIN OK (PDF). Специальное устройство, располагающееся между картой и терминалом, совершало атаку «человек посередине» и подменяло одно из полей, которые отправляла карта. Эту подмену нельзя было обнаружить на терминале с помощью описанных выше методов. Для защиты от таких атак консорциум EMV еще до находки исследователей предусмотрел новый механизм защиты — схему CDA. Во время нее терминал может проверить целостность большинства полей, которые передает карта и которые участвуют в фазе под названием «риск‑менеджмент».

Офлайновая аутентификация создавалась в первую очередь для защиты офлайновых платежей, когда терминал не подключен к интернету постоянно. Именно поэтому, если результат работы режимов DDA или CDA не заканчивается успехом, в современных терминалах, подключенных к интернету, это не приведет к отказу транзакции в 99% случаев, так как банк‑эмитент авторизует ее с помощью криптограммы, как описано ниже. Однако некоторые платежные системы рекомендуют обращать внимание на постоянные неуспешные аутентификации, особенно если они происходят в разных терминалах.

Верификация плательщика​


Есть два основных способа верификация плательщика: ПИН‑код и подпись. На самом деле их немного больше — ПИН‑код может проверяться в офлайне (на самой карте) и онлайн. Он может быть зашифрован (с помощью симметричного ключа 3DES) или передаваться в открытом виде.

Еще возможен способ верификации NoCVM — то есть отсутствие верификации. Хороший пример таких операций — те, которые не превышают лимиты 3000 рублей и не требуют ввода ПИН‑кода. Их иногда называют Tap & Go.

Другой способ, который в зависимости от платежной системы называется CDCVM или On-Device CVM, делает возможной верификацию на мобильном телефоне владельца карты. Как ты уже догадался, он используется в Google Pay и Apple Pay.

Авторизация транзакции​


Для авторизации транзакции смарт‑карты создают платежную криптограмму. Карта отправляет терминалу список полей — их набор зависит от версии криптограммы и настроек карты. Как правило, это сумма операции, валюта, дата и другие важные для этапа риск‑менеджмента настройки терминала. Далее карта дополняет эти поля своими внутренними полями: счетчик операций, версия криптограммы.


Полученная строка шифруется с помощью записанного на карте секретного ключа 3DES в режиме цифровой подписи и передается банку вместе со всей подписанной информацией. Банк‑эмитент использует аппаратный модуль безопасности (hardware security module, HSM), на котором в защищенной от чтения области памяти содержится копия симметричного ключа карты.


HSM также создает цифровую подпись по данным от платежного терминала. Если он получит такую же криптограмму, то транзакция будет считаться авторизованной. Это значит, что никто не подменил данные операции во время их передачи от карты до банка эмитента. На этом же этапе расшифровывается и сверяется ПИН‑код карты, в случае если используется онлайн‑сверка ПИН.


Обрати внимание, что все эти три функции работают хорошо только вместе. Чтобы корректно работала верификация, она должна контролироваться с помощью аутентификации. Если нет авторизации — вся транзакция становится высокорисковой, и так далее.

Бесконтактные платежи​


Бесконтактные платежи стали набирать популярность с середины 2010-х годов. Банки и платежные системы продвигают их как быстрый и удобный способ оплаты. Оно и понятно — чем больше народ платит картами, тем больше можно заработать на комиссиях! С развитием технологий нужно развивать и безопасность, но это далеко не всегда так. И бесконтактные платежи как раз пример из неудачных.

Когда создавались бесконтактные платежи, карты с чипом в США еще не были особенно распространены, поэтому Visa и MasterCard предусмотрели промежуточный шаг, когда новыми бесконтактными картами можно платить на старых несовременных платежных терминалах, которые не поддерживают современную криптографию. Этот шаг называется Legacy modes — режимы, степень безопасности которых значительно ниже, чем у платежей EMV и современных форм бесконтактных платежей.

Legacy modes по степени защиты больше напоминают операции с магнитной полосой, только проводятся через NFC. Несмотря на то что эти режимы предполагалось использовать лишь в нескольких странах, а через какое‑то время и вовсе отменить, мы в 2020 году встречаем их повсеместно — в том числе в России, где даже магнитная полоса запрещена.

Отдельная проблема — это то, как платежные системы подошли к реализации бесконтактных платежей. Вместо того чтобы придумать что‑то новое, в компаниях Visa и MasterCard решили и здесь использовать EMV, но каждая сделала это по‑своему, так что де‑юре они перестали быть частью стандарта EMV.

INFO​

Что из этого следует:
  • Во‑первых, механизмы защиты и их проблемы, описанные в начале 2000-х годов, сохранились. В большинстве карт даже криптографические ключи, используемые для криптограмм EMV и NFC, одни и те же.
  • Во‑вторых, ассоциация EMV не могла больше влиять на то, как будет построен платежный процесс.

В компании Visa были недовольны слишком долгим временем проведения платежа. Когда для этого использовался чип, проблем не было — карта вставлялась в терминал. Однако в Visa посчитали, что держать карту у терминала, ожидая, пока пройдут все шаги EMV, — это не очень‑то удобно. Этап, который вызывал основную задержку, — это офлайновая аутентификация карты.

Одновременно с этим в MasterCard приняли диаметрально противоположное решение — признали, что офлайновая аутентификация важна и для тех карт, которые поддерживают наиболее безопасную схему аутентификации CDA, и сделали ее обязательной. В спецификации EMV, если взаимодействие по схеме CDA не заканчивается успешно, терминал все еще может отправить криптограмму для онлайновой авторизации. Тогда как для бесконтактных платежей MasterCard неудачная аутентификация CDA всегда ведет к отмене платежа. Разница во времени операций незначительная, однако это остается решающим фактором для Visa.

Выводы​


Теперь, когда ты знаешь, как работают электронные и в том числе бесконтактные платежи, ты готов к разговору об уязвимостях в этих схемах. Это мы обсудим в следующих статьях, а заодно разберем самые громкие кейсы мошенничества.

Тимур Юнусов

Источник
cc-h.jpg
Last edited by a moderator: