Security

Security

Topics relating to application security and attacks against software.
Daisy pearl

Daisy pearl

1680242473

Crypto Wallets : Your Key to Navigating UPI Tax on Digital Payments

Understanding Crypto Wallets

In the world of digital currencies, crypto wallets play a crucial role. A #cryptowallet is a digital wallet that allows users to securely store, send, and receive digital currencies like Bitcoin, Ethereum, and more. Unlike traditional wallets, crypto wallets do not store physical currency or assets. Instead, they store the user’s private and public keys, which are used to manage their digital assets on the blockchain.

Benefits of Crypto Wallets

One of the primary benefits of using a crypto wallet is the high level of privacy and security they offer. Users can keep their #cryptocurrency holdings separate from their personal identifying information, making it much more difficult for hackers and other malicious actors to access their funds.

Crypto wallets also provide a convenient way for users to manage their #digitalassets and keep track of their transactions. With a growing number of merchants accepting cryptocurrencies as #payments, having a crypto wallet is becoming more important than ever.

Crypto Wallets in India

In India, the popularity of cryptocurrencies is on the rise. As more and more people turn to digital currencies as an alternative to traditional financial systems, having a cryptocurrency wallet is becoming increasingly important. With a crypto wallet, users in India can securely store and manage their digital assets, even if they are subject to transaction fees on traditional payment platforms like #upi. Additionally, with the ability to buy, sell, and trade digital currencies through crypto wallets, users in India have more options than ever before.

In conclusion, crypto wallets are essential in the world of digital currencies. They offer a high level of #privacy and #security, as well as a convenient way for users to manage their digital assets. As cryptocurrencies continue to gain popularity in India and around the world, having a crypto wallet is becoming more important than ever.

Connect with the leading Blockchain wallet development company to seamlessly manage your daily crypto transactions and ensure the security and privacy of your digital assets.

Ref : Account-to-account transfers free on UPI: NPCI

#blockchainfirm #cryptopayments #upipayment #digitalassets #digitalindia #merchantservices #upitaxes #taxation #ppi #npci #gasfee #etherum #paymentsolutions #paymentgatewayintegration #transactionbanking

 

Crypto Wallets : Your Key to Navigating UPI Tax on Digital Payments

Shynet: Modern, Privacy-friendly, and Cookie-free Web Analytics

Shynet 

Modern, privacy-friendly, and cookie-free web analytics. 

Motivation

There are a lot of web analytics tools. Unfortunately, most of them come with the following caveats:

  • They require handing all of your visitors' info to a third-party company
  • They use cookies to track visitors across sessions, so you need to have those annoying cookie notices
  • They collect so much personal data that even the NSA is jealous
  • They are closed source and/or expensive, often with limited data portability
  • They are hard to use

Shynet has none of these caveats. You host it yourself, so the data is yours. It works without cookies, so you don't need any intrusive cookie notices. It collects just enough data to be useful, but not enough to be creepy. It's open source and intended to be self-hosted. And you may even find the interface easy to use.

Shynet is a portmanteau of "Skynet" and "shy." The idea is that it gives you loads of useful information (Skynet) while also respecting your visitors' privacy (shy).

Screenshots

Note: These screenshots have been edited to hide sensitive data. The "real" Shynet has a lot more pages and information available, but hopefully this gives you an idea of the general look and feel of the tool.

Shynet's homepage Shynet's homepage, where you can see all of your services at a glance.

A service page A real service page, where you can see higher-level details about a site.

Not shown: management view, session view, full service view. (You'll need to install Shynet for yourself to see those!)

Shynet is built using a17t, an atomic design library. Customization and extension is simple; learn more about a17t.

Features

Architecture

  • Runs on a single machine — Because it's so small, Shynet can easily run as a single docker container on a single small VPS
  • ...or across a giant Kubernetes cluster — For higher traffic installations, Shynet can be deployed with as many parallelized ingress nodes as needed, with Redis caching and separate backend workers for database IO
  • Built using Django — Shynet is built using Django, so deploying, updating, and migrating can be done without headaches
  • Multiple users and sites — A single Shynet instance can support multiple users, each tracking multiple different sites

Tracking

  • JavaScript not required — It will fallback to using a 1x1 transparent tracking pixel if JavaScript isn't available
  • Lightweight — The tracking script weighs less than a kilobyte (and doesn't look like your typical tracking script)
  • Generally not blocked — Because you host Shynet yourself, it tends not to be on ad block lists
  • Primary-key integration — You can easily associate visitors in Shynet with their user accounts on your site (if that's something you want)

Metrics

Here's the information Shynet can give you about your visitors:

  • Hits — how many pages on your site were opened/viewed
  • Sessions — how many times your site was visited (essentially a collection of hits)
  • Page load time — how long the pages on your site look to load
  • Bounce rate — the percentage of visitors who left after just one page
  • Duration — how long visitors stayed on the site
  • Referrers — the links visitors followed to get to your site
  • Locations — the relative popularity of all the pages on your site
  • Operating system — your visitors' OS (from user agent)
  • Browser — your visitors' browser (from user agent)
  • Geographic location & network — general location of your visitors (from IP)
  • Device type — whether your visitors are using a desktop, tablet, or phone (from user agent)

Workflow

  • Collaboration built-in — Administrators can easily share services with other users, as well
  • Accounts (or not) — Shynet has a fully featured account management workflow (powered by Django Allauth)

Recommendations

Shynet isn't for everyone. It's great for personal projects and small to medium size websites, but hasn't been tested with ultra-high traffic sites. It also requires a fair amount of technical know-how to deploy and maintain, so if you need a one-click solution, you're best served with other tools.

Concepts

Shynet is pretty simple, but there are a few key terms you need to know in order to use it effectively:

Services are the properties on the web you'd like to track. These generally correspond to websites or single top-level domains. Shynet generates one tracking embed per service.

Hits are a single page-load on one of your services.

Sessions are a collection of hits (or just one) that are made by the same browser in a short period of time.

Installation

You can find instructions on getting started and usage in the Usage Guide. Out of the box, we support deploying via a simple Docker container, docker-compose, Heroku, or Kubernetes (see kubernetes).

FAQ

Does Shynet respond to Do Not Track (DNT) signals? Yes. While there isn't any standardized way to handle DNT requests, Shynet allows you to specify whether you want to collect any data from users with DNT enabled on a per-service basis. (By default, Shynet will not collect any data from users who specify DNT.)

Is this GDPR compliant? It depends on how you use it. If you're worried about GDPR, you should talk to a lawyer about your particular data collection practices. I'm not a lawyer. (And this isn't legal advice.)

Troubleshooting

Having trouble with Shynet? Check out the troubleshooting guide, or create an issue if you think you found a bug in Shynet itself (or have a feature suggestion).

Roadmap

To see the upcoming planned features, check out the repository's roadmap project. Upcoming features include data aggregation through rollups, anomaly detection, detailed data exports, two-factor authentication, and a data deletion tool.

In the Wild

These sites use Shynet to monitor usage without violating visitors' privacy: PolitiTweet, Miles' personal site, a17t, Lensant, WhoAreMyRepresentatives.org, and more. (Want to add your site to this list? Send a PR.)

Contributing

Are you interested in contributing to Shynet? Just send a pull request! Maybe once the project matures there will be more detailed contribution guidelines, but for now just send the code this way and we'll make sure it meets our standards together. Just know that by contributing, you agree to share all of your contributions under the same license as the project (see LICENSE). And always be sure to follow the Code of Conduct.


Shynet was created by Miles McCain (@MilesMcCain) at the Recurse Center using a17t.


Download Details:

Author: Milesmcc
Source Code: https://github.com/milesmcc/shynet 
License: Apache-2.0 license

#python #docker #kubernetes #security #django 

Shynet: Modern, Privacy-friendly, and Cookie-free Web Analytics

Rudder-server: Privacy & Security Focused Segment-alternative

The Customer Data Platform for Developers


As the leading open source Customer Data Platform (CDP), RudderStack provides data pipelines that make it easy to collect data from every application, website and SaaS platform, then activate it in your warehouse and business tools.

With RudderStack, you can build customer data pipelines that connect your whole customer data stack and then make them smarter by triggering enrichment and activation in customer tools based on analysis in your data warehouse. It's easy-to-use SDKs and event source integrations, Cloud Extract integrations, transformations, and expansive library of destination and warehouse integrations makes building customer data pipelines for both event streaming and cloud-to-warehouse ELT simple.

RudderStack 

Try RudderStack Cloud Free - a free tier of RudderStack Cloud. Click here to start building a smarter customer data pipeline today, with RudderStack Cloud.

Key features

Warehouse-first: RudderStack treats your data warehouse as a first class citizen among destinations, with advanced features and configurable, near real-time sync.

Developer-focused: RudderStack is built API-first. It integrates seamlessly with the tools that the developers already use and love.

High Availability: RudderStack comes with at least 99.99% uptime. We have built a sophisticated error handling and retry system that ensures that your data will be delivered even in the event of network partitions or destinations downtime.

Privacy and Security: You can collect and store your customer data without sending everything to a third-party vendor. With RudderStack, you get fine-grained control over what data to forward to which analytical tool.

Unlimited Events: Event volume-based pricing of most of the commercial systems is broken. With RudderStack Open Source, you can collect as much data as possible without worrying about overrunning your event budgets.

Segment API-compatible: RudderStack is fully compatible with the Segment API. So you don't need to change your app if you are using Segment; just integrate the RudderStack SDKs into your app and your events will keep flowing to the destinations (including data warehouses) as before.

Production-ready: Companies like Mattermost, IFTTT, Torpedo, Grofers, 1mg, Nana, OnceHub, and dozens of large companies use RudderStack for collecting their events.

Seamless Integration: RudderStack currently supports integration with over 90 popular tool and warehouse destinations.

User-specified Transformation: RudderStack offers a powerful JavaScript-based event transformation framework which lets you enhance or transform your event data by combining it with your other internal data. Furthermore, as RudderStack runs inside your cloud or on-premise environment, you can easily access your production data to join with the event data.

Get started

The easiest way to experience RudderStack is to sign up for RudderStack Cloud Free - a completely free tier of RudderStack Cloud.

You can also set up RudderStack on your platform of choice with these two easy steps:

Step 1: Set up RudderStack

Note: If you are planning to use RudderStack in production, we STRONGLY recommend using our Kubernetes Helm charts. We update our Docker images with bug fixes much more frequently than our GitHub repo.

Step 2: Verify the installation

Once you have installed RudderStack, send test events to verify the setup.

Architecture

RudderStack is an independent, stand-alone system with a dependency only on the database (PostgreSQL). Its backend is written in Go with a rich UI written in React.js.

A high-level view of RudderStack’s architecture is shown below:

Architecture

For more details on the various architectural components, refer to our documentation.

Contribute

We would love to see you contribute to RudderStack. Get more information on how to contribute here.


Download Details:

Author: Rudderlabs
Source Code: https://github.com/rudderlabs/rudder-server/ 
License: AGPL-3.0 license

#golang #react #bigquery #security #privacy 

Rudder-server: Privacy & Security Focused Segment-alternative

Eraser: Cleaning Up Images From Kubernetes Nodes

Eraser: Cleaning up Images from Kubernetes Nodes

Eraser helps Kubernetes admins remove a list of non-running images from all Kubernetes nodes in a cluster.

Getting started

You can find a quick start guide in the Eraser documentation.

Contributing

There are several ways to get involved:

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Support

How to file issues and get help

This project uses GitHub Issues to track bugs and feature requests. Please search the existing issues before filing new issues to avoid duplicates. For new issues, file your bug or feature request as a new Issue.

The Eraser maintainers will respond to the best of their abilities.

Microsoft Support Policy

Eraser is an open source project that is not covered by the Microsoft Azure support policy.

Support for this project is limited to the resources listed above.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.


Download Details:

Author: Azure
Source Code: https://github.com/Azure/eraser 
License: MIT license

#kubernetes #containers #images #vulnerabilities #hacktoberfest #security #tools 

Eraser: Cleaning Up Images From Kubernetes Nodes

Полезные приемы безопасности Linux для защиты вашей системы

В предыдущем посте мы говорили о сетевых командах Linux и видели несколько полезных примеров, используемых для устранения неполадок в вашей сети, сегодня мы поговорим о некоторых командах безопасности Linux, которые вам понадобятся для защиты вашей системы.

Каждый час исследователи и хакеры обнаруживают новые уязвимости. Они строят эксплойты поверх этих уязвимостей.

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

Защита терминала

Вы можете обезопасить свою консоль, ограничив root для использования определенных терминалов. Вы можете сделать это, указав терминалы, которые будет использовать root, в файле /etc/securetty.

Имейте в виду, что крайне необходимо предотвратить вход в систему root по соображениям безопасности.

Всегда меняйте пароль

Надежный пароль является обязательным в наши дни, но чтобы добавить еще один уровень безопасности, вы должны время от времени менять свой пароль.

Вы можете забыть изменить его самостоятельно, поэтому должно быть что-то, что напоминает вам о возрасте вашего пароля и о том, когда его изменить.

Есть два способа добиться этого; первый способ — через командную строку, используя команду изменения, например:

  • С помощью команды chage.
  • Установите значения по умолчанию в /etc/login.defs.
$ chage -M 20 likegeeks

Мы используем параметр -M, чтобы установить дни истечения срока действия вашего пароля.

Вы можете ввести chage без параметров, и он спросит вас о значении.

$ chage likegeeks

Или вы можете установить свои правила по умолчанию в

/etc/login.defs

файл.

Вы можете изменить эти значения в соответствии с вашими потребностями.

PASS_MAX_DAYS 10

PASS_MIN_DAYS 0

PASS_WARN_AGE 3

Имейте в виду, что вы должны заставить пользователей использовать надежный пароль с помощью pam_cracklib .

После того, как вы установили его, вы можете перейти к

/etc/pam.d/system-auth

и введите что-то вроде этого:

password required pam_cracklib.so minlen=12 lcredit=-1 ucredit=-1 dcredit=-2 ocredit=-1

sudo-уведомление

Команда sudo упрощает жизнь, а также может привести к проблемам с безопасностью Linux, которые могут разрушить вашу жизнь.

Все конфигурации sudo в

/etc/sudoers

файл.

Вы можете запретить пользователям запускать нужные вам команды от имени root.

Вы можете заставить sudo отправлять электронное письмо, когда кто-то его использует, добавив в файл следующую строку:

mailto yourname@yourdomain.com

И установите для mail_always значение on.

mail_always on

Защита SSH

Если мы говорим о безопасности Linux, нам нужно поговорить о сервисе SSH. SSH является важным сервисом для вашей системы, он позволяет вам легко подключаться к вашей системе, а иногда это единственный способ заставить вашу систему выжить, когда что-то пойдет не так, поэтому настройка SSH является обязательной.

Поскольку в наших постах мы используем CentOS 7, файл конфигурации SSH находится в:

/etc/ssh/sshd_config

Сканеры или боты, которые используют злоумышленники, пытаются подключиться к SSH через порт 22, который используется по умолчанию.

Обычно ваш SSH-порт меняется на другой неиспользуемый порт, скажем, 5555. Вы можете изменить SSH-порт, введя номер порта в файле конфигурации следующим образом:

Port 5555

Вы также можете ограничить вход в систему root, изменив значение PermitRootLogin на no:

PermitRootЛогин нет

И, конечно же, отключите туннелированные четкие пароли и вместо этого используйте вход с открытым ключом:

PasswordAuthentication no

PermitEmptyPasswords no

Одна из проблем, с которой вы можете столкнуться, — это тайм-ауты SSH. Вы можете решить эту проблему, настроив следующие параметры.

Например, следующие настройки подразумевают, что SSH-сервер будет отправлять пакет каждые 60 секунд:

ServerAliveInterval 15

ServerAliveCountMax 3

TCPKeepAlive yes

Регулируя эти значения, вы можете обеспечить более длинное соединение:

ClientAliveInterval 30

ClientAliveCountMax 5

Вы можете указать разрешенных пользователей для использования службы SSH:

AllowUsers user1 user2

Или вы можете сделать это в группе:

AllowGroup group1 group2

Защита SSH с помощью аутентификатора Google

Кроме того, вы можете использовать двухфакторную аутентификацию для SSH, например Google Authenticator.

$  yum install google-authenticator

Затем запустите его, чтобы проверить установку.

$ google-authenticator

На вашем мобильном телефоне должно быть установлено приложение Google-аутентификатор.

Редактировать

/etc/pam.d/sshd

файл и добавьте это:

auth required pam_google_authenticator.so

И последнее, что нужно сделать, это сообщить об этом SSH, добавив следующую строку в

/etc/ssh/sshd_config
ChallengeResponseAuthentication yes

Теперь перезапустите SSH.

$ systemctl restart sshd

И когда вы входите в систему с помощью SSH, он спросит о коде подтверждения.

Обнаружение вторжений с помощью Tripwire (мониторинг файловой системы)

Tripwire — один из замечательных инструментов для обеспечения безопасности Linux. Это система обнаружения вторжений (HIDS).

Задача Tripwire — следить за файловой системой, за тем, кто изменил файлы и когда это изменение произошло.

Чтобы получить tripwire, вам нужен доступ к репозиторию EPEL. Вы можете легко добавить его:

wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm

$ rpm -ivh epel-release-7-9.noarch.rpm

После того, как вы установили репозиторий EPEL, вы можете установить tripwire.

$ sudo yum install tripwire

Сначала создайте ключевые файлы следующим образом:

$ tripwire-setup-keyfiles

Вам будет предложено ввести парольную фразу для ключевых файлов. Tripwire предложит вам использовать надежный пароль.

Теперь вы можете настроить Tripwire, внеся изменения в этот файл:

/etc/tripwire/twpol.txt

Этот файл очень легко читать и изменять, так как каждая строка имеет комментарий, который хорошо ее описывает.

Затем вы должны инициализировать его следующим образом:

$ tripwire --init

Сканирование системы займет некоторое время, в зависимости от размера ваших файлов.

Tripwire считает любые изменения в файловой системе вторжением и уведомит об этом администратора, и ему потребуется восстановить систему с файлами, которым можно доверять.

По этой причине вы должны подтверждать любые системные изменения через Tripwire. Для этого используйте следующую команду:

$ tripwire --check

И последнее, что касается Tripwire: я бы порекомендовал вам защитить файлы twpol.txt и twcfg.txt в качестве еще одного шага безопасности.

Tripwire имеет множество опций и настроек; вы можете проверить их с помощью

man tripwire

Использование брандмауэра

Firewalld — замена iptables; это улучшает управление безопасностью Linux. Вы можете изменить конфигурацию, не прерывая текущие соединения.

Он работает как служба, которая позволяет нам немедленно добавлять и изменять правила, и использует сетевые зоны.

Чтобы узнать, запущен ли в данный момент Firewalld, введите следующую команду:

$ firewall-cmd --state

Вы можете перечислить предопределенные зоны следующим образом:

$ firewall-cmd --get-zones

Каждая зона из них имеет уровень доверия.

Вы можете обновить значение следующим образом:

$ firewall-cmd --set-default-zone=<new-name>

Вы можете получить всю необходимую информацию о любой конкретной зоне следующим образом:

$ firewall-cmd --zone=<zone-name> --list-all

Вы можете перечислить все поддерживаемые сервисы следующим образом:

$ firewall-cmd --get-services

Затем вы можете добавить дополнительные услуги или удалить их внутри зоны:

$ firewall-cmd --zone=<zone-name> --add-service=<service-name>

$ firewall-cmd --zone=<zone-name> --remove-service=<service-name>

Вы можете перечислить все порты, открытые в любой конкретной зоне:

$ firewall-cmd --zone=<zone-name> --list-ports

Вы можете добавить порты в зону следующим образом:

$ firewall-cmd --zone=<zone-name> --add-port=<port-number/protocol>

$ firewall-cmd --zone=<zone-name> --remove-port=<port-number/protocol>

Вы можете добавить или удалить перенаправление портов следующим образом:

$ firewall-cmd --zone=<zone-name> --add-forward-port=<port-number>

$ firewall-cmd --zone=<zone-name> --remove-forward-port=<port-number>

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

Возвращаемся к iptables

Некоторые люди предпочитают брандмауэр iptables Firewalld; вы можете легко вернуться к iptables.

Сначала отключите Firewalld:

$ systemctl disable firewalld

$ systemctl stop firewalld

Затем установите iptables:

$ yum install iptables-services

$ touch /etc/sysconfig/iptables

$ touch /etc/sysconfig/ip6tables

Теперь вы можете запустить службу iptables:

$ systemctl start iptables

$ systemctl start ip6tables

$ systemctl enable iptables

$ systemctl enable ip6tables

Наконец, перезагрузите систему.

Ограничение компиляторов

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

Сначала получите список всех бинарников из пакетов, затем установите для них разрешение.

$ rpm -q --filesbypkg gcc | grep 'bin'

Создайте новую группу:

$ groupadd compilerGroup

Затем измените группу двоичных файлов компилятора следующим образом:

$ chown root:compilerGroup /usr/bin/gcc

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

$ chmod 0750 /usr/bin/gcc

Теперь любой пользователь, который попытается использовать gcc, увидит сообщение об отказе в доступе.

Потрясающие неизменяемые файлы (предотвратить изменение файлов)

Вы не можете перезаписывать неизменяемые файлы любым пользователем, даже root. Он не может изменить или удалить его, если не удалит из него неизменяемый бит, и это может сделать только пользователь root.

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

Вы можете защитить файлы конфигурации или любой файл, который вы хотите.

Чтобы сделать любой файл неизменяемым, используйте команду chattr .

$ chattr +i /myscript

Вы можете удалить неизменяемый атрибут следующим образом:

$ chattr -i /myscript

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

Остальные примеры использования неизменяемых файлов я оставлю на ваше воображение.

Управление SELinux с помощью aureport

Обычно, если вы используете панели управления хостингом, вы обнаружите, что SELinux отключен.

Отключение SELinux оставит систему незащищенной. Я согласен, но в SELinux есть некоторые сложности, но вы можете облегчить себе жизнь, если будете управлять им с помощью aureport.

Утилита aureport предназначена для создания табличных отчетов для файлов журналов аудита .

$ aureport --avc

Вы можете создать список исполняемых файлов следующим образом:

$ aureport -x

Вы можете использовать aureport для создания полного отчета об аутентификации.

$ aureport -au -i

Или вы можете перечислить неудачные события аутентификации.

$ aureport -au --summary -i --failed

Или, может быть, сводка успешных событий аутентификации.

Awesome!!

Инструмент aureport упрощает работу с SELinux.

Использование инструмента герметика

В дополнение к инструменту aureport вы можете использовать хороший инструмент безопасности Linux, называемый sealert, вы можете установить его с помощью этой команды:

$ yum install setools

Теперь у нас есть инструмент, который будет активно возвращать объявления с

/var/log/audit/audit.log

файл и дает нам что-то читаемое о проблемах SELinux.

Вы можете использовать его следующим образом:

$ sealert -a /var/log/audit/audit.log

Самое лучшее в отчете sealert — это то, что в конце каждого предупреждения вы найдете способ решения проблемы.

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

Надеюсь, вы нашли пост полезным и интересным.

Спасибо.

Оригинальный источник статьи: https://likegeeks.com/

#linux #security #tricks 

Полезные приемы безопасности Linux для защиты вашей системы
津田  淳

津田 淳

1679388540

如何使用有用的 Linux 安全技巧来强化您的系统

在上一篇文章中,我们讨论了Linux 网络命令,我们看到了一些用于排除网络故障的有用示例,今天我们将讨论一些您需要加固系统的 Linux 安全命令。

研究人员和黑客每小时都会发现新的漏洞。他们在这些漏洞之上构建漏洞。

也许您正在定期更新您的系统,但这还不够,您需要加固您的系统以尽可能地保护您的资产。

保护终端

您可以通过限制根使用特定终端来保护您的控制台。您可以通过在 /etc/securetty 文件中指定 root 将使用的终端来执行此操作。

请记住,出于安全原因,非常需要阻止 root 登录。

随时更改密码

如今,强密码是必须的,但为了增加另一层安全性,您应该不时更改密码。

您可能会忘记自己更改它,因此必须有一些东西可以提醒您您的密码年龄以及何时修改它。

有两种方法可以实现这一目标;第一种方法是通过命令行使用如下更改命令:

  • 使用 chage 命令。
  • 在 /etc/login.defs 中设置默认值。
$ chage -M 20 likegeeks

我们使用 -M 选项来设置密码的到期日。

您可以键入不带选项的 chage,它会询问您有关该值的信息。

$ chage likegeeks

或者您可以在中设置默认规则

/etc/login.defs

文件。

您可以根据需要更改这些值。

PASS_MAX_DAYS 10

PASS_MIN_DAYS 0

PASS_WARN_AGE 3

请记住,您应该使用pam_cracklib强制用户使用强密码。

一旦你安装了它,你可以去

/etc/pam.d/system-auth

并输入如下内容:

password required pam_cracklib.so minlen=12 lcredit=-1 ucredit=-1 dcredit=-2 ocredit=-1

须藤通知

sudo 命令让生活更轻松,也可能导致 Linux 安全问题,从而毁了你的生活。

中的所有 sudo 配置

/etc/sudoers

文件。

您可以阻止用户以 root 身份运行您想要的命令。

您可以通过在文件中添加以下行来让 sudo 在有人使用它时发送电子邮件:

mailto yourname@yourdomain.com

并将 mail_always 设置为打开。

mail_always on

保护 SSH

说起 Linux 安全,就不得不说说 SSH 服务。SSH 是您的系统必不可少的服务,它使您能够轻松地连接到您的系统,有时它是让您的系统在出现问题时存活下来的唯一方法,因此调整 SSH 是必须的。

由于我们的帖子使用的是CentOS 7,所以SSH配置文件在:

/etc/ssh/sshd_config

攻击者使用的扫描器或机器人尝试连接到默认端口 22 上的 SSH。

将 SSH 端口更改为另一个未使用的端口很常见,比如 5555。您可以通过在配置文件中键入端口号来更改 SSH 端口,如下所示:

Port 5555

您还可以通过将 PermitRootLogin 的值更新为 no 来限制 root 登录:

PermitRoot登录号

并确保禁用隧道明文密码并改为使用公私密钥登录:

PasswordAuthentication no

PermitEmptyPasswords no

您可能面临的问题之一是 SSH 超时。您可以通过配置以下设置来处理此问题。

例如,以下设置意味着 SSH 服务器将每 60 秒发送一个数据包:

ServerAliveInterval 15

ServerAliveCountMax 3

TCPKeepAlive yes

通过调整这些值,您可以提供更长的连接:

ClientAliveInterval 30

ClientAliveCountMax 5

您可以指定允许使用 SSH 服务的用户:

AllowUsers user1 user2

或者你可以按组制作:

AllowGroup group1 group2

使用 Google 身份验证器保护 SSH

除此之外,您还可以对 SSH 使用双因素身份验证,例如 google authenticator。

$  yum install google-authenticator

然后运行它以验证安装。

$ google-authenticator

您应该在手机上安装谷歌验证器应用程序。

编辑

/etc/pam.d/sshd

文件并添加:

auth required pam_google_authenticator.so

最后要做的是通过将以下行添加到

/etc/ssh/sshd_config
ChallengeResponseAuthentication yes

现在重新启动您的 SSH。

$ systemctl restart sshd

并且当你使用SSH登录时,它会询问验证码。

使用 Tripwire 进行入侵检测(监控文件系统)

Tripwire 是 Linux 安全领域的重要工具之一。它是一个入侵检测系统 (HIDS)。

Tripwire 的工作是监控文件系统、更改文件的人员以及更改发生的时间。

要获得 tripwire,您需要访问 EPEL 存储库。您可以轻松添加它:

wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm

$ rpm -ivh epel-release-7-9.noarch.rpm

一旦你安装了 EPEL 仓库,你就可以安装 tripwire。

$ sudo yum install tripwire

首先,像这样创建密钥文件:

$ tripwire-setup-keyfiles

它将提示您输入密钥文件的密码。Tripwire 会告诉你使用强密码。

现在您可以通过更改此文件来自定义 Tripwire:

/etc/tripwire/twpol.txt

这个文件非常容易阅读和修改,因为每一行都有一个很好地描述它的注释。

然后你应该像这样初始化它:

$ tripwire --init

扫描系统需要一些时间,具体取决于您的文件大小。

Tripwire 将对文件系统的任何修改视为入侵,并将通知管理员,他将需要使用可信任的文件来恢复系统。

因此,您应该通过 Tripwire 验证任何系统更改。为此,请使用以下命令:

$ tripwire --check

关于 Tripwire 的最后一件事,我建议您保护 twpol.txttwcfg.txt文件,作为安全的另一个步骤。

Tripwire 有很多选项和设置;你可以检查它们

man tripwire

使用防火墙

Firewalld 是 iptables 的替代品;它提高了 Linux 安全性的管理。您可以在不停止当前连接的情况下更改配置。

它作为一项服务运行,允许我们立即添加和更改规则,并且它使用网络区域。

要知道 Firewalld 当前是否正在运行,请键入以下命令:

$ firewall-cmd --state

您可以像这样列出预定义区域:

$ firewall-cmd --get-zones

其中的每个区域都有一个信任级别。

您可以像这样更新值:

$ firewall-cmd --set-default-zone=<new-name>

您可以获得有关任何特定区域的所有相关信息,如下所示:

$ firewall-cmd --zone=<zone-name> --list-all

您可以像这样列出所有支持的服务:

$ firewall-cmd --get-services

然后您可以在区域内添加或删除其他服务:

$ firewall-cmd --zone=<zone-name> --add-service=<service-name>

$ firewall-cmd --zone=<zone-name> --remove-service=<service-name>

您可以列出在任何特定区域中打开的所有端口:

$ firewall-cmd --zone=<zone-name> --list-ports

您可以像这样将端口添加到区域:

$ firewall-cmd --zone=<zone-name> --add-port=<port-number/protocol>

$ firewall-cmd --zone=<zone-name> --remove-port=<port-number/protocol>

您可以像这样添加或删除端口转发:

$ firewall-cmd --zone=<zone-name> --add-forward-port=<port-number>

$ firewall-cmd --zone=<zone-name> --remove-forward-port=<port-number>

Firewalld 非常全面,Firewalld 最好的地方是你可以在不重启或停止服务的情况下管理防火墙架构,不像 iptables,你应该重新加载或重启服务。

回到 iptables

有些人更喜欢iptables 防火墙而不是 Firewalld;您可以轻松返回 iptables。

首先,禁用 Firewalld:

$ systemctl disable firewalld

$ systemctl stop firewalld

然后安装iptables:

$ yum install iptables-services

$ touch /etc/sysconfig/iptables

$ touch /etc/sysconfig/ip6tables

现在你可以启动 iptables 服务了:

$ systemctl start iptables

$ systemctl start ip6tables

$ systemctl enable iptables

$ systemctl enable ip6tables

最后,重新启动系统。

限制编译器

攻击者可能会在他的机器上编译漏洞并将其上传到受害者服务器而不需要编译器,但无论如何,如果您不像大多数现代托管面板那样在生产中使用它们,最好限制编译器。

首先,从包中获取所有二进制文件的列表,然后为它们设置权限。

$ rpm -q --filesbypkg gcc | grep 'bin'

创建一个新组:

$ groupadd compilerGroup

然后像这样更改编译器二进制文件组:

$ chown root:compilerGroup /usr/bin/gcc

最后一件重要的事情是将此二进制文件的权限更改为仅编译器组。

$ chmod 0750 /usr/bin/gcc

现在,任何尝试使用 gcc 的用户都会看到权限被拒绝的消息。

很棒的不可变文件(防止文件修改)

您不能由任何用户覆盖不可变文件,即使是 root。除非他从中删除不可变位,否则他无法修改或删除它,而 root 用户只能执行此操作。

您可以说此功能以 root 身份保护您免受任何可能损坏或危害您的系统的错误。惊人的!!

您可以保护配置文件或任何您想要的文件。

要使任何文件不可变,请使用chattr 命令

$ chattr +i /myscript

您可以像这样删除不可变属性:

$ chattr -i /myscript

您可以用相同的方式保护系统中的任何文件,但请记住,如果您对系统二进制文件执行此操作,除非删除不可变位,否则无法更新它们。

我将把其余使用不可变文件的示例留给您去想象。

使用 aureport 管理 SELinux

如果您使用主机控制面板,您会发现 SELinux 被禁用是很常见的事情。

禁用 SELinux 将使系统暴露在外。我同意,但是 SELinux 有一些复杂性,但是如果您使用 aureport 来管理它,您可以让您的生活更轻松。

aureport 实用程序是为审计日志文件创建表格报告而开发的。

$ aureport --avc

您可以像这样创建可执行文件列表:

$ aureport -x

您可以使用 aureport 生成完整的身份验证报告。

$ aureport -au -i

或者您可以列出失败的身份验证事件。

$ aureport -au --summary -i --failed

或者可能是成功身份验证事件的摘要。

惊人的!!

aureport 工具使使用 SELinux 变得非常容易。

使用 sealert 工具

除了 aureport 工具,你还可以使用一个很好的 Linux 安全工具,叫做 sealert,你可以用这个命令安装它:

$ yum install setools

现在我们有一个工具可以主动返回公告

/var/log/audit/audit.log

文件并为我们提供有关 SELinux 问题的可读信息。

你可以像这样使用它:

$ sealert -a /var/log/audit/audit.log

sealert 报告最好的一点是在每个警报的结尾,您会找到解决问题的方法。

在这篇文章中,我们只介绍了一些可以帮助您强化系统的 Linux 安全技巧。但是,对于许多需要加固的正在运行的服务,有很多 Linux 安全技巧。

我希望你觉得这篇文章有用且有趣。

谢谢。

文章原文出处:https: //likegeeks.com/

#linux #security #tricks 

如何使用有用的 Linux 安全技巧来强化您的系统
Bongani  Ngema

Bongani Ngema

1679384659

How to Useful Linux Security Tricks To Harden Your System

In the previous post, we talked about Linux network commands, and we saw some useful examples used to troubleshoot your network, today we will talk about some Linux security commands that you will need to harden your system.

Researchers and hackers discover new vulnerabilities every hour. They build exploits on top of these vulnerabilities.

Maybe you are updating your system periodically, but this is not enough, you need to harden your system to protect your assets as much as possible.

Securing the terminal

You can secure your console by limiting the root to use particular terminals. You can do this by specifying the terminals that the root will use in /etc/securetty file.

Keep in mind that it’s highly required to prevent root login for security reasons.

Change your password always

A strong password is a must these days, but to add another layer of security, you should change your password from time to time.

You may forget to change it yourself, so there must be something that reminds you about your password age and when to modify it.

There are two ways to achieve that; the first way is by command line using the change command like this:

  • Using the chage command.
  • Set defaults in /etc/login.defs.
$ chage -M 20 likegeeks

We use the -M option to set the expiration days for your password.

You can type chage without options, and it will ask you about the value.

$ chage likegeeks

Or you can set your default rules in

/etc/login.defs

file.

You can change these values according to your needs.

PASS_MAX_DAYS 10

PASS_MIN_DAYS 0

PASS_WARN_AGE 3

Keep in mind that you should force users to use a strong password using pam_cracklib.

Once you’ve installed it, you can go to

/etc/pam.d/system-auth

and type something like this:

password required pam_cracklib.so minlen=12 lcredit=-1 ucredit=-1 dcredit=-2 ocredit=-1

sudo notification

sudo command makes life easier and also can lead to Linux Security issues that can ruin your life.

All sudo configurations in the

/etc/sudoers

file.

You can prevent users from running the commands you want as root.

You can make sudo send an email when somebody uses it by adding the following line to the file:

mailto yourname@yourdomain.com

And set mail_always to on.

mail_always on

Securing SSH

If we talk about Linux security, we need to talk about SSH service. SSH is an essential service to your system, it enables you to connect easily to your system, and sometimes it is the only way to make your system survive when things go bad, so tuning SSH is a must.

Since we use CentOS 7 in our posts, so the SSH configuration file is in:

/etc/ssh/sshd_config

The scanners or bots that the attackers use try to connect to SSH on port 22, which is the default.

It is common to change your SSH port to another unused port, let’s say 5555. You can change the SSH port by typing the Port number in the configuration file like this:

Port 5555

You can also restrict the root login by updating the value of PermitRootLogin to no:

PermitRootLogin no

And surely disable tunneled clear passwords and use public-private key login instead:

PasswordAuthentication no

PermitEmptyPasswords no

One of the issues you may face is the SSH timeouts. You can handle this problem by configuring the following settings.

For example, the following settings imply that the SSH server will send a packet every 60 seconds:

ServerAliveInterval 15

ServerAliveCountMax 3

TCPKeepAlive yes

By adjusting these values, you can provide a longer connection:

ClientAliveInterval 30

ClientAliveCountMax 5

You can specify the allowed users for using SSH service:

AllowUsers user1 user2

Or you can make it per group:

AllowGroup group1 group2

Securing SSH using Google authenticator

Further to this, you can use two-factor authentication for SSH like google authenticator.

$  yum install google-authenticator

Then run it to verify the installation.

$ google-authenticator

You should have Google authenticator application installed on your Mobile phone.

Edit

/etc/pam.d/sshd

file and add this:

auth required pam_google_authenticator.so

And the last thing to do is to tell SSH about this by adding the following line to

/etc/ssh/sshd_config
ChallengeResponseAuthentication yes

Now restart your SSH.

$ systemctl restart sshd

And when you log in using SSH, it will ask about verification code.

Intrusion detection with Tripwire (Monitoring Filesystem)

Tripwire is one of the great tools in Linux security. It’s an intrusion detection system (HIDS).

Tripwire’s job is to monitor the filesystem, who changed the files, and when that change happened.

To get tripwire, you need access to the EPEL repository. You can add it easily:

wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-9.noarch.rpm

$ rpm -ivh epel-release-7-9.noarch.rpm

Once you’ve installed EPEL repo, you can install tripwire.

$ sudo yum install tripwire

First, create keyfiles like this:

$ tripwire-setup-keyfiles

It will prompt you to enter a passphrase for keyfiles. Tripwire will tell you to use a strong password.

Now you can customize Tripwire by making changes to this file:

/etc/tripwire/twpol.txt

This file is very easy to read and modify since every line has a comment that describes it well.

Then you should initialize it like this:

$ tripwire --init

It will take some time scanning the system depends on your file sizes.

Tripwire considers any modifications to the filesystem as an intrusion and will notify the administrator, and he will need to restore the system with files that can be trusted.

For this reason, you should validate any system changes through Tripwire. To do this, use the following command:

$ tripwire --check

One last thing about Tripwire, I would recommend that you secure both the twpol.txt and twcfg.txt files as another step of security.

Tripwire has a lot of options and settings; you can check them with

man tripwire

Using firewalld

Firewalld is a replacement for iptables; it improves the management of Linux security. You can change the configuration without stopping the current connections.

It runs as a service that allows us to add and change rules immediately, and it uses network zones.

To know if Firewalld is currently running or not, type this command:

$ firewall-cmd --state

You can list the predefined zones like this:

$ firewall-cmd --get-zones

Each zone of these has a trust level.

You can update the value like this:

$ firewall-cmd --set-default-zone=<new-name>

You can get all the relevant information about any particular zone like this:

$ firewall-cmd --zone=<zone-name> --list-all

You can list all supported services like this:

$ firewall-cmd --get-services

Then you can add additional services or remove them within a zone:

$ firewall-cmd --zone=<zone-name> --add-service=<service-name>

$ firewall-cmd --zone=<zone-name> --remove-service=<service-name>

You can list all ports open in any particular zone:

$ firewall-cmd --zone=<zone-name> --list-ports

You can add ports to a zone like this:

$ firewall-cmd --zone=<zone-name> --add-port=<port-number/protocol>

$ firewall-cmd --zone=<zone-name> --remove-port=<port-number/protocol>

You can add or remove port forwarding like this:

$ firewall-cmd --zone=<zone-name> --add-forward-port=<port-number>

$ firewall-cmd --zone=<zone-name> --remove-forward-port=<port-number>

Firewalld is very comprehensive, and the best thing about Firewalld is that you can manage firewall architecture without restarting or stopping service, unlike iptables, where you should reload or restart the service.

Returning to iptables

Some people prefer iptables firewall over Firewalld; you can return to iptables easily.

First, disable Firewalld:

$ systemctl disable firewalld

$ systemctl stop firewalld

Then install iptables:

$ yum install iptables-services

$ touch /etc/sysconfig/iptables

$ touch /etc/sysconfig/ip6tables

Now you can start the iptables service:

$ systemctl start iptables

$ systemctl start ip6tables

$ systemctl enable iptables

$ systemctl enable ip6tables

Finally, reboot your system.

Restricting the compilers

The attacker might compile the exploits on his machine and upload it to the victim server without the need to the compilers, but anyway, it’s preferable to restrict the compilers if you don’t use them in production as most modern hosting panels do.

First, get a list of all binaries from packages, then set the permission for them.

$ rpm -q --filesbypkg gcc | grep 'bin'

Create a new group:

$ groupadd compilerGroup

Then change the group of the compiler binaries like this:

$ chown root:compilerGroup /usr/bin/gcc

And one last important thing is to change the permission of this binary to be only the compilers group.

$ chmod 0750 /usr/bin/gcc

Now, any user who tries to use gcc will see permission denied message.

Awesome immutable files (Prevent File Modification)

You cannot overwrite immutable files by any user, even root. He can’t modify it or delete it unless he removes the immutable bit from it, and root user only can do this.

You can say that this feature protects you as root from any mistakes that can damage or harm your system. Awesome!!

You can protect configuration files or any file you want.

To make any file immutable, use the chattr command.

$ chattr +i /myscript

You can remove immutable attribute like this:

$ chattr -i /myscript

You can protect any files in your system the same way, but keep in mind that, if you do this to the system binaries, you can’t update them unless you remove the immutable bit.

I will leave the rest of the examples of using immutable files to your imagination.

Managing SELinux with aureport

It is a common thing if you are using hosting control panels, you will find SELinux disabled.

Disabling SELinux will leave the system exposed. I agree, but SELinux has some complexity, but you can make your life easier if you manage it using aureport.

The aureport utility is developed to create tabular reports for audit log files.

$ aureport --avc

You can create a list of executable files like this:

$ aureport -x

You can use aureport to generate a full authentication report.

$ aureport -au -i

Or you can list the failed authentication events.

$ aureport -au --summary -i --failed

Or maybe a summary of successful authentication events.

Awesome!!

aureport tool makes working with SELinux pretty easy.

Using the sealert Tool

In addition to the aureport tool, you can use a good Linux security tool called sealert, you can install it with this command:

$ yum install setools

Now we have a tool that will actively return announcements from

/var/log/audit/audit.log

file and gives us something readable about SELinux problems.

You can use it like this:

$ sealert -a /var/log/audit/audit.log

The best thing about the sealert report is at the end of each alert, you will find how to resolve the problem.

In this post, we’ve covered just some of the Linux security tricks that can help you harden your system. However, there are a lot of Linux security tricks for many running services that need hardening.

I hope you found the post useful and interesting.

Thank you.

Original article source at: https://likegeeks.com/

#linux #security #tricks 

How to Useful Linux Security Tricks To Harden Your System
佴 芬嘉

佴 芬嘉

1679148060

了解 API 安全的 5 条基本原则

在本 API 教程中,我们将了解 API 安全的 5 条基本原则。应用程序编程接口 (API) 是数字化转型和业务创新的核心,使公司能够为客户创建新产品和服务。 

但与每件好事一样,也存在挑战。API 是很好的连接器,但这些连接会带来一定的风险。很少有一周没有关于另一次 API 攻击的消息。不幸的是,这不能再被视为只是一个警告。由于 API 漏洞可能导致危险的后果,因此绝对不应忽视它们。API 安全应该是任何开发 API 或将它们集成到应用程序中的人的优先事项。

尽管经常讨论提高 API 安全性的必要性,但许多组织仍未将其列为优先事项。您可能已经读到过像 Tesla 或 Peloton 这样的大公司正在经历 API 漏洞。但是,如果在同一级别上报告各种规模的 API 攻击,那么保护 API 的重要性就会变得一目了然。

在本文中,我将重点介绍 API 安全性的关键注意事项。通过遵循这些核心原则,组织和开发人员可以确保其系统的安全并降低成为下一个 API 漏洞主体的风险。

1. 确保保护所有API

API可以分为两类:外部API和内部API。从名称来看,似乎外部的应该比内部的更好地受到保护——就像你家的门需要安全锁一样。但是,涉及到API安全,API是否暴露给外部环境就真的不重要了。它应该始终受到保护。这与零信任架构保持一致,在这种架构中,从基于网络的边界转变为基于身份的边界需要验证对 API 的所有访问权限。

将应用程序与第三方资源集成的外部 API 似乎更容易受到攻击。未能设置身份验证和授权可能导致第三方代理获得对内部数据的访问权限。尽管这些数据可能不太敏感,但泄露的信息可用于加深漏洞并发起网络钓鱼攻击以获取更关键的用户和系统数据。

然而,重要的是要记住,内部 API 可能与外部 API 一样容易受到攻击。这些 API 广泛用于访问系统内的资源和链接内部应用程序。但是,它们位于系统边界内这一事实并不能使它们受到更多保护。因此,建议保护所有 API。攻击可能来自内部 — 攻击者可能会在创建供内部使用然后在外部发布时发现您的 API。此外,由于内部服务未受保护,外部参与者首先破坏边界安全然后深入基础设施的情况并不少见。

2.始终使用API​​网关和中央OAuth服务器

API 网关是一种工具,可确保对后端服务的访问经过身份验证和授权。它还有助于集中跨 API 使用的通用功能。网关可以标准化与您的 API 的交互并充当单一入口点。标准 API 网关功能包括速率限制、阻止恶意客户端、正确的日志记录、路径和标头重写以及收集业务指标。如果没有网关,API 提供商将不得不通过各种功能逐个增强每个端点,如果遗漏任何一个,可能会导致严重的安全漏洞。

为了实现其中大部分功能,API 网关需要证明调用者是谁。此验证通常以基于令牌的方式处理,其中令牌代表最终用户并包含有关客户端应用程序的信息。可以通过不同的方式获得此类令牌,​​但目前最流行和最安全的方法之一是使用 OAuth 2.0 和 OpenID Connect 标准来定义令牌的发布方式。一旦这些令牌被颁发并呈现给 API 网关,就必须对其进行验证。验证不同令牌类型的模式多种多样,但市场上大多数现代 API 网关都可以处理这种情况。至少,应验证令牌的过期时间,并且通常还通过验证声明来检查令牌是否颁发给了正确的受众aud

总而言之,将您的 API(包括公共 API 和内部 API)置于网关之后可以提高安全性。但是,确保您的 API 网关不颁发令牌至关重要。相反,中央 OAuth 服务器应该颁发令牌,因为它实现了许多复杂的过程,如客户端和用户身份验证、客户端授权、令牌签名等。这些过程涉及处理大量数据和许多用于签署已颁发凭据的密钥。此类任务只能由 OAuth 服务器执行。集中管理凭据和令牌发行将使您能够减轻与临时解决方案和补丁相关的风险。

3.明智地使用访问令牌

基于令牌的现代架构非常适合保护 API。令牌有助于建立信任并确保 API 有足够的信息来做出正确的访问决策。但是,要充分获得收益并保护您的系统,正确使用每种不同的令牌类型至关重要。

JSON Web Tokens(或 JWT)已成为使用最广泛的访问令牌格式之一,因为它们易于使用并且可以由服务本身进行验证。然而,虽然使用 JWT 作为访问和刷新令牌被认为是一种好的做法,但请记住它们只能在内部使用。当令牌在您的基础架构之外暴露给第三方客户端时,您应该使用不透明令牌而不是 JWT。

不透明令牌被认为比 JWT 更安全有几个原因。首先是它们的性质——它们是不透明的字符串,对客户没有任何意义。当它收到一个不透明的令牌时,它必须调用发行者来验证令牌并获取数据。另一方面,当使用 JWT 时,接收方不需要调用发行方,因此不可能撤销 JWT。JWT 也极有可能包含一些个人身份信息 (PII),应用程序本身不应使用这些信息并将其用于 API,因此 JWT 更适合内部使用。

其他一些要遵循的令牌处理最佳实践是:

  • 始终验证传入的 JWT。
  • 创建或重用用于 JWT 验证的库。
  • 不要使用 JWT 进行会话处理。
  • 为外部或公共客户使用不透明的令牌。

正确使用令牌是 API 安全不可或缺的一部分。遵循安全专家创建的最佳实践。

4.限制对传入流量的信任

考虑对您的 API 应用零信任方法。建立零信任架构意味着创建一个系统,在这个系统中,任何人都不可信,任何用户或访问数据的服务都经过验证。零信任架构本身并不是一个单一的架构——它是一套设计系统和操作的指南,旨在加强安全性以保护企业资产。

身份验证对于成功实施零信任架构至关重要。例如,确定用户是否是内部用户、用户属于组织的哪个部分、哪个服务正在从另一个服务请求信息以及哪个第三方服务正在请求访问内部公司服务是至关重要的。

可以通过使用 HTTPS(甚至在内部)并验证所有传入的 JWT,甚至是那些由网关从不透明令牌转换而来的 JWT,来限制对传入流量的信任。这将防止恶意行为者在您的基础设施内操作。

5. 始终测试、监控和审计

为了使您的 API 和整个系统真正有效地抵御安全威胁,必须持续测试和监控哪些 API 或端点构成风险。必须在初始阶段识别漏洞,以便相对容易和快速地纠正它们。

设置旨在保护您的 API 的安全措施之后,应建立对它们的治理。让专门的专家团队积极监控和审核您的 API 安全系统始终是一个好主意。这些人应该收集指标、记录 API 使用情况,并检查意外请求或异常客户端行为。这将使您能够在漏洞损害您的系统之前发现漏洞,从而确保您组织的资产和用户数据安全。

结论

随着 API 的重要性不断增加,维护高标准的 API 安全性成为首要问题。因此,必须确保 API 和流经它们的数据安全且仅供预期用户访问。这不是等待的事情——如果你还没有,你需要现在就开始。

请记住保护外部和内部 API、利用 API 网关、使用中央 OAuth 服务器、定期验证传入流量并持续审核您的系统。管理 API 身份验证和授权时需要考虑许多技术策略。遵循最佳实践可以帮助您保护 API 并阻止不良行为。

文章原文出处:https: //nordicapis.com

#api #security 

了解 API 安全的 5 条基本原则

Cilium: eBPF-based Networking, Security, and Observability

Cilium

Cilium is a networking, observability, and security solution with an eBPF-based dataplane. It provides a simple flat Layer 3 network with the ability to span multiple clusters in either a native routing or overlay mode. It is L7-protocol aware and can enforce network policies on L3-L7 using an identity based security model that is decoupled from network addressing.

Cilium implements distributed load balancing for traffic between pods and to external services, and is able to fully replace kube-proxy, using efficient hash tables in eBPF allowing for almost unlimited scale. It also supports advanced functionality like integrated ingress and egress gateway, bandwidth management and service mesh, and provides deep network and security visibility and monitoring.

A new Linux kernel technology called eBPF is at the foundation of Cilium. It supports dynamic insertion of eBPF bytecode into the Linux kernel at various integration points such as: network IO, application sockets, and tracepoints to implement security, networking and visibility logic. eBPF is highly efficient and flexible. To learn more about eBPF, visit eBPF.io.

Overview of Cilium features for networking, observability, service mesh, and runtime security

Stable Releases

The Cilium community maintains minor stable releases for the last three major Cilium versions. Older Cilium stable versions from major releases prior to that are considered EOL.

For upgrades to new major releases please consult the Cilium Upgrade Guide.

Listed below are the actively maintained release branches along with their latest minor release, corresponding image pull tags and their release notes:

v1.132023-02-15quay.io/cilium/cilium:v1.13.0Release Notes
v1.122023-02-13quay.io/cilium/cilium:v1.12.7Release Notes
v1.112023-02-13quay.io/cilium/cilium:v1.11.14Release Notes

Software Bill of Materials

Starting with Cilium version 1.13.0, all images include a Software Bill of Materials (SBOM). The SBOM is generated in SPDX format. More information on this is available on Cilium SBOM.

Functionality Overview

Protect and secure APIs transparently

Ability to secure modern application protocols such as REST/HTTP, gRPC and Kafka. Traditional firewalls operates at Layer 3 and 4. A protocol running on a particular port is either completely trusted or blocked entirely. Cilium provides the ability to filter on individual application protocol requests such as:

  • Allow all HTTP requests with method GET and path /public/.*. Deny all other requests.
  • Allow service1 to produce on Kafka topic topic1 and service2 to consume on topic1. Reject all other Kafka messages.
  • Require the HTTP header X-Token: [0-9]+ to be present in all REST calls.

See the section Layer 7 Policy in our documentation for the latest list of supported protocols and examples on how to use it.

Secure service to service communication based on identities

Modern distributed applications rely on technologies such as application containers to facilitate agility in deployment and scale out on demand. This results in a large number of application containers to be started in a short period of time. Typical container firewalls secure workloads by filtering on source IP addresses and destination ports. This concept requires the firewalls on all servers to be manipulated whenever a container is started anywhere in the cluster.

In order to avoid this situation which limits scale, Cilium assigns a security identity to groups of application containers which share identical security policies. The identity is then associated with all network packets emitted by the application containers, allowing to validate the identity at the receiving node. Security identity management is performed using a key-value store.

Secure access to and from external services

Label based security is the tool of choice for cluster internal access control. In order to secure access to and from external services, traditional CIDR based security policies for both ingress and egress are supported. This allows to limit access to and from application containers to particular IP ranges.

Simple Networking

A simple flat Layer 3 network with the ability to span multiple clusters connects all application containers. IP allocation is kept simple by using host scope allocators. This means that each host can allocate IPs without any coordination between hosts.

The following multi node networking models are supported:

Overlay: Encapsulation-based virtual network spanning all hosts. Currently VXLAN and Geneve are baked in but all encapsulation formats supported by Linux can be enabled.

When to use this mode: This mode has minimal infrastructure and integration requirements. It works on almost any network infrastructure as the only requirement is IP connectivity between hosts which is typically already given.

Native Routing: Use of the regular routing table of the Linux host. The network is required to be capable to route the IP addresses of the application containers.

When to use this mode: This mode is for advanced users and requires some awareness of the underlying networking infrastructure. This mode works well with:

  • Native IPv6 networks
  • In conjunction with cloud network routers
  • If you are already running routing daemons

Load Balancing

Cilium implements distributed load balancing for traffic between application containers and to external services and is able to fully replace components such as kube-proxy. The load balancing is implemented in eBPF using efficient hashtables allowing for almost unlimited scale.

For north-south type load balancing, Cilium's eBPF implementation is optimized for maximum performance, can be attached to XDP (eXpress Data Path), and supports direct server return (DSR) as well as Maglev consistent hashing if the load balancing operation is not performed on the source host.

For east-west type load balancing, Cilium performs efficient service-to-backend translation right in the Linux kernel's socket layer (e.g. at TCP connect time) such that per-packet NAT operations overhead can be avoided in lower layers.

Bandwidth Management

Cilium implements bandwidth management through efficient EDT-based (Earliest Departure Time) rate-limiting with eBPF for container traffic that is egressing a node. This allows to significantly reduce transmission tail latencies for applications and to avoid locking under multi-queue NICs compared to traditional approaches such as HTB (Hierarchy Token Bucket) or TBF (Token Bucket Filter) as used in the bandwidth CNI plugin, for example.

Monitoring and Troubleshooting

The ability to gain visibility and to troubleshoot issues is fundamental to the operation of any distributed system. While we learned to love tools like tcpdump and ping and while they will always find a special place in our hearts, we strive to provide better tooling for troubleshooting. This includes tooling to provide:

  • Event monitoring with metadata: When a packet is dropped, the tool doesn't just report the source and destination IP of the packet, the tool provides the full label information of both the sender and receiver among a lot of other information.
  • Metrics export via Prometheus: Key metrics are exported via Prometheus for integration with your existing dashboards.
  • Hubble: An observability platform specifically written for Cilium. It provides service dependency maps, operational monitoring and alerting, and application and security visibility based on flow logs.

Getting Started

What is eBPF and XDP?

Berkeley Packet Filter (BPF) is a Linux kernel bytecode interpreter originally introduced to filter network packets, e.g. for tcpdump and socket filters. The BPF instruction set and surrounding architecture has recently been significantly reworked with additional data structures such as hash tables and arrays for keeping state as well as additional actions to support packet mangling, forwarding, encapsulation, etc. Furthermore, a compiler back end for LLVM allows for programs to be written in C and compiled into BPF instructions. An in-kernel verifier ensures that BPF programs are safe to run and a JIT compiler converts the BPF bytecode to CPU architecture specific instructions for native execution efficiency. BPF programs can be run at various hooking points in the kernel such as for incoming packets, outgoing packets, system calls, kprobes, uprobes, tracepoints, etc.

BPF continues to evolve and gain additional capabilities with each new Linux release. Cilium leverages BPF to perform core data path filtering, mangling, monitoring and redirection, and requires BPF capabilities that are in any Linux kernel version 4.8.0 or newer (the latest current stable Linux kernel is 4.14.x).

Many Linux distributions including CoreOS, Debian, Docker's LinuxKit, Fedora, openSUSE and Ubuntu already ship kernel versions >= 4.8.x. You can check your Linux kernel version by running uname -a. If you are not yet running a recent enough kernel, check the Documentation of your Linux distribution on how to run Linux kernel 4.9.x or later.

To read up on the necessary kernel versions to run the BPF runtime, see the section Prerequisites.

https://cdn.jsdelivr.net/gh/cilium/cilium@master/Documentation/images/bpf-overview.png

XDP is a further step in evolution and enables to run a specific flavor of BPF programs from the network driver with direct access to the packet's DMA buffer. This is, by definition, the earliest possible point in the software stack, where programs can be attached to in order to allow for a programmable, high performance packet processor in the Linux kernel networking data path.

Further information about BPF and XDP targeted for developers can be found in the BPF and XDP Reference Guide.

To know more about Cilium, it's extensions and use cases around Cilium and BPF take a look at Further Readings section.

Community

Slack

Join the Cilium Slack channel to chat with Cilium developers and other Cilium users. This is a good place to learn about Cilium, ask questions, and share your experiences.

Special Interest Groups (SIG)

See Special Interest groups for a list of all SIGs and their meeting times.

Weekly Developer meeting

  • The developer community is hanging out on zoom on a weekly basis to chat. Everybody is welcome.
  • Weekly, Wednesday, 8:00 am PT, 11:00 am ET, 5:00 pm CEST
  • Join zoom

eBPF & Cilium Office Hours livestream

We host a weekly community YouTube livestream called eCHO which (very loosely!) stands for eBPF & Cilium Office Hours. Join us live, catch up with past episodes, or head over to the eCHO repo and let us know your ideas for topics we should cover.

Governance

The Cilium project is governed by a group of Maintainers and Committers. How they are selected and govern is outlined in our governance document.

Adopters

A list of adopters of the Cilium project who are deploying it in production, and of their use cases, can be found in file USERS.md.

Roadmap

Cilium maintains a public roadmap. It gives a a high-level view of the main priorities for the project, the maturity of different features and projects, and how to influence the project direction.


Download Details:

Author: cilium
Source Code: https://github.com/cilium/cilium 
License: Apache-2.0 license

#kubernetes #security #networking #monitoring #kernel 

Cilium: eBPF-based Networking, Security, and Observability

Узнайте о 5 основных принципах безопасности API

В этом руководстве по API мы узнаем о 5 основных принципах безопасности API. Интерфейсы прикладного программирования (API) занимают центральное место в цифровой трансформации и бизнес-инновациях, позволяя компаниям создавать новые продукты и услуги для клиентов. 

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

Хотя необходимость повышения безопасности API часто обсуждается, многие организации до сих пор не уделяют этому первоочередное внимание. Возможно, вы читали о крупных игроках, таких как Tesla или Peloton, которые сталкиваются с нарушениями API. Но если бы об атаках API всех масштабов сообщалось на одном уровне, важность защиты API стала бы кристально ясной.

В этой статье я расскажу об основных аспектах безопасности API. Следуя этим основным принципам, организации и разработчики могут обеспечить безопасность своих систем и снизить риски стать объектом следующего взлома API.

1. Обязательно защитите все API

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

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

Однако важно помнить, что внутренние API могут быть столь же уязвимы, как и внешние. Эти API широко используются для доступа к ресурсам внутри системы и связывания внутренних приложений. Но сам факт того, что они расположены в пределах системного периметра, не делает их более защищенными. Поэтому рекомендуется защищать все API. Атаки могут исходить изнутри — злоумышленники могут обнаружить ваши API, когда они создаются для внутреннего использования, а затем публикуются снаружи. Кроме того, нередко внешние субъекты сначала нарушают безопасность периметра, а затем проникают глубже в инфраструктуру, поскольку внутренние службы не защищены.

2. Всегда используйте шлюз API и центральный сервер OAuth

Шлюз API — это инструмент, обеспечивающий аутентификацию и авторизацию доступа к серверным службам. Это также помогает централизовать общие функции, используемые в разных API. Шлюз может стандартизировать взаимодействие с вашими API и служить единой точкой входа. Стандартные функции шлюза API включают ограничение скорости, блокировку вредоносных клиентов, надлежащее ведение журнала, перезапись пути и заголовков, а также сбор бизнес-метрик. Без шлюза поставщики API должны были бы усиливать каждую конечную точку различными функциями одну за другой, и в случае пропуска одной из них это могло бы привести к серьезным пробелам в безопасности.

Для выполнения большинства этих функций шлюзу API требуется доказательство того, кто является вызывающим абонентом. Эта проверка обычно выполняется на основе токенов, где токен представляет конечного пользователя и включает информацию о клиентском приложении. Такие токены можно получить разными способами, но в настоящее время одним из самых популярных и безопасных способов является использование стандартов OAuth 2.0 и OpenID Connect для определения способа выпуска токенов. После того как эти токены выпущены и представлены шлюзу API, они должны быть проверены. Существуют различные шаблоны для проверки различных типов токенов, но большинство современных шлюзов API на рынке могут справиться с этим. Как минимум, срок действия токена должен быть подтвержден, и обычно проверяется, что токен выдан для правильной аудитории, путем проверки утверждения aud.

Таким образом, размещение ваших API — как общедоступных, так и внутренних — за шлюзом позволит вам повысить безопасность. Однако очень важно убедиться, что ваш API-шлюз не выдает токены. Вместо этого центральный сервер OAuth должен выдавать токены, поскольку он реализует множество сложных процессов, таких как аутентификация клиентов и пользователей, авторизация клиентов, подписание токенов и многое другое. Эти процедуры включают обработку большого количества данных и многих ключей, используемых для подписи выданных учетных данных. Такие задачи должен выполнять только сервер OAuth. Централизованное управление учетными данными и выдачей токенов позволит снизить риски, связанные с нестандартными решениями и исправлениями.

3. Используйте токены доступа с умом

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

Веб-токены JSON (или JWT) стали одним из наиболее широко используемых форматов токенов доступа, поскольку они просты в использовании и могут быть проверены самой службой. Однако, хотя использование JWT в качестве маркеров доступа и обновления считается хорошей практикой, помните, что их следует использовать только внутри. Когда токены доступны за пределами вашей инфраструктуры для сторонних клиентов, вы должны использовать непрозрачные токены вместо JWT.

Есть несколько причин, по которым непрозрачные токены считаются более безопасными, чем JWT. Во-первых, это их природа — это непрозрачные строки, не имеющие никакого значения для клиента. Когда он получает непрозрачный токен, он должен позвонить эмитенту, чтобы проверить токен и получить данные. С другой стороны, при использовании JWT получатель не обязан звонить эмитенту, поэтому отозвать JWT невозможно. Также весьма вероятно, что JWT содержит некоторую личную информацию (PII), которую само приложение не должно использовать и предназначено для API, поэтому JWT больше подходят для внутреннего использования.

Вот некоторые другие рекомендации по обработке токенов:

  • Всегда проверяйте входящие JWT.
  • Создавайте или повторно используйте библиотеки для проверки JWT.
  • Не используйте JWT для обработки сеансов.
  • Используйте непрозрачные токены для внешних или общедоступных клиентов.

Правильное использование токенов является неотъемлемой частью безопасности вашего API. Следуйте рекомендациям, созданным профессионалами в области безопасности.

4. Ограничьте доверие к входящему трафику

Рассмотрите возможность применения подхода нулевого доверия к вашим API. Создание архитектуры с нулевым доверием означает создание системы, в которой никому не доверяют, а любой пользователь или служба, получающие доступ к данным, всегда проверяются. Архитектура с нулевым доверием — это не отдельная архитектура сама по себе — это набор рекомендаций по проектированию систем и операций, направленных на усиление безопасности для защиты активов предприятия.

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

Ограничение доверия к входящему трафику может быть выполнено с помощью HTTPS (даже внутри) и проверки всех входящих JWT, даже тех, которые были преобразованы из непрозрачного токена шлюзом. Это предотвратит действия злоумышленников внутри вашей инфраструктуры.

5. Всегда тестируйте, контролируйте и проверяйте

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

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

Заключение

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

Не забывайте защищать как внешние, так и внутренние API, использовать шлюзы API, использовать центральный сервер OAuth, регулярно проверять входящий трафик и постоянно проверять свою систему. Существует множество технических стратегий, которые следует учитывать при управлении аутентификацией и авторизацией API. Следование рекомендациям поможет защитить API и предотвратить нежелательное поведение.

Оригинальный источник статьи: https://nordicapis.com

#api #security 

Узнайте о 5 основных принципах безопасности API
Rui  Silva

Rui Silva

1678997880

Aprenda sobre os 5 princípios essenciais da segurança da API

Neste tutorial de API, aprenderemos sobre 5 princípios essenciais de segurança de API. As Interfaces de Programação de Aplicativos (APIs) são fundamentais para a transformação digital e inovação de negócios, permitindo que as empresas criem novos produtos e serviços para os clientes. 

Mas, como acontece com todas as coisas boas, também existem desafios. As APIs são ótimos conectores, mas essas conexões apresentam certos riscos. Raramente passa uma semana sem notícias sobre outro ataque à API. Infelizmente, isso não pode mais ser visto apenas como um aviso. Como as violações de API podem levar a consequências perigosas, elas definitivamente não devem ser negligenciadas. A segurança da API deve ser uma prioridade para qualquer pessoa que esteja desenvolvendo APIs ou integrando-as em aplicativos.

Embora a necessidade de melhorar a segurança da API seja frequentemente discutida, muitas organizações ainda falham em priorizá-la. Você pode ter lido sobre grandes players como Tesla ou Peloton passando por violações de API. Mas se os ataques de API de todas as escalas fossem relatados no mesmo nível, a importância de proteger as APIs ficaria clara.

Neste artigo, destacarei as principais considerações para a segurança da API. Ao seguir esses princípios básicos, organizações e desenvolvedores podem garantir a segurança de seus sistemas e reduzir os riscos de se tornarem alvo da próxima violação de API.

1. Certifique-se de proteger todas as APIs

As APIs podem ser divididas em duas categorias: APIs externas e internas. A julgar pelos nomes, pode parecer que os externos devem ser mais protegidos do que os internos – assim como as portas de sua casa exigem fechaduras seguras. No entanto, quando se trata de segurança da API, realmente não importa se a API está exposta ao ambiente externo ou não. Deve ser sempre protegido. Isso se alinha com uma arquitetura de confiança zero em que a mudança de um perímetro baseado em rede para um perímetro baseado em identidade exige que todo o acesso a uma API seja verificado.

APIs externas que integram aplicativos com recursos de terceiros podem parecer mais propensas a ataques. A falha na configuração da autenticação e autorização pode fazer com que agentes terceirizados obtenham acesso aos dados internos. Embora esses dados possam não ser muito confidenciais, as informações vazadas podem ser usadas para aprofundar a violação e lançar um ataque de phishing para obter dados muito mais críticos do usuário e do sistema.

No entanto, é crucial lembrar que as APIs internas podem ser tão vulneráveis ​​quanto as externas. Essas APIs são amplamente utilizadas para acessar recursos dentro do sistema e vincular aplicações internas. Mas o simples fato de estarem posicionados dentro do perímetro do sistema não os torna mais protegidos. Portanto, a recomendação é proteger todas as APIs. Os ataques podem vir de dentro — os invasores podem descobrir suas APIs quando criadas para uso interno e depois publicadas externamente. Além disso, não é incomum que atores externos primeiro violem a segurança do perímetro e depois penetrem mais profundamente na infraestrutura porque os serviços internos estão desprotegidos.

2. Sempre use um gateway de API e um servidor OAuth central

Um gateway de API é uma ferramenta que garante que o acesso aos serviços de back-end seja autenticado e autorizado. Também ajuda a centralizar recursos comuns usados ​​em APIs. O gateway pode padronizar as interações com suas APIs e servir como um único ponto de entrada. Os recursos de gateway de API padrão incluem limitação de taxa, bloqueio de clientes mal-intencionados, registro adequado, reescrita de caminhos e cabeçalhos e coleta de métricas de negócios. Sem um gateway, os provedores de API teriam que reforçar cada endpoint com vários recursos um por um e, caso um fosse perdido, isso poderia levar a sérias falhas de segurança.

Para atender a maioria desses recursos, o gateway de API precisa de prova de quem é o chamador. Essa verificação geralmente é tratada de maneira baseada em token, em que o token representa o usuário final e inclui informações sobre o aplicativo cliente. Esses tokens podem ser obtidos de diferentes maneiras, mas atualmente um dos métodos mais populares e seguros é usar os padrões OAuth 2.0 e OpenID Connect para definir como os tokens são emitidos. Depois que esses tokens são emitidos e apresentados ao gateway da API, eles devem ser validados. Existem vários padrões para validar diferentes tipos de token, mas os gateways de API mais modernos do mercado podem lidar com isso. No mínimo, a expiração do token deve ser validada e também é comum verificar se o token foi emitido para o público correto validando a auddeclaração.

Em resumo, colocar suas APIs — públicas e internas — atrás de um gateway permitirá aumentar a segurança. No entanto, é vital garantir que seu gateway de API não emita tokens. Em vez disso, um servidor OAuth central deve emitir tokens, pois implementa muitos processos complexos, como autenticação de cliente e usuário, autorização de cliente, assinatura de token e muito mais. Esses procedimentos envolvem o manuseio de muitos dados e muitas chaves usadas para assinar as credenciais emitidas. Essas tarefas devem ser executadas apenas pelo servidor OAuth. Centralizar o gerenciamento de credenciais e a emissão de tokens permitirá mitigar os riscos associados a soluções e patches ad hoc.

3. Use tokens de acesso com sabedoria

Uma arquitetura moderna baseada em token é ótima para proteger APIs. Os tokens ajudam a estabelecer confiança e garantem que as APIs tenham informações suficientes para tomar decisões de acesso adequadas. No entanto, para colher todos os benefícios e proteger seu sistema, é de extrema importância usar cada tipo de token diferente corretamente.

Os JSON Web Tokens (ou JWTs) se tornaram um dos formatos mais utilizados para tokens de acesso, pois são fáceis de usar e podem ser validados pelo próprio serviço. No entanto, embora o uso de JWTs como tokens de acesso e atualização seja considerado uma boa prática, lembre-se de que eles devem ser usados ​​apenas internamente. Quando os tokens são expostos fora de sua infraestrutura para clientes de terceiros, você deve usar tokens opacos em vez de JWTs.

Existem algumas razões pelas quais os tokens opacos são considerados mais seguros do que os JWTs. Em primeiro lugar está a sua natureza - são strings opacas que não têm nenhum significado para o cliente. Ao receber um token opaco, deve chamar o emissor para verificar o token e obter os dados. Por outro lado, quando JWTs são usados, o receptor não é obrigado a ligar para o emissor, portanto, é impossível revogar um JWT. Também é altamente provável que um JWT contenha algumas informações de identificação pessoal (PII) que o próprio aplicativo não deva consumir e se destine à API, por isso os JWTs são mais apropriados para uso interno.

Algumas outras práticas recomendadas de manipulação de tokens a serem seguidas são:

  • Sempre verifique os JWTs recebidos.
  • Crie ou reutilize bibliotecas para validação de JWT.
  • Não use JWTs para manipulação de sessão.
  • Use tokens opacos para clientes externos ou públicos.

O uso adequado de tokens é parte integrante da segurança de sua API. Siga as melhores práticas criadas por profissionais de segurança.

4. Limite a confiança no tráfego de entrada

Considere aplicar uma abordagem de confiança zero às suas APIs. Estabelecer uma arquitetura de confiança zero significa criar um sistema em que ninguém é confiável e qualquer usuário ou serviço acessando dados é sempre verificado. Uma arquitetura de confiança zero não é uma arquitetura única em si — é um conjunto de diretrizes para projetar sistemas e operações que visam aumentar a segurança para proteger os ativos corporativos.

A autenticação é crítica para qualquer implementação bem-sucedida de uma arquitetura de confiança zero. Por exemplo, é vital determinar se o usuário é interno, a que parte da organização ele pertence, qual serviço está solicitando informações de outro serviço e qual serviço de terceiros está solicitando acesso a um serviço corporativo interno.

Limitar a confiança no tráfego de entrada pode ser feito usando HTTPS (mesmo internamente) e verificando todos os JWTs de entrada, mesmo aqueles transformados de um token opaco pelo gateway. Isso impedirá que agentes mal-intencionados operem dentro de sua infraestrutura.

5. Sempre teste, monitore e audite

Para tornar suas APIs e todo o sistema realmente eficazes contra ameaças de segurança, é essencial testar e monitorar continuamente quais APIs ou endpoints representam um risco. As vulnerabilidades devem ser identificadas na fase inicial para que a sua correção seja relativamente fácil e rápida.

A configuração de medidas de segurança destinadas a proteger suas APIs deve ser seguida pelo estabelecimento de governança sobre elas. É sempre uma boa ideia ter uma equipe dedicada de especialistas monitorando e auditando ativamente seu sistema de segurança de API. Essas pessoas devem coletar métricas, registrar o uso da API e verificar solicitações inesperadas ou comportamento incomum do cliente. Isso permitirá que você detecte uma violação antes que ela prejudique seu sistema, mantendo os ativos de sua organização e os dados do usuário seguros.

Conclusão

Como as APIs continuam a crescer em importância, manter a segurança de API de alto padrão é uma preocupação primordial. Como tal, é essencial manter as APIs e os dados que fluem por elas seguros e acessíveis apenas ao usuário pretendido. Isso não é algo para esperar - se você ainda não o fez, precisa começar agora.

Lembre-se de proteger APIs externas e internas, aproveitar gateways de API, usar um servidor OAuth central, verificar regularmente o tráfego de entrada e auditar continuamente seu sistema. Há muitas estratégias técnicas a serem consideradas ao gerenciar autenticação e autorização de API. Seguir as práticas recomendadas pode ajudá-lo a proteger as APIs e evitar comportamentos indesejados.

Fonte do artigo original em: https://nordicapis.com

#api #security 

Aprenda sobre os 5 princípios essenciais da segurança da API
Phung Dang

Phung Dang

1678990140

Tìm hiểu về 5 nguyên tắc cơ bản của bảo mật API

Trong hướng dẫn API này, chúng ta sẽ tìm hiểu về 5 nguyên tắc cơ bản của bảo mật API. Giao diện lập trình ứng dụng (API) là trung tâm của quá trình chuyển đổi kỹ thuật số và đổi mới kinh doanh, cho phép các công ty tạo ra các sản phẩm và dịch vụ mới cho khách hàng. 

Nhưng như với mọi điều tốt đẹp, cũng có những thách thức. API là trình kết nối tuyệt vời, nhưng những kết nối này tiềm ẩn những rủi ro nhất định. Hiếm khi một tuần trôi qua mà không có tin tức về một cuộc tấn công API khác. Thật không may, điều này không thể được xem như một lời cảnh báo nữa. Vì vi phạm API có thể dẫn đến những hậu quả nguy hiểm, nên chắc chắn không nên bỏ qua chúng. Bảo mật API phải là ưu tiên hàng đầu đối với bất kỳ ai đang phát triển API hoặc tích hợp chúng vào các ứng dụng.

Mặc dù nhu cầu cải thiện bảo mật API thường được thảo luận, nhiều tổ chức vẫn không ưu tiên nó. Bạn có thể đã đọc về những người chơi lớn như Tesla hoặc Peloton đã vi phạm API. Nhưng nếu các cuộc tấn công API ở mọi quy mô được báo cáo ở cùng cấp độ, thì tầm quan trọng của việc bảo vệ API sẽ trở nên rõ ràng.

Trong bài viết này, tôi sẽ nêu bật những điểm cần cân nhắc chính đối với bảo mật API. Bằng cách tuân theo các nguyên tắc cốt lõi này, các tổ chức và nhà phát triển có thể đảm bảo an toàn cho hệ thống của họ và giảm thiểu rủi ro trở thành đối tượng của vi phạm API tiếp theo.

1. Đảm bảo bảo vệ tất cả các API

API có thể được chia thành hai loại: API bên ngoài và bên trong. Đánh giá theo tên gọi, có vẻ như những cái bên ngoài nên được bảo vệ tốt hơn những cái bên trong — giống như cửa nhà bạn cần có khóa an toàn. Tuy nhiên, khi nói đến bảo mật API, việc API có tiếp xúc với môi trường bên ngoài hay không thực sự không quan trọng. Nó phải luôn luôn được bảo vệ. Điều này phù hợp với kiến ​​trúc không tin cậy trong đó việc chuyển từ vành đai dựa trên mạng sang vành đai dựa trên danh tính yêu cầu tất cả quyền truy cập vào API phải được xác minh.

API bên ngoài tích hợp ứng dụng với tài nguyên của bên thứ ba có vẻ dễ bị tấn công hơn. Việc không thiết lập xác thực và ủy quyền có thể dẫn đến việc các tác nhân bên thứ ba có quyền truy cập vào dữ liệu nội bộ. Mặc dù dữ liệu này có thể không quá nhạy cảm, nhưng thông tin bị rò rỉ có thể được sử dụng để làm sâu thêm lỗ hổng và khởi động một cuộc tấn công lừa đảo để lấy dữ liệu hệ thống và người dùng quan trọng hơn nhiều.

Tuy nhiên, điều quan trọng cần nhớ là các API nội bộ có thể dễ bị tấn công như các API bên ngoài. Các API này được sử dụng rộng rãi để truy cập tài nguyên bên trong hệ thống và liên kết các ứng dụng nội bộ. Nhưng thực tế là chúng được định vị trong vành đai hệ thống không làm cho chúng được bảo vệ tốt hơn. Do đó, khuyến nghị là bảo vệ tất cả các API. Các cuộc tấn công có thể đến từ bên trong — những kẻ tấn công có thể phát hiện ra các API của bạn khi được tạo để sử dụng nội bộ và sau đó xuất bản ra bên ngoài. Ngoài ra, không có gì lạ khi các tác nhân bên ngoài lần đầu tiên vi phạm vành đai bảo mật và sau đó xâm nhập sâu hơn vào cơ sở hạ tầng vì các dịch vụ nội bộ không được bảo vệ.

2. Luôn sử dụng Cổng API và Máy chủ OAuth trung tâm

Cổng API là một công cụ đảm bảo rằng quyền truy cập vào các dịch vụ phụ trợ được xác thực và ủy quyền. Nó cũng giúp tập trung các tính năng phổ biến được sử dụng trên các API. Cổng có thể chuẩn hóa các tương tác với API của bạn và đóng vai trò là một điểm vào duy nhất. Các tính năng cổng API tiêu chuẩn bao gồm giới hạn tốc độ, chặn ứng dụng khách độc hại, ghi nhật ký thích hợp, viết lại đường dẫn và tiêu đề cũng như thu thập số liệu kinh doanh. Nếu không có cổng, các nhà cung cấp API sẽ phải củng cố từng điểm cuối bằng nhiều tính năng khác nhau và trong trường hợp bỏ sót một điểm, điều đó có thể dẫn đến lỗ hổng bảo mật nghiêm trọng.

Để đáp ứng hầu hết các tính năng này, cổng API cần có bằng chứng về người gọi là ai. Việc xác minh này thường được xử lý theo cách dựa trên mã thông báo trong đó mã thông báo đại diện cho người dùng cuối và bao gồm thông tin về ứng dụng khách. Có thể nhận được các mã thông báo như vậy theo nhiều cách khác nhau, nhưng hiện tại, một trong những phương pháp phổ biến và an toàn nhất là sử dụng các tiêu chuẩn OAuth 2.0 và OpenID Connect để xác định cách phát hành mã thông báo. Sau khi các mã thông báo này được phát hành và hiển thị tới cổng API, chúng phải được xác thực. Có nhiều mẫu khác nhau để xác thực các loại mã thông báo khác nhau, nhưng hầu hết các cổng API hiện đại trên thị trường đều có thể xử lý việc này. Ở mức tối thiểu, thời hạn hết hạn của mã thông báo phải được xác thực và thông thường cũng phải kiểm tra xem mã thông báo có được phát hành cho đúng đối tượng hay không bằng cách xác thực yêu cầu aud.

Tóm lại, việc đặt API của bạn — cả công khai và nội bộ — phía sau cổng sẽ cho phép bạn tăng cường bảo mật. Tuy nhiên, điều quan trọng là đảm bảo rằng cổng API của bạn không phát hành mã thông báo. Thay vào đó, máy chủ OAuth trung tâm sẽ phát hành mã thông báo vì nó thực hiện nhiều quy trình phức tạp như xác thực ứng dụng khách và người dùng, ủy quyền ứng dụng khách, ký mã thông báo, v.v. Các thủ tục này liên quan đến việc xử lý nhiều dữ liệu và nhiều khóa được sử dụng để ký các thông tin xác thực đã cấp. Các tác vụ như vậy chỉ nên được thực hiện bởi máy chủ OAuth. Tập trung hóa việc quản lý thông tin đăng nhập và phát hành mã thông báo sẽ cho phép bạn giảm thiểu rủi ro liên quan đến các giải pháp và bản vá đặc biệt.

3. Sử dụng mã thông báo truy cập một cách khôn ngoan

Kiến trúc dựa trên mã thông báo hiện đại rất phù hợp để bảo vệ các API. Mã thông báo giúp thiết lập niềm tin và đảm bảo API có đủ thông tin để đưa ra quyết định truy cập phù hợp. Tuy nhiên, để gặt hái đầy đủ lợi ích và bảo mật hệ thống của bạn, điều quan trọng nhất là phải sử dụng đúng từng loại mã thông báo khác nhau.

Mã thông báo web JSON (hoặc JWT) đã trở thành một trong những định dạng mã thông báo truy cập được sử dụng rộng rãi nhất vì chúng dễ sử dụng và có thể được chính dịch vụ xác thực. Tuy nhiên, trong khi sử dụng JWT làm mã thông báo truy cập và làm mới được coi là thông lệ tốt, hãy nhớ rằng chúng chỉ nên được sử dụng nội bộ. Khi mã thông báo được hiển thị bên ngoài cơ sở hạ tầng của bạn cho khách hàng bên thứ ba, bạn nên sử dụng mã thông báo mờ thay vì JWT.

Có một vài lý do tại sao mã thông báo mờ được coi là an toàn hơn JWT. Thứ nhất là bản chất của chúng — chúng là những chuỗi không rõ ràng không có bất kỳ ý nghĩa nào đối với khách hàng. Khi nhận được mã thông báo mờ, nó phải gọi cho nhà phát hành để xác minh mã thông báo và lấy dữ liệu. Mặt khác, khi JWT được sử dụng, người nhận không bắt buộc phải gọi cho nhà phát hành, do đó không thể thu hồi JWT. Cũng có khả năng cao là JWT chứa một số thông tin nhận dạng cá nhân (PII) mà bản thân ứng dụng không nên sử dụng và được dành cho API, do đó tại sao JWT phù hợp hơn để sử dụng nội bộ.

Một số phương pháp hay nhất về xử lý mã thông báo khác cần tuân theo là:

  • Luôn xác minh JWT đến.
  • Tạo hoặc sử dụng lại các thư viện để xác thực JWT.
  • Không sử dụng JWT để xử lý phiên.
  • Sử dụng mã thông báo mờ cho khách hàng bên ngoài hoặc công khai.

Việc sử dụng mã thông báo đúng cách là một phần không thể thiếu trong bảo mật API của bạn. Thực hiện theo các phương pháp hay nhất do các chuyên gia bảo mật tạo ra.

4. Giới hạn niềm tin đối với lưu lượng truy cập đến

Cân nhắc áp dụng phương pháp không tin cậy cho các API của bạn. Thiết lập kiến ​​trúc không tin cậy có nghĩa là tạo ra một hệ thống không ai đáng tin cậy và mọi người dùng hoặc dịch vụ truy cập dữ liệu luôn được xác minh. Bản thân kiến ​​trúc không tin cậy không phải là một kiến ​​trúc đơn lẻ — nó là một tập hợp các hướng dẫn để thiết kế các hệ thống và hoạt động nhằm thắt chặt an ninh để bảo vệ tài sản của doanh nghiệp.

Xác thực là rất quan trọng đối với bất kỳ triển khai thành công nào của kiến ​​trúc không tin cậy. Ví dụ: điều quan trọng là phải xác định xem người dùng có phải là nội bộ hay không, người dùng thuộc về bộ phận nào của tổ chức, dịch vụ nào đang yêu cầu thông tin từ dịch vụ khác và dịch vụ bên thứ ba nào đang yêu cầu quyền truy cập vào dịch vụ nội bộ của công ty.

Việc giới hạn độ tin cậy đối với lưu lượng truy cập đến có thể được thực hiện bằng cách sử dụng HTTPS (thậm chí trong nội bộ) và xác minh tất cả các JWT đến, ngay cả những JWT được cổng chuyển đổi từ mã thông báo mờ. Điều này sẽ ngăn chặn các tác nhân độc hại hoạt động bên trong cơ sở hạ tầng của bạn.

5. Luôn Kiểm tra, Giám sát và Kiểm toán

Để làm cho API của bạn và toàn bộ hệ thống thực sự hiệu quả trước các mối đe dọa bảo mật, điều cần thiết là phải liên tục kiểm tra và giám sát API hoặc điểm cuối nào gây rủi ro. Các lỗ hổng phải được xác định trong giai đoạn ban đầu để việc sửa chữa chúng có thể tương đối dễ dàng và nhanh chóng.

Việc thiết lập các biện pháp bảo mật nhằm bảo vệ API của bạn nên được tuân theo bằng cách thiết lập quyền quản trị đối với chúng. Luôn luôn là một ý tưởng hay khi có một nhóm chuyên gia tận tâm chủ động giám sát và kiểm tra hệ thống bảo mật API của bạn. Những người này nên thu thập số liệu, ghi nhật ký sử dụng API và kiểm tra các yêu cầu không mong muốn hoặc hành vi bất thường của khách hàng. Điều này sẽ cho phép bạn phát hiện vi phạm trước khi nó gây hại cho hệ thống của bạn, giữ an toàn cho tài sản của tổ chức và dữ liệu người dùng.

Phần kết luận

Khi các API tiếp tục phát triển về tầm quan trọng, việc duy trì bảo mật API tiêu chuẩn cao là mối quan tâm hàng đầu. Do đó, việc giữ cho API và dữ liệu truyền qua chúng an toàn và chỉ người dùng dự định mới có thể truy cập được là điều bắt buộc. Đây không phải là thứ để chờ đợi — nếu bạn chưa làm, bạn cần phải bắt đầu ngay bây giờ.

Hãy nhớ bảo vệ cả API bên ngoài và bên trong, tận dụng cổng API, sử dụng máy chủ OAuth trung tâm, thường xuyên xác minh lưu lượng truy cập đến và liên tục kiểm tra hệ thống của bạn. Có nhiều chiến lược kỹ thuật cần xem xét khi quản lý xác thực và ủy quyền API. Làm theo các phương pháp hay nhất có thể giúp bạn bảo vệ API và ngăn chặn hành vi không mong muốn.

Nguồn bài viết gốc tại: https://nordicapis.com

#api #security 

Tìm hiểu về 5 nguyên tắc cơ bản của bảo mật API

Learn About The 5 Essential Principles Of API Security

In this API tutorial, we will learn about 5 essential principles of API security. Application Programming Interfaces (APIs) are central to digital transformation and business innovation, allowing companies to create new products and services for customers. 

But as with every good thing, there are also challenges. APIs are great connectors, but these connections pose certain risks. Rarely a week passes without news about another API attack. Unfortunately, this cannot be viewed as just a warning anymore. Since API breaches can lead to dangerous consequences, they definitely should not be overlooked. API security should be a priority for anyone developing APIs or integrating them into applications.

Although the need to improve API security is often discussed, many organizations still fail to prioritize it. You may have read about big players like Tesla or Peloton going through API breaches. But if API attacks of all scales were reported on the same level, the importance of protecting APIs would become crystal clear.

In this article, I will highlight the key considerations for API security. By following these core principles, organizations and developers can ensure the safety of their systems and mitigate the risks of becoming the subject of the next API breach.

1. Make Sure to Protect All APIs

APIs can be divided into two categories: external and internal APIs. Judging by the names, it may seem that the external ones should be protected better than internal ones — just like the doors to your house require secure locks. However, when it comes to API security, it really does not matter whether the API is exposed to the external environment or not. It should always be protected. This aligns with a zero-trust architecture where the shift from a network-based perimeter to an identity-based perimeter requires all access to an API to be verified.

External APIs that integrate applications with third-party resources may seem more prone to attacks. Failure to set up authentication and authorization can lead to third-party agents gaining access to internal data. Though this data might not be too sensitive, the leaked information could be used to deepen the breach and launch a phishing attack to get ahold of much more critical user and system data.

However, it is crucial to remember that internal APIs can be as vulnerable as external ones. These APIs are widely used to access resources within the system and link internal applications. But the mere fact that they are positioned within the system perimeter doesn’t make them more protected. Therefore, the recommendation is to protect all APIs. Attacks might come from inside — attackers might discover your APIs when created for internal use and then published externally. Also, it is not uncommon for external actors to first breach the perimeter security and then penetrate deeper into the infrastructure because internal services are unprotected.

2. Always Use an API Gateway and a Central OAuth Server

An API gateway is a tool that ensures that access to backend services is authenticated and authorized. It also helps centralize common features used across APIs. The gateway can standardize interactions with your APIs and serve as a single entry point. Standard API gateway features include rate limiting, blocking malicious clients, proper logging, path and headers rewriting, and gathering business metrics. Without a gateway, API providers would have to reinforce each endpoint with various features one by one, and in case one is missed, it could lead to serious security gaps.

To fulfill most of these features, the API gateway needs proof of who the caller is. This verification is commonly handled in a token-based manner where the token represents the end user and includes information about the client application. Such tokens can be obtained in different ways, but currently, one of the most popular and secure methods is to use OAuth 2.0 and OpenID Connect standards to define how tokens are issued. Once these tokens are issued and presented to the API gateway, they must be validated. There are various patterns for validating different token types, but most modern API gateways in the market can handle this. At a minimum, the token’s expiration should be validated, and it is also typical to check that the token is issued for the correct audience by validating the aud claim.

In summary, placing your APIs — both public and internal — behind a gateway will allow you to increase security. However, it is vital to ensure that your API gateway does not issue tokens. Instead, a central OAuth server should issue tokens since it implements many complex processes like client and user authentication, client authorization, token signing, and more. These procedures involve handling a lot of data and many keys used to sign the issued credentials. Such tasks should only be performed by the OAuth server. Centralizing the management of credentials and token issuance will allow you to mitigate the risks associated with ad hoc solutions and patches.

3. Use Access Tokens Wisely

A modern token-based architecture is great for protecting APIs. Tokens help establish trust and ensure APIs have enough information to make proper access decisions. However, to fully reap the benefits and secure your system, it is of the utmost importance to use each different token type correctly.

JSON Web Tokens (or JWTs) has become one of the most widely used formats for access tokens as they are easy to use and can be validated by the service itself. However, while using JWTs as access and refresh tokens is considered good practice, remember that they should only be used internally. When tokens are exposed outside of your infrastructure to third-party clients, you should use opaque tokens instead of JWTs.

There are a few reasons why opaque tokens are considered more secure than JWTs. Firstly is their nature — they are opaque strings that do not have any meaning to the client. When it receives an opaque token, it must call the issuer to verify the token and get the data. On the other hand, when JWTs are used, the receiver is not required to call the issuer, so it is impossible to revoke a JWT. It is also highly likely that a JWT contains some personally identifiable information (PII) that the application itself should not consume and is intended for the API, hence why JWTs are more appropriate for internal use.

Some other token-handling best practices to follow are:

  • Always verify incoming JWTs.
  • Create or reuse libraries for JWT validation.
  • Don’t use JWTs for session handling.
  • Use opaque tokens for external or public clients.

Proper usage of tokens is an integral part of your API security. Follow the best practices created by security professionals.

4. Limit Trust on Incoming Traffic

Consider applying a zero-trust approach to your APIs. Establishing a zero-trust architecture means creating a system where no one is trusted and any user or service accessing data is always verified. A zero-trust architecture is not a single architecture in itself — it is a set of guidelines for designing systems and operations that intend to tighten the security to protect enterprise assets.

Authentication is critical to any successful implementation of a zero-trust architecture. For example, it is vital to determine whether the user is internal, what part of the organization the user belongs to, what service is requesting information from another service, and what third-party service is requesting access to an internal corporate service.

Limiting trust on incoming traffic can be done by using HTTPS (even internally) and verifying all incoming JWTs, even those transformed from an opaque token by the gateway. This will prevent malicious actors from operating inside your infrastructure.

5. Always Test, Monitor, and Audit

To make your APIs and the whole system really effective against security threats, it is essential to continuously test and monitor which APIs or endpoints pose a risk. The vulnerabilities must be identified in the initial phase so that correcting them can be relatively easy and quick.

Setting up security measures aimed to protect your APIs should be followed by establishing governance over them. It is always a good idea to have a dedicated team of experts actively monitoring and auditing your API security system. These people should gather metrics, log API usage, and check unexpected requests or unusual client behavior. This will allow you to catch a breach before it harms your system, keeping your organization’s assets and user data safe.

Conclusion

As APIs continue to grow in importance, maintaining high-standard API security is a paramount concern. As such, keeping APIs and the data flowing through them safe and only accessible to the intended user is a must. This is not something to wait on — if you haven’t already, you need to get on it now.

Remember to protect both external and internal APIs, leverage API gateways, use a central OAuth server, regularly verify incoming traffic, and continuously audit your system. There are many technical strategies to consider when managing API authentication and authorization. Following the best practices can help you safeguard APIs and thwart unwanted behavior.

Original article source at: https://nordicapis.com

#api #security 

Learn About The 5 Essential Principles Of API Security
戈 惠鈺

戈 惠鈺

1678813920

探索 API 安全的 5 大基础

在本文中,我们将了解 API 安全的 5 个基础知识。 

应用程序编程接口 (API) 是数字化转型和业务创新的核心,使公司能够为客户创造新产品和服务。但是,就像所有美好的事物一样,也有困难。API 是很好的连接器,但这些连接会带来一定的风险。很少有一周没有另一次 API 攻击的消息。不幸的是,这不能再被视为警告。由于 API 违规会产生危险的后果,因此当然不能忽视它们。API 安全应该是任何开发 API 或将它们集成到应用程序中的人的首要任务。


尽管经常讨论提高 API 安全性的必要性,但许多组织仍未将其视为优先事项。您可能已经读过有关像 Tesla 或 Peloton 这样的大公司破坏 API 的信息。但是,当各种规模的 API 攻击都在同一级别上报时,保护 API 的重要性就变得显而易见了。

在本文中,我将介绍 API 安全性的关键方面。通过遵循这些基本原则,组织和开发人员可以保护他们的系统并降低下一次 API 黑客攻击的风险。

1. 保证所有API的保护

API可以分为两类:外部API和内部API。顾名思义,外面应该比里面更安全,就像你的门需要安全锁一样。但是,涉及到 API 安全时,API 是否对外公开并不重要。它必须始终受到保护。这适用于非信任架构,在这种架构中,从网络边界转移到基于身份的边界需要验证所有 API 访问权限。

将应用程序与第三方资源集成的外部 API 似乎更容易受到攻击。未设置身份验证和授权可能导致第三方访问内部数据。虽然这些数据可能不是很敏感,但信息泄露可以用来加深漏洞并发起网络钓鱼攻击,以获得更敏感的用户和系统数据。

但是,请务必记住,内部 API 可能与外部 API 一样容易受到攻击。这些 API 广泛用于访问系统内的资源以及与内部应用程序通信。但它们位于系统边界内的事实并不能使它们更安全。因此,建议保护所有 API。攻击可能来自内部 - 攻击者可以在构建供内部使用的 API 时发现它们,然后将它们发布到外部。此外,由于内部服务未受到保护,外部参与者先突破安全边界然后深入基础设施的情况并不少见。

2. 始终使用 API 网关和 OAuth 中央服务器。

API 网关是一种为访问后端服务提供身份验证和授权的工具。它还有助于集中 API 中使用的共享资源。网关可以标准化与您的 API 的交互,并充当单一入口点。标准 API 网关功能包括速率限制、恶意客户端阻止、正确的日志记录、路径和标头重写以及业务指标收集。如果没有网关,API 提供商将不得不使用不同的资源来强化每个端点,而丢失一个端点可能会导致严重的安全漏洞。

为了实现其中的大部分功能,API 网关需要证明调用者是谁。此验证通常基于令牌进行,其中令牌代表最终用户并包含有关客户端应用程序的信息。这些令牌可以通过多种方式获得,但目前最常见和最安全的方法之一是使用 OAuth 2.0 和 OpenID Connect 标准来确定如何颁发令牌。一旦颁发了这些令牌并授予对 API 网关的访问权限,就必须对其进行验证。验证不同类型的令牌有不同的模型,但市场上大多数现代 API 网关都可以处理这个问题。至少_

简而言之,将您的 API(公共的和内部的)放在门户后面可以提高安全性。但是,确保您的 API 网关不会颁发令牌很重要。相反,中央 OAuth 服务器将颁发令牌,因为它执行许多复杂的过程,例如客户端和用户身份验证、客户端授权、令牌签名等,涉及处理大量数据和用于签署颁发的凭据的多个密钥。这些任务只能由 OAuth 服务器执行。凭证的集中管理和令牌的发行将降低与特殊解决方案和补丁相关的风险。

3. 明智地使用访问令牌

基于令牌的现代架构非常适合保护 API。令牌有助于建立信任并确保 API 具有足够的信息来做出适当的访问决策。但是,为了获得全部好处并保护您的系统,您必须正确使用每种不同类型的令牌。

JSON(或 JWT)网络令牌已成为使用最广泛的访问令牌格式之一,因为它们易于使用并且可以由服务本身进行身份验证。然而,虽然使用 JWT 作为访问和刷新令牌被认为是一种好的做法,但请记住它们应该只在内部使用。当令牌在您的基础架构之外可供第三方客户端使用时,您应该使用不透明令牌而不是 JWT。

不透明令牌被认为比 JWT 更安全的原因有很多。首先,这是它们的本性——这些是对客户没有意义的模棱两可的字符串。收到模糊令牌后,它必须调用发送方来验证令牌并检索数据。另一方面,当使用 JWT 时,接收方不需要调用发送方,因此 JWT 不能被撤销。JWT 也很有可能包含一些个人身份信息 (PII),这些信息不应由应用程序本身使用,而是用于 API,因此 JWT 更适合内部使用。

以下是处理令牌的一些其他准则:

  • 始终验证收到的 JWT。
  • 创建或重用用于 JWT 验证的库。
  • 不要使用 JWT 进行会话处理。
  • 为外部或公共客户使用不透明的令牌。

正确使用令牌是保护 API 的重要组成部分。遵循安全专家创建的最佳实践。

4.限制对传入流量的信任

考虑一种不可靠的 API 方法。建立一个无需信任的架构意味着创建一个系统,在这个系统中,任何人都不可信任,并且始终验证每个用户或访问数据的服务。无信任架构本身并不是一个单一的架构;它是一套用于设计系统和操作的指南,这些指南提供了保护企业资产的安全性

身份验证对于成功实施无信任架构至关重要。例如,重要的是要确定用户是否是内部用户、用户属于组织的哪个部分、哪个服务正在向另一个请求信息,以及哪些第三方服务正在请求访问公司内部服务。

传入流量的隐私限制可以使用 HTTPS(甚至在内部)来完成,并验证所有传入的 JWT,即使是那些被网关标记化的 JWT。这将防止基础设施中的恶意活动。

5.经常检查检查再检查

为了让您的 API 和整个系统真正有效地抵御安全威胁,不断测试和监控哪些 API 或端点构成风险非常重要。应在早期识别漏洞,以便消除它们相对简单和快速。

设置安全措施以保护您的 API 必须同时设置对它们的管理权限。有专门的专家组积极监控和测试 API 的安全性总是好的。这些人应该收集指标、记录 API 使用情况,并检查意外请求或异常客户端行为。这将使您能够在漏洞损坏您的系统之前检测到漏洞,从而保护您组织的资产和用户数据的安全。

结论

随着 API 的重要性不断增长,保持高标准的 API 安全成为当务之急。因此,API 和通过它们的数据必须是安全的,并且只能供其目标用户访问。这不是一件值得期待的事情——如果你还没有,你需要现在就开始。

不要忘记保护外部和内部 API、使用 API 网关、使用中央 OAuth 服务器、定期扫描传入流量并不断测试您的系统。在管理 API 授权和身份验证时,需要考虑许多技术策略。遵循最佳实践将帮助您保护 API 并避免意外行为。

资料来源: https: //nordicapis.com

#api #security 

探索 API 安全的 5 大基础
Corey Brooks

Corey Brooks

1678758870

JSON Web Token (JWT): Authorization and Authentication

Learn about JSON Web Token (JWT) and how things are going to work during the authentication and authorization process.

In this article, we will discuss authentication and authorization using the JWT token and different cryptographic algorithms and techniques. So, we will be looking at the following things one by one:

  • Introduction of JWT Token
  • Why JWT Token?
  • Structure of JWT Token
  • Client-Server Scenario With JWT Token
  • Client-Server Scenario With JWT Refresh Token

Let’s start one by one with the basics and real-time scenarios.

Basically, JWT is used for the authentication and authorization of different users.

Authentication

In this process, we send the username and password to the authentication server. The authentication server will validate those credentials and store them somewhere on the browser session and cookies and send the ID to the end user.

Authorization

In authorization, we check whatever credential is entered by the user during the “Authentication” process, and that same user will have granted access to the resource using the credential that we store in the “Authentication” process and then authorize that particular user.

Introduction of JWT Token

  • JSON Web Token is the pen standard (RFC 7519) self-contained way that will be used to transmit the data securely over the different environments as a JSON object.
  • RFC (Request for Comment) is the shortened form of Remote Function Call and a formal document from the Internet Engineering Task Force. 
  • JWT is the trusted way of authentication because it is digitally signed and secret using HMAC Algorithm or sometimes using a public/private key using RSA.
  • HMAC stands for Hashed-based Message Authentication Code; it uses some great cryptographic hashing technique that provides efficient security.
  • JWT is part of the great authentication and authorization framework, like OAuth and OpenID, which will provide a great mechanism to transfer data securely.

Why JWT Token?

  • The user will authenticate using the JWT token, which is a digitally signed signature with a secret key issued by the issuer. So, that will be used to authenticate the user securely and manage the claims, and many more.
  • Instead of storing user credentials information somewhere on the server that can easily be accessed by attackers over the internet, we use JWT. When we use that, we maintain user secrets with different cryptographic algorithms and encode that to authenticate users. 

That’s why many web applications use JWT for the authentication of users securely.

Structure of JWT Token

The JSON Web Token consists of three parts that store user information in the token separated by dots(.) For example:

Three Parts

Encoded

As you see in the above diagram, it is an encoded Base64 URL that stores user secrets and information in three parts:

1. Header

The header stores information about the JWT token, like the type of token and whatever algorithm we used to create it. For example:

{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload

Payload is the second part of the JWT token, which stores information about users like claims, roles, subjects, and additional information related to a user. For example:

{
  "sub": "1234567890",
  "name": "Jaydeep Patil",
  "admin": "true"
}

3. Signature

A signature checks user information that is present in the header and payload that validate things with the secret key and the data present in the base64-encoded string. The secret key is present on the server, which we use while creating the token. That secret key prevents external attackers from cracking the token. So, in this process, a Base64-encoded string is created to be used for authentication and authorization:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),//This is the Secret Key which is store at server side and use in signature
your-256-bit-secret)

These are the three parts of the token that are present in the Base64Url string, which is separated by a dot and stores secret information of the user for validating users.

Client-Server Scenario With JWT Token

You can see in the following diagram how the authentication process works for the user when they want to access the resources from the backend server.

Diagram

  • First, the user sends a request to the authentication server with credentials like the user name and password.
  • Then, the authentication server will validate that information, and whatever information is provided by the user will be correct and successfully authenticated so the auth server can issue the JWT Valid Access Token to the user.
  • Next, the user sends the first request to the backend server with a valid JWT Access Token, and the server will provide the requested resource to the user.
  • Later on, if the user wants to access another service from the backend server, then he will send a second request to the server.
  • Now, as you see in the diagram, the user sends the second request to the server to access the protected resource, but at that time, the token is expired, so the server responds to the end user.
  • Finally, as you see in the last part of the diagram, the user again needs to log in and send the user credential to the authentication server to get a new JWT Valid Access Token and store it somewhere on the client side in the local storage and something similar in the Base64Url Encoded URL. This way, the normal authentication process will work.

Client-Server Scenario With JWT Refresh Token

You can see in the following diagram how the JWT Refresh Token will work step-by-step.

Token 2

  • First, the user will send the request to the authentication server with credentials like the user name and password.
  • Next, the authentication server validates the user information and credentials that will be correct, and the server will provide the JWT Valid Access Token and Refresh Token. 
  • Then, the user will store that token somewhere on the client side in the local storage and something similar, as per need and requirement.
  • Later on, the user sends the first request to the backend server to access the protected resources with the JWT Valid Access Token in the header.
  • Next, the backend server checks the roles and permission of the user, like the login the user is authorized to use to get to the protected resources, and that will be valid and proper. Next, the backend server provides the requested protected resource to the end user.
  • In the meantime, the user sends the second request to the backend server to access another service. If the JWT Valid Access Token is expired, the server will respond to the end user, as you see in the above image. Then, the user sends the authentication request to the auth server with the “Refresh Token” to get a new JWT Access Token.
  • Next, the server will validate the user information and provide a new access token with a refresh token to the end username, and the refresh tokens will have more life than the Simple JWT Valid Access Token.

All the above steps are executed continuously while navigating the web application and accessing the new services and resources over the internet.

Conclusion

This article was all about the JWT token and how things are going to work during the authentication and authorization process.

I hope you understand all things related to JWT and now have a basic idea about it.

Happy coding!

Source: https://javascript.plainenglish.io

#jwt #security

JSON Web Token (JWT): Authorization and Authentication