HTTP/2 Rapid Reset : anatomie de l'attaque record

Post Syndicated from Lucas Pardue original http://blog.cloudflare.com/fr-fr/technical-breakdown-http2-rapid-reset-ddos-attack-fr-fr/


À compter du 25 août 2023, nous avons commencé à observer des attaques HTTP inhabituellement volumineuses frappant bon nombre de nos clients. Ces attaques ont été détectées et atténuées par notre système anti-DDoS automatisé. Il n’a pas fallu longtemps pour que ces attaques atteignent des tailles record, pour finir par culminer à un peu plus de 201 millions de requêtes par seconde, soit un chiffre près de trois fois supérieur à la précédente attaque la plus volumineuse que nous ayons enregistrée.

Vous êtes victime d’une attaque ou avez besoin d’une protection supplémentaire ? Cliquez ici pour demander de l’aide.

Le fait que l’acteur malveillant soit parvenu à générer une attaque d’une telle ampleur à l’aide d’un botnet de tout juste 20 000 machines s’avère préoccupant. Certains botnets actuels se composent de centaines de milliers ou de millions de machines. Comme qu’Internet dans son ensemble ne reçoit habituellement qu’entre 1 et 3 milliards de requêtes chaque seconde, il n’est pas inconcevable que l’utilisation de cette méthode puisse concentrer l’intégralité du nombre de requêtes du réseau sur un petit nombre de cibles.

Détection et atténuation

Il s’agissait d’un nouveau vecteur d’attaque évoluant à une échelle sans précédent, mais les protections Cloudflare existantes ont largement pu absorber le plus gros de ces attaques. Si nous avons constaté au départ un certain impact sur le trafic client (environ 1 % des requêtes ont été touchées pendant la vague d’attaques initiale), nous avons ensuite pu perfectionner nos méthodes d’atténuation afin de bloquer l’attaque pour n’importe quel client Cloudflare sans affecter nos systèmes.

Nous avons remarqué ces attaques en même temps que deux autres acteurs majeurs du secteur : Google et AWS. Nous nous sommes attelés au renforcement des systèmes de Cloudflare afin de nous assurer qu’aujourd’hui tous nos clients sont protégés contre cette nouvelle méthode d’attaque DDoS sans impact sur ces derniers. Nous avons également participé, avec Google et AWS, à une révélation coordonnée de l’attaque aux prestataires affectés et aux fournisseurs d’infrastructure essentielle.

Cette attaque a été rendue possible par l’abus de certaines fonctionnalités du protocole HTTP/2 et des détails de mise en œuvre des serveurs (voir la CVE-2023-44487 pour plus d’informations). Comme l’attaque tire parti d’une faiblesse sous-jacente du protocole HTTP/2, nous pensons que tous les fournisseurs qui ont déployé le HTTP/2 subiront l’attaque. Ce constat comprend tous les serveurs web modernes. Aux côtés de Google et d’AWS, nous avons divulgué la méthode d’attaque aux fournisseurs de serveurs web qui, nous l’espérons, déploieront les correctifs. Entre temps, la meilleure défense consiste à utiliser un service d’atténuation des attaques DDoS tel que Cloudflare en amont de chaque réseau en contact avec Internet ou de chaque serveur d’API.

Cet article s’intéressera en profondeur aux détails du protocole HTTP/2, la fonctionnalité exploitée par les acteurs malveillants pour générer ces attaques d’envergure, ainsi qu’aux stratégies d’atténuation que nous avons appliquées pour nous assurer que tous nos clients sont protégés. Nous espérons qu’en publiant ces détails d’autres serveurs web et services affectés disposeront des informations dont ils ont besoin pour mettre en œuvre ces stratégies d’atténuation. En outre, l’équipe chargée des normes du protocole HTTP/2, de même que les équipes travaillant sur les futures normes web, pourront mieux concevoir ces dernières afin d’empêcher de telles attaques.

Détails de l’attaque RST

Le protocole d’application HTTP sous-tend Internet. La norme HTTP Semantics est commune à toutes les versions de HTTP : l’architecture générale, la terminologie et les aspects de protocole, comme les messages de requête et de réponse, les méthodes, les codes d’état, les champs d’en-tête et de trailer, le contenu des messages et bien d’autres. Chaque version individuelle de HTTP définit la manière dont la sémantique est transformée au « format conversation » (wire) pour l’échange sur Internet. Un client doit, par exemple, sérialiser un message de requête en données binaires avant de l’envoyer. Le serveur l’analyse ensuite et le retransforme en message qu’il peut traiter.

Le protocole HTTP/1.1 utilise une forme textuelle de sérialisation. Les messages de requête et de réponse sont échangés sous la forme d’un flux de caractères ASCII, envoyé via une couche de transport fiable, comme le TCP, selon le format suivant (dans lequel CRLF signifie retour chariot et saut de ligne) :

 HTTP-message   = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

Une requête GET très simple pour https://blog.cloudflare.com/ ressemblerait, par exemple, à ceci sur la conversation :

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

Et la réponse ressemblerait à ce qui suit :

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Ce format encapsule les messages sur la conversation, pour indiquer qu’il est possible d’utiliser une unique connexion TCP pour échanger plusieurs requêtes et réponses. Le format nécessite toutefois que chaque message soit envoyé en entier. En outre, afin de faire entrer correctement en corrélation les requêtes avec les réponses, un ordre strict se révèle nécessaire. Les messages peuvent donc être échangés de manière sérielle et ne peuvent pas être multiplexés. Deux requêtes GET, pour https://blog.cloudflare.com/ et https://blog.cloudflare.com/page/2/,, se présenteraient ainsi sous la forme suivante :

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLFGET /page/2/ HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

Et les réponses :

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>CRLFHTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Les pages web nécessitent davantage d’interactions HTTP compliquées que ces exemples. Lorsque vous visitez le blog de Cloudflare, votre navigateur charge plusieurs scripts, styles et ressources multimédias. Si vous accédez à la page d’accueil à l’aide du protocole HTTP/1.1 et que vous décidez rapidement de vous rendre sur la page 2, votre navigateur a le choix entre deux options. Soit attendre l’ensemble des réponses en attente pour la page que vous ne souhaitez plus consulter avant de démarrer la page 2, soit annuler les requêtes en transit en mettant fin à la connexion TCP et en établissant une nouvelle connexion. Aucune de ces options ne s’avère particulièrement pratique. Les navigateurs ont tendance à contourner ces limitations en gérant un pool de connexions TCP (jusqu’à 6 par hôte) et en mettant en œuvre une logique complexe de répartition des requêtes au sein du pool.

Le protocole HTTP/2 répond à bon nombre des problèmes du HTTP/1.1. Chaque message HTTP est sérialisé sous la forme d’un ensemble de trames HTTP/2 disposant d’un type, d’une longueur, de marqueurs, d’un identifiant (ID) de flux et d’un contenu. L’ID de flux indique clairement quels octets sur la conversation s’appliquent à un message donné, afin de permettre le multiplexage et la concurrence en toute sécurité. Les flux sont bidirectionnels. Les clients envoient des trames et les serveurs répondent par des trames utilisant le même ID.

En HTTP/2, notre requête GET pour https://blog.cloudflare.com serait échangée sur l’ID de flux 1, le client envoyant une trame HEADERS et le serveur répondant par une trame HEADERS, suivies par une ou plusieurs trames DATA. Comme les requêtes du client utilisent toujours des ID de flux impairs, les requêtes suivantes utiliseront donc les ID de flux 3, 5 et ainsi de suite. Les réponses peuvent être transmises dans n’importe quel ordre et les trames provenant de flux différents peuvent être entrelacées.

Le multiplexage et la concurrence des flux constituent de puissantes fonctionnalités du protocole HTTP/2. Elles permettent l’utilisation plus efficace d’une unique connexion TCP. Le HTTP/2 optimise la récupération de ressources, notamment lorsqu’elle est associée à la priorisation. En réciproque, le fait de faciliter le lancement de vastes quantités de tâches parallèles aux clients peut accroître le pic de demande de ressources serveur par rapport au HTTP/1.1. Il s’agit là d’un vecteur évident de déni de service.

Afin de proposer quelques garde-fous, le HTTP/2 avance la notion de maximum de flux concurrents actifs. Le paramètre SETTINGS_MAX_CONCURRENT_STREAMS permet à un serveur d’annoncer sa limite de concurrence. Par exemple, si le serveur annonce une limite de 100, seules 100 requêtes pourront être actives à un moment donné. Si un client tente d’ouvrir un flux au-delà de cette limite, ce dernier devra être rejeté par le serveur à l’aide d’une trame RST_STREAM. Le rejet d’un flux n’affecte pas les autres flux en transit sur la connexion.

La réalité de l’affaire est un peu plus compliquée. Les flux présentent un cycle de vie. Vous trouverez ci-dessous un schéma de l’état d’un flux HTTP/2. Le client et le serveur gèrent leurs propres vues de l’état d’un flux. L’envoi ou la réception de trames HEADERS, DATA et RST_STREAM déclenchent les transitions. Les vues de l’état d’un flux sont indépendantes, mais restent synchronisées.

Les trames HEADERS et DATA intègrent un marqueur END_STREAM qui, lorsqu’il est défini sur la valeur 1 (true), peut déclencher une transition d’état.

Examinons ceci plus en détail avec un exemple de requête GET sans contenu de message. Le client envoie la requête sous la forme d’une trame HEADERS comportant le marqueur END_STREAM défini sur 1. Il déclenche en premier lieu la transition de l’état « idle » (à l’arrêt) à « open » (ouvert), avant de déclencher immédiatement une transition vers l’état « half-closed » (mi-fermé). L’état « half-closed » du client indique qu’il ne peut plus envoyer de trames HEADERS ou DATA, mais uniquement des trames WINDOW_UPDATE, PRIORITY ou RST_STREAM. Il peut toutefois recevoir n’importe quelle trame.

Une fois que le serveur reçoit et analyse la trame HEADERS, il fait passer l’état du flux d’« idle » à « open », puis à « half-closed », afin de correspondre à celui du client. L’état « half-closed » du serveur indique qu’il peut envoyer n’importe quelle trame, mais qu’il ne peut recevoir que des trames WINDOW_UPDATE, PRIORITY ou RST_STREAM.

La réponse à la requête GET contient un contenu de message, aussi le serveur envoie-t-il une trame HEADERS comportant le marqueur END_STREAM défini sur 0, puis une trame DATA comportant le marqueur END_STREAM défini sur 1. La trame DATA déclenche la transition du flux de half-closed à closed (fermé) sur le serveur. Lorsque le client la reçoit, il lance également sa transition vers l’état « closed ». Une fois un flux fermé, plus aucune trame ne peut être envoyée ou reçue.

En appliquant ce cycle de vie dans le contexte de la concurrence, le protocole HTTP/2 précise :

Les flux à l’état « open » ou dans l’un des deux états « half-closed » comptent dans le nombre maximum de flux qu’un point de terminaison est autorisé à ouvrir. Les flux dans l’un de ces trois états comptent à l’égard de la limite annoncée dans le paramètre SETTINGS_MAX_CONCURRENT_STREAMS.

En théorie, la limite de concurrence est utile. Certains facteurs pratiques entravent toutefois son efficacité, que nous aborderons plus tard dans cet article.

Annulation de requête HTTP/2

Un peu plus tôt, nous avons évoqué l’annulation de requêtes en transit par le client. Le protocole HTTP/2 prend cette fonctionnalité en charge de manière plus efficace que le HTTP/1.1. Plutôt que de devoir abandonner la connexion dans son ensemble, un client peut désormais envoyer une trame RST_STREAM pour un seul flux. Cette dernière demande au serveur de mettre fin au traitement de la requête et d’abandonner la réponse. Cette opération libère des ressources serveur et permet d’éviter de gaspiller de la bande passante.

Reprenons notre exemple précédent, avec les trois requêtes. Cette fois, le client annule la requête sur le flux 1 après l’envoi de toutes les trames HEADERS. Le serveur analyse la trame RST_STREAM avant d’être prêt à diffuser la réponse et, à la place, ne répond qu’aux flux 3 et 5 :

L’annulation de requête constitue une fonctionnalité bien utile. Lorsque vous parcourez une page web comportant plusieurs images, par exemple, un navigateur web peut annuler les images qui ne sont pas affichées dès l’ouverture. Les images qui lui parviennent peuvent donc être chargées plus rapidement. Le protocole HTTP/2 rend ce comportement bien plus efficace par rapport au HTTP/1.1.

Un flux de requête annulé passe rapidement par tous les états du cycle de vie d’un flux. La trame HEADERS envoyée par le client, comportant le marqueur END_STREAM défini sur 1, passe de l’état « idle » à « open », puis à « half-closed », avant que la trame RST_STREAM ne déclenche immédiatement sa transition de l’état « half-closed » à « closed ».

Souvenez-vous que seuls les flux à l’état « open » ou « half-closed » sont comptabilisés dans la limite de concurrence du flux. Lorsqu’un client annule un flux, il regagne instantanément la capacité d’ouvrir un autre flux à la place et peut immédiatement envoyer une nouvelle requête. C’est là le cœur du fonctionnement de la vulnérabilité CVE-2023-44487.

Des réinitialisations rapides conduisant à un déni de service

Le processus d’annulation de requête du protocole HTTP/2 peut être utilisé de manière abusive en réinitialisant rapidement un nombre illimité de flux. Lorsqu’un serveur HTTP/2 peut traiter des trames client-sent RST_STREAM et leur faire changer d’état suffisamment rapidement, ces réinitialisations rapides ne posent pas de problème. Les soucis commencent lorsqu’une quelconque forme de retard ou de latence apparaît lors du nettoyage. Le client peut avoir à traiter un nombre de requêtes si important que les tâches s’accumulent, en entraînant une consommation excessive de ressources sur le serveur.

Une architecture de déploiement HTTP courante consiste à exécuter un proxy HTTP/2 ou un équilibreur de charge en amont des autres composants. Lorsqu’une requête client arrive, elle est rapidement retransmise et la tâche réelle est effectuée sous forme d’activité asynchrone à un autre endroit. Cette opération permet au proxy de traiter le trafic client très efficacement. Toutefois, cette séparation des préoccupations peut compliquer la phase de nettoyage des tâches en cours pour le proxy. Ce type de déploiement est donc plus susceptible de rencontrer des problèmes en cas de réinitialisations rapides.

Lorsque les proxys inverses de Cloudflare traitent du trafic client entrant HTTP/2, ils copient les données du socket de la connexion au sein d’un tampon et traitent ces données en tampon dans l’ordre. Chaque requête est lue (trames HEADERS et DATA) et transmise à un service en amont. Lorsque les trames RST_STREAM sont lues, l’état local de la requête est abandonné et l’amont est notifié de l’annulation de la requête. Les proxys répètent ensuite le processus jusqu’à ce que toutes les données en tampon aient été traitées. Cette logique peut toutefois être utilisée de manière abusive : si un client malveillant commence à envoyer une énorme chaîne de requêtes, qu’il réinitialise au début d’une connexion, nos serveurs s’empresseront de toutes les lire. Cette situation engendrera alors une pression sur les serveurs en amont, au point qu’ils se retrouveront incapables de traiter les nouvelles requêtes entrantes.

Un point important à souligner est que la concurrence de flux ne peut pas, par elle-même, atténuer les réinitialisations rapides. Le client peut créer des requêtes afin de produire des taux de requêtes élevés, peu importe la valeur choisie par le serveur pour le paramètre SETTINGS_MAX_CONCURRENT_STREAMS.

Anatomie d’une réinitialisation rapide

Voici un exemple de réinitialisation rapide (Rapid Reset) reproduite à l’aide d’un client de démonstration de faisabilité tentant d’envoyer un total de 1 000 requêtes. J’ai utilisé un serveur du commerce ne disposant d’aucune mesure d’atténuation et écoutant le port 443 au sein d’un environnement de test. Le trafic est disséqué à l’aide de Wireshark et filtré pour ne montrer que le trafic HTTP/2, pour plus de clarté. Téléchargez la pcap pour suivre la démonstration.

Il est un peu difficile à analyser, en raison du grand nombre de trames. Nous pouvons en obtenir un résumé rapide à l’aide de l’outil HTTP/2 de Wireshark, disponible sous « Statistics » (Statistiques) :

La première trame de cette trace, dans le paquet 14, est la trame SETTINGS du serveur, qui annonce un nombre maximum de flux concurrents de 100. Dans le paquet 15, le client envoie quelques trames de contrôle, puis commence à envoyer des requêtes, rapidement réinitialisées. La première trame HEADERS fait 26 octets de long, tandis que toutes les trames HEADERS suivantes ne mesurent que 9 octets. Cette différence de taille est due à une technologie de compression nommée HPACK. Au total, le paquet 15 contient 525 requests, remontant le long du flux 1051.

Curieusement, la trame RST_STREAM du flux 1051 ne rentre pas dans le paquet 15. Nous voyons donc, dans le paquet 16, le serveur répondre par une erreur 404. Le client envoie ensuite la trame RST_STREAM dans le paquet 17, avant de passer à l’envoi des 475 requêtes suivantes.

Veuillez noter que bien que le serveur ait annoncé 100 flux concurrents, les deux paquets envoyés par le client comportaient bien plus de trames HEADERS. Le client n’a pas attendu le trafic de retour du serveur, il n’était limité que par la taille des paquets qu’il pouvait envoyer. Aucune trame RST_STREAM du serveur n’apparaît dans cette trace, un constat qui indique que le serveur n’a pas observé de violation du nombre de flux concurrents.

Impact sur les clients

Comme mentionné plus haut, lorsque les requêtes sont annulées, les services en amont sont notifiés et peuvent abandonner ces dernières avant de gaspiller trop de ressources sur leur traitement. C’est ce qui s’est passé dans cette attaque, au cours de laquelle les requêtes malveillantes n’ont jamais été retransmises aux serveurs d’origine. Toutefois, l’ampleur de ces attaques a engendré des effets.

Tout d’abord, lorsque le taux de requêtes entrantes a atteint des pics jamais encore observés jusqu’ici, nous avons reçu des signalements de niveaux élevés d’erreurs 502 observées par les clients. C’est ce qui s’est produit dans nos datacenters les plus impactés, car ils avaient du mal à traiter toutes les requêtes. Notre réseau est conçu pour faire face aux attaques d’envergure, mais cette vulnérabilité a révélé une faiblesse au sein de notre infrastructure. Intéressons-nous de plus près aux détails, en nous concentrant sur la manière dont les requêtes entrantes sont traitées lorsqu’elles arrivent dans l’un de nos datacenters :

Nous pouvons voir que notre infrastructure se compose d’une chaîne de différents serveurs de proxy aux responsabilités différentes. Plus particulièrement, lorsqu’un client se connecte à Cloudflare pour envoyer du trafic HTTPS, ce dernier passe en premier par notre proxy de déchiffrement TLS, qui déchiffre le trafic TLS et traite le trafic HTTP 1, 2 ou 3, avant de le transmettre à notre proxy de « logique métier ». Ce dernier est responsable du chargement de l’ensemble des paramètres pour chaque client, puis du routage correct des requêtes vers les autres services d’amont. Plus important encore dans le cas qui nous intéresse, il est également responsable des fonctionnalités de sécurité. C’est là que l’atténuation des attaques sur la couche 7 est mise en œuvre.

Le problème avec ce vecteur d’attaque réside dans le fait qu’il parvient à envoyer un grand nombre de requêtes de manière très rapide, sur chaque connexion. Chacune d’elles devait être retransmise au proxy de logique métier avant que nous n’ayons l’occasion de la bloquer. Lorsque le volume de requêtes s’est révélé supérieur à la capacité de notre proxy, le pipeline reliant ces deux services a atteint son niveau de saturation dans certains de nos serveurs.

Quand cette situation se produit, le proxy TLS ne peut plus se connecter à son proxy d’amont. C’est pourquoi certains de nos clients ont vu s’afficher une erreur « 502 Bad Gateway » lors des attaques les plus graves. Il est important de noter qu’à la date d’aujourd’hui, les journaux utilisés pour produire les analyses HTTP sont également émis par notre proxy de logique métier. En conséquence, ces erreurs ne sont pas visibles au sein du tableau de bord Cloudflare. Nos tableaux de bord internes révèlent qu’environ 1 % des requêtes ont été affectées lors de la vague d’attaques initiale (avant la mise en œuvre des mesures d’atténuation), avec un pic se situant autour de 12 % pendant quelques secondes lors de l’attaque la plus massive, le 29 août. Le graphique suivant montre la proportion de ces erreurs sur une période de deux heures au cours de l’attaque :

Nous nous sommes efforcés de réduire ce nombre de manière considérable les jours suivants, comme nous le détaillons plus loin dans cet article. Ce nombre aujourd’hui est effectivement de zéro, à la fois grâce aux modifications apportées à notre pile et à nos mesures d’atténuation, qui ont drastiquement réduit la taille de ces attaques.

Erreurs 499 et les défis liés à la concurrence des flux HTTP/2

Un autre symptôme signalé par certains clients réside dans l’augmentation des erreurs 499. La raison est ici quelque peu différente et se trouve liée à la concurrence de flux maximale au sein d’une connexion HTTP/2, comme détaillée précédemment dans l’article.

Les paramètres HTTP/2 sont échangés au début d’une connexion à l’aide de trames SETTINGS. En l’absence de réception d’un paramètre explicite, ce sont les valeurs par défaut qui s’appliquent. Lorsqu’un client établit une connexion HTTP/2, il peut soit attendre la trame SETTINGS d’un serveur (lent), soit présupposer les valeurs par défaut et commencer à envoyer des requêtes (rapide). Pour le paramètre SETTINGS_MAX_CONCURRENT_STREAMS, la valeur par défaut est, dans les faits, illimitée (les ID de flux s’appuient sur un espace mathématique de 31 bits et les requêtes utilisent les nombres impairs. la limite réelle est donc établie à 1 073 741 824). La spécification recommande qu’un serveur ne propose pas moins de 100 flux concurrents. Les clients sont généralement axés sur la vitesse. Ils n’ont donc pas tendance à attendre les paramètres du serveur et ce fait entraîne en quelque sorte une situation de compétition. Ils « parient » sur la limite que le serveur pourrait avoir choisie. S’ils se trompent, la requête sera rejetée et devra être renvoyée. Le fait de parier sur un ensemble numérique de 1 073 741 824 nombres s’avère pour le moins absurde. Pour contrebalancer cette situation, de nombreux clients décident de se limiter à l’émission de 100 flux concurrents, dans l’espoir que les serveurs suivent la recommandation de la spécification. Si les serveurs ont sélectionné une valeur inférieure à 100, le pari du client échoue et les flux sont réinitialisés.

Un serveur pourrait réinitialiser un flux pour de nombreuses raisons en dehors d’un dépassement de la limite de concurrence. Le HTTP/2 est strict et nécessite qu’un flux soit fermé (closed) en cas d’erreurs d’interprétation ou d’erreurs logiques. En 2019, Cloudflare a développé plusieurs mesures d’atténuation en réponse aux vulnérabilités DoS du protocole HTTP/2. Plusieurs de ces vulnérabilités résultaient d’un mauvais comportement de la part du client, qui poussait le serveur à réinitialiser un flux. Une stratégie très efficace pour freiner ces clients consiste à compter le nombre de réinitialisations du serveur au cours d’une connexion puis, lorsque ce chiffre dépasse un certain seuil, de mettre un terme à cette dernière à l’aide d’une trame GOAWAY. Les clients peuvent commettre une ou deux erreurs au cours d’une connexion et il s’agit là d’un constat acceptable. Un client qui commet trop d’erreurs est probablement soit défectueux, soit malveillant, et le fait de mettre fin à la connexion répond aux deux cas.

En réponse aux attaques DoS permises par la vulnérabilité CVE-2023-44487, Cloudflare a réduit la concurrence de flux maximale à 64. Avant d’effectuer cette modification, nous n’avions pas conscience que les clients n’attendaient pas la trame SETTINGS et supposaient à la place que la concurrence était fixée à 100. Certaines pages web, comme les galeries d’images, entraînent effectivement l’envoi immédiat de 100 requêtes par le navigateur au début d’une connexion. Malheureusement, les 36 flux au-delà de notre limite devaient être réinitialisés et cette opération déclenchait les compteurs de nos mesures d’atténuation. Nous interrompions donc des connexions sur des clients légitimes, avec pour résultat un échec total du chargement des pages. Dès que nous avons constaté ce problème d’interopérabilité, nous avons de nouveau fixé la concurrence de flux maximale à 100.

Actions côté Cloudflare

En 2019, nous avons découvert plusieurs vulnérabilités DoS liées à l’implémentation du protocole HTTP/2. Cloudflare a développé et déployé une série de mesures de détection et d’atténuation en réponse. La vulnérabilité CVE-2023-44487 est une différente manifestation de la vulnérabilité HTTP/2. Toutefois, pour l’atténuer, nous avons pu étendre les protections existantes afin de surveiller les trames RST_STREAM envoyées par les clients et de mettre fin aux connexions lorsque ces dernières étaient utilisées à des fins abusives. Les scénarios d’utilisation légitimes des trames RST_STREAM par les clients n’ont pas été affectés.

En plus d’un correctif direct, nous avons mis en œuvre plusieurs améliorations du serveur concernant le traitement des trames HTTP/2 et du code de répartition des requêtes. Le serveur de logique métier a, en outre, fait l’objet de perfectionnements au niveau de la mise en file d’attente et de la planification. Ces derniers réduisent le travail inutile et améliorent la réponse aux annulations. Ensemble, ces mesures diminuent l’impact des divers schémas d’abus potentiels, tout en accordant plus d’espace au serveur pour traiter les requêtes avant d’atteindre la saturation.

Atténuer les attaques à un moment plus précoce

Cloudflare dispose déjà de systèmes en place permettant d’atténuer efficacement les attaques de très grande ampleur à l’aide de méthodes moins coûteuses. L’une d’elles se nomme « IP Jail » (Prison IP). En cas d’attaques hypervolumétriques, ce système collecte les adresses IP des clients participant à l’attaque et les empêche de se connecter à la propriété attaquée, que ce soit au niveau de l’adresse IP ou de notre proxy TLS. Ce système demande toutefois quelques secondes pour être pleinement efficace. Au cours de ces précieuses secondes, les serveurs d’origine sont déjà protégés, mais notre infrastructure doit encore absorber l’ensemble des requêtes HTTP. Comme ce nouveau botnet ne dispose dans les faits d’aucune période de démarrage, nous devons pouvoir neutraliser ces attaques avant qu’elles ne deviennent un problème.

Pour y parvenir, nous avons étendu le système IP Jail afin qu’il protège l’intégralité de notre infrastructure. Une fois une adresse IP « en prison », nous l’empêchons non seulement de se connecter à la propriété attaquée, mais interdisons également aux adresses IP correspondants d’utiliser le HTTP/2 pour se connecter à un autre domaine sur Cloudflare pendant quelque temps. Comme de tels abus du protocole ne sont pas possibles à l’aide du HTTP/1.x, l’acteur malveillant se trouve sévèrement limité dans sa capacité à conduire des attaques d’envergure, tandis qu’un client légitime partageant la même adresse IP ne constaterait d’une très légère diminution des performances pendant ce temps. Les mesures d’atténuation basées sur l’IP constituent un outil pour le moins brutal. C’est pourquoi nous devons faire preuve d’une extrême prudence lorsque nous les utilisons à grande échelle et chercher à éviter les faux positifs autant que possible. De même, comme la durée de vie d’une adresse IP donnée au sein d’un botnet est généralement courte, l’atténuation à long terme risque davantage de nuire que d’aider. Le graphique suivant montre l’évolution du nombre d’adresses IP lors de l’attaque dont nous avons été témoins :

Il apparaît très clairement que les nouvelles adresses IP repérées lors d’une journée donnée disparaissent très rapidement après l’attaque.

Le fait que ces actions se déroulent dans notre proxy TLS, à l’entrée de notre pipeline HTTPS, permet d’économiser des ressources considérables par rapport à notre système d’atténuation de couche 7 habituel. Cette situation nous a permis de supporter ces attaques d’autant plus facilement et, aujourd’hui, le nombre d’erreurs 502 aléatoires dues à ces botnets a été réduit à zéro.

Améliorations en matière d’observabilité

L’un des autres fronts sur lequel nous avons apporté des modifications est celui de l’observabilité. Le fait de renvoyer des erreurs aux clients sans que ces dernières soient visibles dans les outils d’analyse des clients se révèle pour le moins insatisfaisant. Fort heureusement, nous avons lancé un projet visant à réorganiser ces systèmes bien avant les attaques récentes. Il permettra à terme à chaque service compris au sein de notre infrastructure de journaliser ses propres données, au lieu de s’en remettre à notre proxy de logique métier pour consolider et émettre les données de journalisation. Cet incident a fait ressortir l’importance de ce travail, dans le cadre duquel nous redoublons d’efforts.

Nous travaillons également à une meilleure journalisation au niveau de la connexion, afin de nous permettre de repérer ce type d’abus de protocole bien plus rapidement, afin d’améliorer nos capacités d’atténuation des attaques DDoS.

Conclusion

Si l’attaque à laquelle cet article est consacré constituait sans conteste la dernière attaque record à ce jour, nous savons que ce ne sera pas la dernière. Alors que les attaques gagnent chaque jour en sophistication, Cloudflare travaille avec acharnement aux moyens d’identifier les nouvelles menaces de manière proactive, en déployant des contremesures sur notre réseau mondial afin de protéger nos millions de clients, immédiatement et automatiquement.

Cloudflare fournit une protection contre les attaques DDoS gratuite, totalement illimitée et sans surcoût lié à l’utilisation à l’ensemble de ses clients, et ce depuis 2017. Nous proposons en outre une gamme de fonctionnalités de sécurité supplémentaires afin de répondre aux besoins des entreprises de toutes les tailles. Contactez-nous si vous n’êtes pas sûr de savoir si vous êtes protégé ou si vous souhaitez comprendre comment vous pourriez l’être.

HTTP/2 Rapid Reset: cómo desarmamos el ataque sin precedentes

Post Syndicated from Lucas Pardue original http://blog.cloudflare.com/es-es/technical-breakdown-http2-rapid-reset-ddos-attack-es-es/


El 25 de agosto de 2023, empezamos a observar algunos ataques de inundación HTTP inusualmente voluminosos que afectaban a muchos de nuestros clientes. Nuestro sistema DDoS automatizado detectó y mitigó estos ataques. Sin embargo, no pasó mucho tiempo antes de que empezaran a alcanzar tamaños sin precedentes, hasta alcanzar finalmente un pico de 201 millones de solicitudes por segundo, casi el triple que el mayor ataque registrado hasta ese momento.

¿Estás siendo blanco de un ataque o necesitas mayor protección? Si necesitas ayuda, haz clic aquí.

Lo más inquietante es que el atacante fuera capaz de generar semejante ataque con una botnet de solo 20 000 máquinas. Hoy en día existen botnets formadas por cientos de miles o millones de máquinas. La web suele recibir solo entre 1000 y 3000 millones de solicitudes por segundo, por eso no parece imposible que utilizando este método se pudiera concentrar el volumen de solicitudes de toda una web en un pequeño número de objetivos.

Detección y mitigación

Se trataba de un vector de ataque novedoso a una escala sin precedentes, pero las soluciones de protección de Cloudflare pudieron mitigar en gran medida los efectos más graves de los ataques. Si bien al principio observamos cierto impacto en el tráfico de los clientes, que afectó aproximadamente al 1 % de las solicitudes durante la oleada inicial de ataques, hoy hemos podido perfeccionar nuestros métodos de mitigación para detener el ataque de cualquier cliente de Cloudflare sin que nuestros sistemas se vean afectados.

Nos dimos cuenta de estos ataques mientras otros dos grandes empresas del sector, Google y AWS, observaban lo mismo. Trabajamos para consolidar los sistemas de Cloudflare y garantizar que, a día de hoy, todos nuestros clientes estén protegidos de este nuevo método de ataque DDoS sin que afecte a ningún cliente. También hemos participado con Google y AWS en una divulgación coordinada del ataque a los proveedores afectados y a los proveedores de infraestructuras críticas.

Este ataque fue posible mediante el abuso de algunas funciones del protocolo HTTP/2 y de detalles de implementación del servidor (para más información, véase CVE-2023-44487). Dado que el ataque aprovecha una deficiencia subyacente en el protocolo HTTP/2, creemos que cualquier proveedor que haya implementado este protocolo será objeto del ataque. Esto incluye todos los servidores web modernos. Nosotros, junto con Google y AWS, hemos revelado el método de ataque a los proveedores de servidores web, que esperamos implementen revisiones. Mientras tanto, la mejor protección es utilizar un servicio de mitigación de DDoS como el de Cloudflare frente a cualquier servidor web o API pública.

Este artículo analiza los detalles del protocolo HTTP/2, la función que explotaron los atacantes para generar estos ataques masivos, y las estrategias de mitigación que adoptamos para garantizar la protección de todos nuestros clientes. Nuestra esperanza es que, al publicar estos detalles, otros servidores y servicios web afectados dispongan de la información que necesitan para aplicar estrategias de mitigación. Y, además, el equipo de estándares del protocolo HTTP/2, así como los equipos que trabajen en futuros estándares web, puedan diseñarlos mejor para evitar este tipo de incidentes.

Detalles del ataque RST

HTTP es el protocolo de aplicación que permite la transferencia de información en la web. La semántica HTTP es común a todas las versiones de HTTP. La arquitectura general, la terminología y los aspectos del protocolo, como los mensajes de solicitud y respuesta, los métodos, los códigos de estado, los campos de encabezado y finalizador, el contenido de los mensajes y mucho más. Cada versión individual de HTTP define cómo se transforma la semántica en un “formato para transmisión” (wire format) para el intercambio a través de Internet. Por ejemplo, un cliente tiene que serializar un mensaje de solicitud en datos binarios y enviarlo, y luego el servidor lo vuelve a analizar en un mensaje que pueda procesar.

HTTP/1.1 utiliza una forma textual de serialización. Los mensajes de solicitud y respuesta se intercambian como una secuencia de caracteres ASCII, enviados a través de una capa de transporte fiable como TCP y utiliza el siguiente formato (donde CRLF significa “retorno de carro” y “salto de línea”):

 HTTP-message   = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

Por ejemplo, una solicitud GET muy sencilla para https://blog.cloudflare.com/ tendría este aspecto en el formato para transmisión:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

Y la respuesta sería la siguiente:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Este formato encapsula los mensajes en la transmisión, lo que significa que es posible utilizar una única conexión TCP para intercambiar varias solicitudes y respuestas. Sin embargo, el formato requiere que cada mensaje se envíe entero. Además, para correlacionar correctamente las solicitudes con las respuestas, se requiere un orden estricto, lo que significa que los mensajes se intercambian en serie y no se pueden multiplexar. Dos solicitudes GET, para https://blog.cloudflare.com/ y https://blog.cloudflare.com/page/2/,, serían:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLFGET /page/2/ HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

Con las respuestas:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>CRLFHTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Las páginas web requieren interacciones HTTP más complicadas que estos ejemplos. Cuando visites el blog de Cloudflare, tu navegador cargará numerosos scripts, estilos y activos multimedia. Si visitas la página principal utilizando HTTP/1.1 y decides rápidamente ir a la página 2, tu navegador puede elegir entre dos opciones. O bien esperar todas las respuestas en cola para la página que ya no quieres antes de que la página 2 pueda siquiera comenzar, o bien cancelar las solicitudes abiertas cerrando la conexión TCP y abriendo una nueva conexión. Ninguna de estas opciones es muy práctica. Los navegadores tienden a sortear estas limitaciones gestionando un conjunto de conexiones TCP (hasta 6 por host) e implementando una compleja lógica de envío de solicitudes sobre el conjunto.

HTTP/2 aborda muchos de los problemas de HTTP/1.1. Cada mensaje HTTP se serializa en un conjunto de tramas HTTP/2 que tienen tipo, longitud, etiquetas, identificador (Id.) de secuencia y carga malintencionada. El identificador de secuencia deja claro qué bytes de la transmisión corresponden a cada mensaje, lo que permite una multiplexación y concurrencia seguras. Las secuencias son bidireccionales. Los clientes envían tramas y los servidores responden con tramas que utilizan el mismo Id.

En HTTP/2, nuestra solicitud GET de https://blog.cloudflare.comse intercambiaría a través del identificador de secuencia 1. El cliente enviaría una trama HEADERS, y el servidor respondería con una trama HEADERS, seguida de una o más tramas DATA. Las solicitudes del cliente siempre utilizan identificadores de secuencia impares, por lo que las solicitudes posteriores utilizarían identificadores de secuencia 3, 5, etc. Las respuestas se pueden servir en cualquier orden, y se pueden intercalar tramas de distintas secuencias.

La multiplexación de secuencias y la concurrencia son potentes funciones de HTTP/2. Permiten un uso más eficiente de una única conexión TCP. HTTP/2 optimiza la obtención de recursos, especialmente cuando se combina con la priorización. Por otro lado, facilitar a los clientes el lanzamiento de grandes cantidades de trabajo paralelo puede aumentar el pico de demanda de recursos del servidor en comparación con HTTP/1.1. Este es un vector obvio de denegación de servicio.

Para ofrecer protección, HTTP/2 proporciona una noción de secuencias concurrentes activas máximas. El parámetro SETTINGS_MAX_CONCURRENT_STREAMS permite a un servidor anunciar su límite de concurrencia. Por ejemplo, si el servidor declara un límite de 100, entonces solo pueden estar activas 100 solicitudes en cualquier momento. Si un cliente intenta abrir una secuencia por encima de este límite, el servidor la rechazará mediante una trama RST_STREAM. El rechazo de la secuencia no afecta a las demás secuencias en curso en la conexión.

La realidad es un poco más complicada. Las secuencias tienen un ciclo de vida. A continuación se muestra un diagrama de la máquina de estado de la secuencia HTTP/2. El cliente y el servidor gestionan sus propias vistas del estado de una secuencia. Las tramas HEADERS, DATA y RST_STREAM activan transiciones cuando se envían o reciben. Aunque las vistas del estado de la secuencia son independientes, están sincronizadas.

Las tramas HEADERS y DATA incluyen una etiqueta END_STREAM, que cuando se establece en el valor 1 (verdadero), puede activar una transición de estado.

Examinemos esto con un ejemplo de una solicitud GET que no tiene contenido de mensaje. El cliente envía la solicitud como una trama HEADERS con la etiqueta END_STREAM establecida en 1. El cliente primero pasa la secuencia del estado inactivo al estado abierto, y luego pasa inmediatamente al estado semicerrado. El estado semicerrado del cliente significa que ya no puede enviar tramas HEADERS ni DATA, solo tramas WINDOW_UPDATE, PRIORITY o RST_STREAM. Sin embargo, puede recibir cualquier trama.

Una vez que el servidor recibe y analiza la trama HEADERS, cambia el estado de la secuencia de inactivo a abierto y luego a semicerrado, para que coincida con el cliente. El estado semicerrado del servidor significa que puede enviar cualquier trama, pero solo recibir tramas WINDOW_UPDATE, PRIORITY o RST_STREAM.

La respuesta a la solicitud GET incluye el contenido del mensaje, por lo que el servidor envía una trama HEADERS con la etiqueta END_STREAM establecida en 0, y luego una trama DATA con la etiqueta END_STREAM establecida en 1. La trama DATA marca la transición de la secuencia de semicerrado a cerrado en el servidor. Cuando el cliente la recibe, también pasa a cerrado. Una vez se cierra una secuencia, no se pueden enviar ni recibir tramas.

Aplicando de nuevo este ciclo de vida al contexto de la concurrencia, HTTP/2 establece:

Las secuencias que están en estado “abierto” o en cualquiera de los estados “semicerrado” cuentan para el número máximo de secuencias que un punto final puede abrir. Las secuencias en cualquiera de estos tres estados cuentan para el límite anunciado en el ajuste SETTINGS_MAX_CONCURRENT_STREAMS.

En teoría, el límite de concurrencia es útil. Sin embargo, hay factores prácticos que dificultan su eficacia, de los que hablaremos más adelante en el blog.

Anulación de solicitudes HTTP/2

Antes hemos hablado de la anulación por parte del cliente de solicitudes en curso. El protocolo HTTP/2 admite esta función de una forma mucho más eficaz que HTTP/1.1. En lugar de tener que interrumpir toda la conexión, un cliente puede enviar una trama RST_STREAM para una única secuencia. Esta ventaja indica al servidor que deje de procesar la solicitud y anule la respuesta, lo que libera recursos del servidor y evita malgastar ancho de banda.

Consideremos nuestro ejemplo anterior de tres solicitudes. Esta vez el cliente anula la solicitud en la secuencia 1 después de que se hayan enviado todas las tramas HEADERS. El servidor analiza esta trama RST_STREAM antes de estar preparado para servir la respuesta y, en su lugar, solo responde a las secuencias 3 y 5:

La anulación de solicitudes es una función útil. Por ejemplo, al desplazarse por una página web con varias imágenes, un navegador web puede cancelar las imágenes que quedan fuera de la ventanilla, lo que significa que las imágenes que entran en ella pueden cargarse más rápido. El protocolo HTTP/2 hace que este comportamiento sea mucho más eficiente en comparación con HTTP/1.1.

Una secuencia de solicitud que se anula, pasa rápidamente por el ciclo de vida de la secuencia. La trama HEADERS del cliente con la etiqueta END_STREAM establecida en 1 pasa del estado de inactivo a abierto a semicerrado, luego RST_STREAM marca inmediatamente una transición de semicerrado a cerrado.

Recuerda que solo las secuencias que están en estado abierto o semicerrado contribuyen al límite de concurrencia de la secuencia. Cuando un cliente anula una secuencia, obtiene instantáneamente la capacidad de abrir otra en su lugar, y puede enviar otra solicitud inmediatamente. Este es el quid de la cuestión que permite el funcionamiento de CVE-2023-44487.

Restablecimientos rápidos que conducen a la denegación de servicio

Se puede abusar de la anulación de solicitudes HTTP/2 para restablecer rápidamente un número ilimitado de secuencias. Cuando un servidor HTTP/2 es capaz de procesar las tramas RST_STREAM enviadas por el cliente y cambiar el estado con suficiente rapidez, estos restablecimientos rápidos no causan ningún problema. Los problemas empiezan a surgir cuando se produce algún tipo de retraso o demora en la limpieza. El cliente puede hacer tantas solicitudes que se acumule trabajo atrasado, lo que se traduce en un consumo excesivo de recursos en el servidor.

Una arquitectura común de implementación HTTP consiste en ejecutar un proxy HTTP/2 o un equilibrador de carga delante de otros componentes. Cuando llega una solicitud de un cliente, se envía rápidamente y el trabajo real se realiza como una actividad asíncrona en otro lugar. Esta operación permite al proxy gestionar el tráfico de clientes de forma muy eficiente. Sin embargo, esta separación de preocupaciones puede dificultar que el proxy ordene los trabajos en proceso. Por lo tanto, estas implementaciones son más propensas a tropezar con problemas derivados de los restablecimientos rápidos.

Cuando los proxies inversos de Cloudflare procesan el tráfico entrante de clientes HTTP/2, copian los datos del socket de la conexión en un búfer y procesan esos datos almacenados en búfer en orden. A medida que se lee cada solicitud (tramas HEADERS y DATA), se envía a un servicio ascendente. Cuando se leen tramas RST_STREAM, se elimina el estado local de la solicitud y se notifica al servicio ascendente que la solicitud se ha anulado. Todo el proceso se repite hasta que se consuma todo el búfer. Sin embargo, se puede abusar de esta lógica. Si un cliente malintencionado empieza a enviar una enorme cadena de solicitudes y restablecimientos al inicio de una conexión, nuestros servidores las leerán todas con impaciencia y añadirán tensión a los servidores ascendentes hasta el punto de ser incapaces de procesar ninguna nueva solicitud entrante.

Algo que es importante destacar es que la concurrencia de secuencias por sí sola no puede mitigar el restablecimiento rápido. El cliente puede editar las solicitudes para crear altas tasas de solicitudes, independientemente del valor SETTINGS_MAX_CONCURRENT_STREAMS elegido por el servidor.

Análisis exhaustivo de Rapid Reset

A continuación, mostramos un ejemplo de restablecimiento rápido reproducido utilizando un cliente de prueba de concepto que intenta enviar un total de 1000 solicitudes. He utilizado un servidor estándar sin ningún tipo de medida de mitigación, que escucha en el puerto 443 en un entorno de prueba. El tráfico se examina utilizando Wireshark y se filtra para que solo muestre el tráfico HTTP/2 para mayor claridad. Descarga la interfaz pcap para ver explicación.

Es un poco difícil de ver, porque hay muchas tramas. Podemos ver un resumen rápido con la herramienta Estadísticas > HTTP2 de Wireshark:

La primera trama de este rastreo, en el paquete 14, es la trama SETTINGS del servidor, que anuncia una concurrencia de secuencia máxima de 100. En el paquete 15, el cliente envía unas cuantas tramas de control y luego empieza a hacer solicitudes que se restablecen rápidamente. La primera trama HEADERS tiene 26 bytes de longitud, todas las tramas HEADERS posteriores tienen solo 9 bytes. Esta diferencia de tamaño se debe a una tecnología de compresión llamada HPACK. En total, el paquete 15 contiene 525 solicitudes, que llegan hasta la secuencia 1051.

Curiosamente, la trama RST_STREAM para la secuencia 1051 no cabe en el paquete 15, por lo que en el paquete 16 vemos que el servidor envía una respuesta 404.  A continuación, en el paquete 17, el cliente sí envía la trama RST_STREAM, antes de pasar a enviar las 475 solicitudes restantes.

Observa que, aunque el servidor anunciaba 100 secuencias simultáneas, los dos paquetes enviados por el cliente enviaban muchas más tramas HEADERS. El cliente no tenía que esperar ningún tráfico de retorno del servidor, solo estaba limitado por el tamaño de los paquetes que podía enviar. No se ven tramas RST_STREAM del servidor en este rastreo, lo que indica que el servidor no observó una violación de secuencia concurrente.

Impacto en los clientes

Como se ha mencionado anteriormente, a medida que se anulan las solicitudes, los servicios ascendentes reciben una notificación y pueden cancelar las solicitudes antes de gastar demasiados recursos en ello. Así fue este ataque, en el que la mayoría de las solicitudes maliciosas nunca se reenviaron a los servidores de origen. Sin embargo, el gran tamaño de estos ataques causó cierto impacto.

En primer lugar, cuando la tasa de solicitudes entrantes alcanzó picos nunca vistos, recibimos informes de un aumento de los niveles de errores 502 que recibían los clientes. Esto ocurrió en nuestros centros de datos más afectados, mientras trabajaban para procesar todas las solicitudes. Aunque nuestra red está diseñada para hacer frente a grandes ataques, esta vulnerabilidad concreta expuso un punto débil de nuestra infraestructura. Profundicemos un poco más en los detalles, centrándonos en cómo se gestionan las solicitudes entrantes cuando llegan a uno de nuestros centros de datos:

Podemos ver que nuestra infraestructura está compuesta por una cadena de diferentes servidores proxy con distintas responsabilidades. En concreto, cuando un cliente se conecta a Cloudflare para enviar tráfico HTTPS, primero llega a nuestro proxy de descifrado TLS: descifra el tráfico TLS, procesa el tráfico HTTP 1, 2 o 3, y luego lo reenvía a nuestro proxy de “lógica empresarial”. Este se encarga de cargar todas las configuraciones para cada cliente, luego enruta las solicitudes correctamente a otros servicios ascendentes, y lo que es más importante en nuestro caso, también se encarga de las funciones de seguridad. Aquí es donde se procesa la mitigación del ataque a la capa 7.

El problema de este vector de ataque es que consigue enviar muchas solicitudes muy rápido en cada conexión. Cada una de ellas tenía que reenviarse al proxy de lógica empresarial antes de que tuviéramos la oportunidad de bloquearla. A medida que el procesamiento de solicitudes superaba la capacidad de nuestro proxy, la canalización que conecta estos dos servicios alcanzó su nivel de saturación en algunos de nuestros servidores.

Cuando esto ocurre, el proxy TLS ya no se puede conectar a su proxy ascendente, por eso algunos clientes recibieron un error básico “502 Bad Gateway” durante los ataques más graves. Es importante señalar que, a partir de hoy, los registros utilizados para crear análisis HTTP también se emiten por nuestro proxy de lógica empresarial. La consecuencia de ello es que estos errores no son visibles en el panel de control de Cloudflare. Nuestros paneles de control internos muestran que alrededor del 1 % de las solicitudes se vieron afectadas durante la oleada inicial de ataques (antes de que implementáramos las medidas de mitigación). En ese momento, se alcanzaron picos de alrededor del 12 % durante unos segundos en el ataque más grave, ocurrido el 29 de agosto. El siguiente gráfico muestra la relación de estos errores durante dos horas mientras ocurría el ataque:

Trabajamos para reducir este número drásticamente en los días siguientes, como se detalla más adelante en este artículo. Gracias a los cambios en nuestra pila y a nuestras medidas de mitigación, que reducen considerablemente el tamaño de estos ataques, este número es, en la práctica, nulo hoy día.

Errores 499 y los desafíos para la concurrencia de secuencias HTTP/2

Otro síntoma notificado por algunos clientes es un aumento de los errores 499. La razón de este inconveniente es un poco diferente y está relacionada con la máxima concurrencia de secuencias en una conexión HTTP/2 detallada anteriormente en este artículo.

Los parámetros de HTTP/2 se intercambian al inicio de una conexión mediante tramas SETTINGS. Si no se recibe un parámetro explícito, se aplican los valores por defecto. Una vez que un cliente establece una conexión HTTP/2, puede esperar las tramas SETTINGS de un servidor (lento) o puede asumir los valores por defecto y empezar a hacer solicitudes (rápido). Para el ajuste SETTINGS_MAX_CONCURRENT_STREAMS, el valor por defecto es ilimitado en la práctica (los identificadores de secuencia utilizan un espacio numérico de 31 bits, y las solicitudes utilizan números impares, por lo que el límite real es 1073741824). La especificación recomienda que un servidor no ofrezca menos de 100 secuencias. Los clientes se suelen inclinar por la velocidad, por lo que no suelen esperar a la configuración del servidor, lo que crea una especie de condición de anticipación. Los clientes arriesgan en cuanto al límite que puede elegir el servidor. Si se equivocan, la solicitud será rechazada y habrá que volver a intentar. El riesgo en las secuencias 1073741824 es ridículo. En su lugar, muchos clientes deciden limitarse a emitir 100 secuencias simultáneas, con la esperanza de que los servidores sigan la recomendación de la especificación. Cuando los servidores eligen algo por debajo de 100, esta apuesta del cliente falla y las secuencias se reinician.

Hay muchas razones por las que un servidor puede restablecer una secuencia más allá de la superación del límite de concurrencia. HTTP/2 es estricto y exige que se cierre una secuencia cuando se produzcan errores de análisis sintáctico o lógicos. En 2019, Cloudflare desarrolló varias medidas de mitigación en respuesta a las vulnerabilidades DoS de HTTP/2. Varias de esas vulnerabilidades obedecían a un mal comportamiento del cliente, que llevaba al servidor a reiniciar una secuencia. Una estrategia muy eficaz para restringir a esos clientes consiste en contar el número de restablecimientos del servidor durante una conexión y, cuando supera algún valor umbral, cerrar la conexión con una trama GOAWAY. Los clientes legítimos pueden cometer uno o dos errores en una conexión y eso es aceptable. Un cliente que cometa demasiados errores probablemente tenga un problema o sea malintencionado, por lo que el cierre de la conexión aborda ambos casos.

Al responder a los ataques DoS habilitados por CVE-2023-44487, Cloudflare redujo la concurrencia máxima de secuencias a 64. Antes de realizar este cambio, no éramos conscientes de que los clientes no esperan a la trama SETTINGS y, en su lugar, asumen una concurrencia de 100. En efecto, algunas páginas web, como una galería de imágenes, hacen que un navegador envíe 100 solicitudes inmediatamente al inicio de una conexión. Por desgracia, las 36 secuencias que superaban nuestro límite necesitaban restablecerse, lo que activó nuestras medidas de mitigación de recuento. Esta operación implicaba cerrar las conexiones de los clientes legítimos, lo que provocaba un fallo total en la carga de la página. En cuanto nos dimos cuenta de este problema de interoperabilidad, cambiamos la concurrencia máxima de secuencias a 100.

Respuesta de Cloudflare

En 2019 se revelaron varias vulnerabilidades DoS relacionadas con implementaciones de HTTP/2. Cloudflare desarrolló e implementó una serie de detecciones y medidas de mitigación en respuesta.  CVE-2023-44487 es una manifestación diferente de la vulnerabilidad HTTP/2. Sin embargo, para mitigarla pudimos ampliar las protecciones existentes para supervisar las tramas RST_STREAM enviadas por el cliente y cerrar las conexiones cuando se utilizan con fines abusivos. Los usos legítimos de RST_STREAM por parte del cliente no se ven afectados.

Además de una solución directa, hemos implementado varias mejoras en el código de procesamiento de tramas y envío de solicitudes HTTP/2 del servidor. Además, hemos mejorado las colas y la programación del servidor de lógica empresarial para reducir el trabajo innecesario y mejorar la capacidad de respuesta de la anulación. En conjunto, estos avances disminuyen el impacto de varios patrones potenciales de abuso, además de dar más espacio al servidor para procesar las solicitudes antes de que pueda saturarse.

Mitigación previa de los ataques

Cloudflare ya disponía de sistemas para mitigar eficazmente los ataques muy grandes con métodos menos costosos. Uno de ellos se llama “IP Jail”. En los ataques hipervolumétricos, este sistema recoge las direcciones IP de los clientes que participan en el ataque e impide que se conecten a la propiedad que es objeto de ataque, bien a nivel de IP, bien en nuestro proxy TLS. Sin embargo, este sistema necesita unos segundos para ser plenamente eficaz. Durante estos preciados segundos, los servidores de origen ya están protegidos, pero nuestra infraestructura aún tiene que aceptar todas las solicitudes HTTP. Como esta nueva botnet no tiene un periodo de inicialización en la práctica, necesitamos poder neutralizar los ataques antes de que se conviertan en un problema.

Para conseguirlo, hemos ampliado el sistema de IP Jail para proteger toda nuestra infraestructura. Una vez que se “bloquea” una dirección IP, no solo se bloquea su conexión a la propiedad que está siendo blanco de ataque, sino que también prohibimos que las direcciones IP correspondientes utilicen HTTP/2 a cualquier otro dominio en Cloudflare durante un tiempo. Como tales abusos de protocolo no son posibles utilizando HTTP/1.x, este enfoque limita la capacidad del atacante para ejecutar grandes ataques, mientras que cualquier cliente legítimo que comparta la misma dirección IP solo percibirá un leve impacto en rendimiento durante ese tiempo. Las medidas de mitigación basadas en la IP son una herramienta deficiente, por eso debemos ser muy prudentes al utilizarlas a esa escala, y tratar de evitar los falsos positivos en la medida de lo posible. Además, la vida útil de una IP determinada en una botnet suele ser corta, por lo que cualquier medida de mitigación a largo plazo probablemente hará más mal que bien. El siguiente gráfico muestra la rotación de direcciones IP en los ataques que presenciamos:

Como podemos observar, muchas direcciones IP nuevas detectadas en un día determinado desaparecen muy rápido después.

Como todas estas acciones ocurren en nuestro proxy TLS al principio de nuestra canalización HTTPS, se ahorran considerables recursos en comparación con nuestro sistema de mitigación de capa 7 habitual. Esto nos ha permitido aguantar estos ataques mucho mejor y ahora el número de errores 502 aleatorios causados por estas botnets se ha reducido a cero.

Mejoras en la observabilidad

Otro frente en el que estamos implementando cambios es la observabilidad. La devolución de errores a los clientes sin que sean visibles en los análisis de los clientes es insatisfactorio. Afortunadamente, hay un proyecto en marcha para revisar estos sistemas desde mucho antes de estos ataques. Con el tiempo, permitirá que cada servicio de nuestra infraestructura registre sus propios datos, en lugar de depender de nuestro proxy de lógica empresarial para consolidar y emitir datos de registro. Este incidente subrayó la importancia de este trabajo, y estamos redoblando nuestros esfuerzos.

También estamos trabajando en mejorar el registro a nivel de conexión para que nos permita detectar estos abusos de protocolo mucho más rápido y así mejorar nuestras capacidades de mitigación de ataques DDoS.

Conclusión

Aunque este ha sido el último ataque que ha batido récords, sabemos que no será el último. Conforme los ataques se vuelven más sofisticados, Cloudflare trabaja sin descanso para identificar proactivamente nuevas amenazas, implementando contramedidas en nuestra red global para que nuestros millones de clientes estén protegidos de forma inmediata y automática.

Cloudflare ofrece protección DDoS gratuita e ilimitada a todos nuestros clientes desde 2017. Además, ofrecemos una serie de funciones de seguridad adicionales que se adaptan a las necesidades de organizaciones de todos los tamaños. Ponte en contacto con nosotros si no estás seguro de estar protegido o quieres saber cómo puedes estarlo].

Alle Einzelheiten über HTTP/2 Rapid Reset

Post Syndicated from Lucas Pardue original http://blog.cloudflare.com/de-de/technical-breakdown-http2-rapid-reset-ddos-attack-de-de/


Am 25. August 2023 begannen wir, ungewöhnlich große HTTP-Angriffe auf viele unserer Kunden zu bemerken. Diese Angriffe wurden von unserem automatischen DDoS-System erkannt und abgewehrt. Es dauerte jedoch nicht lange, bis sie rekordverdächtige Ausmaße annahmen und schließlich einen Spitzenwert von knapp über 201 Millionen Anfragen pro Sekunde erreichten. Damit waren sie fast dreimal so groß wie der bis zu diesem Zeitpunkt größte Angriff, den wir jemals verzeichnet hatten.

Sie werden angegriffen oder benötigen zusätzlichen Schutz? Klicken Sie hier, um Hilfe zu erhalten.

Besorgniserregend ist die Tatsache, dass der Angreifer in der Lage war, einen solchen Angriff mit einem Botnetz von lediglich 20.000 Rechnern durchzuführen. Es gibt heute Botnetze, die aus Hunderttausenden oder Millionen von Rechnern bestehen. Bedenkt man, dass das gesamte Web in der Regel nur zwischen 1 bis 3 Milliarden Anfragen pro Sekunde verzeichnet, ist es nicht unvorstellbar, dass sich mit dieser Methode quasi die Anzahl aller Anfragen im Internet auf eine kleine Reihe von Zielen konzentrieren ließe.

Erkennen und Abwehren

Dies war ein neuartiger Angriffsvektor in einem noch nie dagewesenen Ausmaß, aber die bestehenden Schutzmechanismen von Cloudflare konnten die Wucht der Angriffe weitgehend bewältigen. Zunächst sahen wir einige Auswirkungen auf den Traffic unserer Kunden – etwa 1 % der Anfragen waren während der ersten Angriffswelle betroffen –, doch heute konnten wir unsere Abwehrmethoden so verfeinern, dass der Angriff für jeden Cloudflare-Kunden gestoppt werden konnte, ohne dass er unsere Systeme beeinträchtigte.

Wir haben diese Angriffe zur gleichen Zeit bemerkt, als zwei andere große Branchenakteure – Google und AWS – dasselbe erlebten. Wir haben daran gearbeitet, die Systeme von Cloudflare zu verstärken, um sicherzustellen, dass alle unsere Kunden heute vor dieser neuen DDoS-Angriffsmethode geschützt sind, ohne dass es Auswirkungen auf die Kunden gibt. Außerdem haben wir gemeinsam mit Google und AWS an einer koordinierten Offenlegung des Angriffs gegenüber den betroffenen Anbietern und Betreibern kritischer Infrastrukturen mitgewirkt.

Dieser Angriff wurde durch den Missbrauch einiger Funktionen des HTTP/2-Protokolls und von Details der Server-Implementierung ermöglicht (siehe  CVE-2023-44487 für Details). Da der Angriff eine zugrundeliegende Sicherheitslücke im HTTP/2-Protokoll ausnutzt, glauben wir, dass jeder Anbieter, der HTTP/2 implementiert hat, dem Angriff ausgesetzt ist. Dazu gehört jeder moderne Webserver. Gemeinsam mit Google und AWS haben wir die Angriffsmethode den Anbietern von Webservern offengelegt, von denen wir erwarten, dass sie Patches implementieren werden. Die beste Schutzmaßnahme ist einstweilen die Verwendung eines DDoS-Abwehrdienstes wie Cloudflare vor jedem Web- oder API-Server, der mit dem Internet verbunden ist.

Dieser Beitrag befasst sich mit allen Einzelheiten zum HTTP/2-Protokoll, der Funktion, die Angreifer ausnutzen, um diese massiven Angriffe zu generieren, und den Abwehrstrategien, die wir ergriffen haben, um sicherzustellen, dass alle unsere Kunden geschützt sind. Wir hoffen, dass durch die Bekanntgabe dieser Details andere betroffene Webserver und -dienste die Informationen erhalten, die sie benötigen, um Abwehrstrategien zum Schutz vor dieser Sicherheitslücke zu implementieren. Darüber hinaus können das Team für die HTTP/2-Protokollstandards sowie die Teams, die an künftigen Webstandards arbeiten, diese besser gestalten, um solche Angriffe zu verhindern.

Nähere Einzelheiten zum RST-Angriff

HTTP ist das Anwendungsprotokoll, auf dem das Web basiert. HTTP Semantics ist allen Versionen von HTTP gemeinsam – die Gesamtarchitektur, Terminologie und Protokollaspekte wie Anfrage- und Antwortnachrichten, Methoden, Statuscodes, Header- und Trailer-Felder, Nachrichteninhalte und vieles mehr. Jede einzelne HTTP-Version definiert, wie die Semantik in ein „Austauschformat“ („wire format“) für den Austausch über das Internet umgewandelt wird. So muss ein Client beispielsweise eine Anfragenachricht in binäre Daten serialisieren und senden, die dann vom Server wieder in eine verarbeitbare Nachricht umgewandelt werden.

HTTP/1.1 verwendet eine textuelle Form der Serialisierung. Anfrage- und Antwortnachrichten werden als Strom von ASCII-Zeichen ausgetauscht, die über eine zuverlässige Transportebene wie TCP unter Verwendung des folgenden Formats (wobei CRLF für Carriage-Return und Linefeed steht) gesendet werden:

 HTTP-message   = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

Eine sehr einfache GET-Anfrage für https://blog.cloudflare.com/ würde beim Austausch zum Beispiel so aussehen:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

Und die Antwort würde so aussehen:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Dieses Format rahmt (Frame)Nachrichten bei der Übertragung ein, was bedeutet, dass es möglich ist, eine einzige TCP-Verbindung für den Austausch mehrerer Anfragen und Antworten zu verwenden. Das Format erfordert jedoch, dass jede Nachricht als Ganzes gesendet wird. Außerdem ist für die korrekte Zuordnung von Anfragen und Antworten eine strikte Reihenfolge erforderlich, d. h. die Nachrichten werden seriell ausgetauscht und können nicht gemultiplext werden. Zwei GET-Anfragen für https://blog.cloudflare.com/ und https://blog.cloudflare.com/page/2/, wären:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLFGET /page/2/ HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

Mit den Antworten:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>CRLFHTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Webseiten erfordern kompliziertere HTTP-Interaktionen als diese Beispiele. Wenn Sie den Cloudflare-Blog besuchen, lädt Ihr Browser mehrere Skripte, Stile und Medieninhalte. Wenn Sie den Cloudflare-Blog besuchen, lädt Ihr Browser mehrere Skripte, Stile und Medieninhalte. Entweder muss man alle in der Warteschlange befindlichen Antworten für die nicht mehr gewünschte Seite abwarten, bevor Seite 2 überhaupt starten kann, oder man bricht laufende Anfragen ab, indem man die TCP-Verbindung schließt und eine neue Verbindung öffnet. Beides ist nicht gerade zweckmäßig. Browser neigen dazu, diese Beschränkungen zu umgehen, indem sie einen Pool von TCP-Verbindungen (bis zu 6 pro Host) verwalten und eine komplexe Logik für den Versand von Anfragen über den Pool implementieren.

HTTP/2 behebt viele der Probleme mit HTTP/1.1. Jede HTTP-Nachricht wird in einen Satz von HTTP/2-Frames serialisiert, die Typ, Länge, Flags, Stream Identifier (ID) und Payload haben. Die Stream-ID macht deutlich, welche Bytes bei der Übertragung zu welcher Nachricht gehören, was sicheres Multiplexing und Gleichzeitigkeit ermöglicht. Streams sind bidirektional. Clients senden Frames und Server antworten mit Frames, die dieselbe ID verwenden.

In HTTP/2 würde unsere GET-Anfrage für https://blog.cloudflare.com über Stream-ID 1 ausgetauscht, wobei der Client einen HEADERS-Frame sendet und der Server mit einem HEADERS-Frame antwortet, gefolgt von einem oder mehreren DATA-Frames. Client-Anfragen verwenden immer ungerade Stream-IDs, sodass nachfolgende Anfragen die Stream-ID 3, 5 usw. verwenden würden. Die Antworten können in beliebiger Reihenfolge gesendet werden, und Frames aus verschiedenen Streams können ineinander verschachtelt werden.

Stream-Multiplexing und Gleichzeitigkeit sind leistungsstarke Funktionen von HTTP/2. Sie ermöglichen eine effizientere Nutzung einer einzigen TCP-Verbindung. HTTP/2 optimiert den Abruf von Ressourcen, insbesondere in Verbindung mit der Priorisierung. Andererseits kann die Erleichterung für Clients, große Mengen an paralleler Arbeit zu starten, den Spitzenbedarf an Serverressourcen im Vergleich zu HTTP/1.1 erhöhen. Dies ist ein naheliegender Vektor für Denial-of-Service.

Um einige Leitlinien bereitzustellen, bietet HTTP/2 einen Begriff für maximal aktive gleichzeitige Streams. Der Parameter SETTINGS_MAX_CONCURRENT_STREAMS ermöglicht es einem Server, sein Limit für die Gleichzeitigkeit bekannt zu geben. Wenn der Server beispielsweise ein Limit von 100 angibt, können zu jedem Zeitpunkt nur 100 Anfragen aktiv sein. Versucht ein Client, einen Stream oberhalb dieser Grenze zu öffnen, muss er vom Server mit einem RST_STREAM-Frame abgelehnt werden. Die Ablehnung eines Streams hat keine Auswirkungen auf die anderen Streams, die sich in der Verbindung befinden.

In Wahrheit ist die Sache ein wenig komplizierter. Streams haben einen Lebenszyklus. Unten sehen Sie ein Diagramm des HTTP/2-Stream-Zustandsrechner. Client und Server verwalten ihre eigenen Ansichten über den Zustand bzw. Status eines Streams. HEADERS-, DATA- und RST_STREAM-Frames lösen Übergänge aus, wenn sie gesendet oder empfangen werden. Obwohl die Ansichten des Stream-Zustands unabhängig sind, werden sie synchronisiert.

HEADERS- und DATA-Frames enthalten ein END_STREAM-Flag, das, wenn es auf den Wert 1 (true) gesetzt ist, einen Übergang des Zustands auslösen kann.

Lassen Sie uns dies anhand eines Beispiels für eine GET-Anfrage ohne Nachrichteninhalt durchgehen. Der Client sendet die Anfrage als HEADERS-Frame, wobei das END_STREAM-Flag auf 1 gesetzt ist. Der Client überführt den Stream zunächst vom Zustand „idle“ in den Zustand „open“ und geht dann sofort in den Zustand „half-closed“ über. Hat der Client den Zustand „half-closed“, bedeutet dies, dass er keine HEADERS oder DATA mehr senden kann, sondern nur noch WINDOW_UPDATE-, PRIORITY- oder RST_STREAM-Frames. Er kann jedoch jeden Frame empfangen.

Sobald der Server den HEADERS-Frame empfängt und analysiert, ändert er den Stream-Zustand von „idle“ zu „open“ und dann zu „half-closed“, damit er mit dem Client übereinstimmt. Der Zustand „half-closed“ bedeutet, dass der Server jeden Frame senden kann, aber nur WINDOW_UPDATE-, PRIORITY- oder RST_STREAM-Frames empfangen kann.

Die Antwort auf die GET-Anfrage enthält Nachrichteninhalte, daher sendet der Server HEADERS mit dem END_STREAM-Flag auf 0, dann DATA mit dem END_STREAM-Flag auf 1. Der DATA-Frame löst auf dem Server den Übergang des Streams von „half-closed“ auf „closed“ aus. Wenn der Client ihn empfängt, geht er ebenfalls in den Zustand „closed“ über. Sobald ein Stream geschlossen ist, können keine Frames mehr gesendet oder empfangen werden.

Wenn man diesen Lebenszyklus zurück in den Kontext der Gleichzeitigkeit überträgt, stellt HTTP/2 fest:

Streams, die sich im Zustand „open“ oder im Zustand „half-closed“ befinden, werden auf die maximale Anzahl von Streams angerechnet, die ein Endpunkt öffnen darf. Streams, die sich in einem dieser drei Zustände befinden, werden auf das in der Einstellung SETTINGS_MAX_CONCURRENT_STREAMS angegebene Limit angerechnet.

Theoretisch ist das Limit für die Gleichzeitigkeit nützlich. Es gibt jedoch praktische Faktoren, die seine Wirksamkeit beeinträchtigen, worauf wir später in diesem Blog eingehen werden.

Widerruf einer HTTP/2-Anfrage

Vorhin haben wir über den Widerruf von gerade in Bearbeitung befindlichen Client-Anfragen gesprochen. HTTP/2 unterstützt dies auf wesentlich effizientere Weise als HTTP/1.1. Anstatt die gesamte Verbindung zu unterbrechen, kann ein Client einen RST_STREAM-Frame für einen einzelnen Stream senden. Dadurch wird der Server angewiesen, die Bearbeitung der Anfrage zu beenden und die Antwort abzubrechen, wodurch Serverressourcen frei werden und keine Bandbreite verschwendet wird.

Betrachten wir unser vorheriges Beispiel mit 3 Anfragen. Dieses Mal widerruft der Client die Anfrage auf Stream 1, nachdem alle HEADERS gesendet wurden. Der Server analysiert diesen RST_STREAM-Frame, bevor er bereit ist, die Antwort zu übermitteln, und antwortet stattdessen nur auf Stream 3 und 5:

Der Widerruf von Anfragen ist eine nützliche Funktion. Beim Scrollen einer Webseite mit mehreren Bildern kann ein Webbrowser beispielsweise Bilder, die außerhalb des Sichtfensters liegen, löschen, sodass Bilder, die in das Sichtfenster gelangen, schneller geladen werden können. HTTP/2 macht dieses Verhalten im Vergleich zu HTTP/1.1 wesentlich effizienter.

Ein widerrufener Anfrage-Stream durchläuft den Lebenszyklus des Streams sehr schnell. Die HEADERS des Clients mit dem auf 1 gesetzten END_STREAM-Flag wechseln den Zustand von „idle“ zu „open“ zu „half-closed“, dann bewirkt RST_STREAM sofort einen Übergang von „half-closed“ zu „closed“.

Erinnern Sie sich, dass nur Streams, die sich im „open“ oder „half-closed“ Zustand befinden, auf das Limit für die Gleichzeitigkeit von Streams angerechnet werden. Wenn ein Client einen Stream abbricht, erhält er sofort die Möglichkeit, an dessen Stelle einen anderen Stream zu öffnen und kann sofort eine weitere Anfrage senden. Genau darum funktioniert CVE-2023-44487.

Schnelles Reset führt zu Denial of Service

Der Widerruf von HTTP/2-Anfragen kann dazu missbraucht werden, eine unbegrenzte Anzahl von Streams schnell zurückzusetzen. Wenn ein HTTP/2-Server in der Lage ist, vom Client gesendete RST_STREAM-Frames zu verarbeiten und den Zustand schnell genug abzubauen, stellen solche schnellen Resets kein Problem dar. Problematisch wird es dann, wenn es bei den Aufräumarbeiten zu Verzögerungen oder Resets kommt.Der Client kann so viele Anfragen stellen, dass sich ein Rückstau bildet, der zu einem übermäßigen Ressourcenverbrauch auf dem Server führt.

Eine gängige HTTP-Bereitstellungsarchitektur besteht darin, einen HTTP/2-Proxy oder Load-Balancer vor anderen Komponenten zu betreiben. Wenn eine Client-Anfrage eintrifft, wird sie schnell abgewickelt und die eigentliche Arbeit wird als asynchrone Aktivität an anderer Stelle erledigt. So kann der Proxy den Client-Traffic sehr effizient verarbeiten. Diese Trennung kann es dem Proxy jedoch erschweren, die in Bearbeitung befindlichen Aufträge aufzuräumen. Daher ist es bei diesen Bereitstellungen wahrscheinlicher, dass es zu Problemen durch schnelle Resets kommt.

Wenn die Reverse-Proxies von Cloudflare eingehenden HTTP/2-Client-Traffic verarbeiten, kopieren sie die Daten aus dem Socket der Verbindung in einen Puffer und verarbeiten diese gepufferten Daten der Reihe nach. Beim Lesen jeder Anfrage (HEADERS- und DATA-Frames) wird diese an einen Upstream-Service weitergeleitet. Wenn RST_STREAM-Frames gelesen werden, wird der lokale Zustand für die Anfrage abgebaut und der vorgelagerte Dienst wird benachrichtigt, dass die Anfrage abgebrochen wurde. Dieser Vorgang wird so lange wiederholt, bis der gesamte Puffer verbraucht ist. Diese Logik kann jedoch missbraucht werden: Wenn ein böswilliger Client eine enorme Kette von Anfragen und Resets zu Beginn einer Verbindung sendet, würden unsere Server sie alle eifrig lesen und die vorgelagerten Server so stark belasten, dass sie keine neuen eingehenden Anfragen mehr verarbeiten können.

Es ist wichtig hervorzuheben, dass die Gleichzeitigkeit von Streams allein das schnelle Reset nicht abwehren kann. Der Client kann Anfragen abwälzen, um hohe Anfrageraten zu erzeugen, unabhängig von dem vom Server gewählten Wert von SETTINGS_MAX_CONCURRENT_STREAMS.

Rapid Reset genau analysiert

Hier ein Beispiel für das Reset anhand eines Proof-of-Concept-Clients, der versucht, insgesamt 1000 Anfragen zu stellen. Ich habe einen handelsüblichen Server ohne jegliche Abwehrmechanismen verwendet, der in einer Testumgebung auf Port 443 lauscht. Der Traffic wurde mit Wireshark analysiert und gefiltert, um nur HTTP/2-Traffic zu zeigen. Jetzt pcap herunterladen, um dem Vorgang zu folgen.

Das ist ein bisschen schwierig zu sehen, weil es viele Bilder gibt. Mit dem Wireshark-Tool Statistik > HTTP2 erhalten wir einen schnellen Überblick:

Der erste Frame in dieser Aufzeichnung, in Paket 14, ist der SETTINGS-Frame des Servers, der eine maximale Anzahl an gleichzeitigen Stream von 100 angibt. In Paket 15 sendet der Client einige Kontrollframes und beginnt dann mit Anfragen, die schnell zurückgesetzt werden. Der erste HEADERS-Frame ist 26 Byte lang, alle folgenden HEADERS sind nur 9 Byte lang. Dieser Größenunterschied ist auf eine Komprimierungstechnologie namens HPACK. zurückzuführen. Insgesamt enthält Paket 15 dabei 525 Anfragen, die bis zum Stream 1051 reichen.

Interessanterweise passt der RST_STREAM für Stream 1051 nicht in Paket 15, so dass der Server in Paket 16 mit einer 404-Antwort antwortet.  In Paket 17 sendet der Client dann das RST_STREAM, bevor er mit dem Senden der restlichen 475 Anfragen fortfährt.

Beachten Sie, dass der Server zwar 100 gleichzeitige Streams ankündigte, die beiden vom Client gesendeten Pakete jedoch viel mehr HEADERS-Frames als diese Zahl enthielten. Der Client musste nicht auf den Antwort-Traffic des Servers warten, er war lediglich durch die Größe der Pakete begrenzt, die er senden konnte. In dieser Aufzeichnung sind keine RST_STREAM-Frames des Servers zu sehen, was darauf hindeutet, dass der Server keinen Verstoß gegen das Limit der Gleichzeitigkeit von Streams festgestellt hat.

Auswirkungen auf Kunden

Wie bereits erwähnt, werden vorgelagerte Dienste benachrichtigt, wenn Anfragen abgebrochen werden, und können diese abbrechen, bevor sie zu viele Ressourcen dafür verschwenden. Dies war bei diesem Angriff der Fall, bei dem die meisten bösartigen Anfragen nie an die Ursprungsserver weitergeleitet wurden. Die schiere Größe dieser Angriffe hatte jedoch einige Auswirkungen.

Erstens erreichten die eingehenden Anfragen höhere Spitzenwerte als jemals zuvor, und die Clients meldeten vermehrt 502-Fehler. Dies geschah in unseren am stärksten betroffenen Rechenzentren, da sie Mühe hatten, alle Anfragen zu verarbeiten. Unser Netzwerk ist zwar für große Angriffe ausgelegt, aber diese spezielle Sicherheitslücke deckte eine Schwäche in unserer Infrastruktur auf. Werfen wir einen genaueren Blick auf die Details, wobei wir uns darauf konzentrieren, wie eingehende Anfragen verarbeitet werden, wenn sie eines unserer Rechenzentren erreichen:

Wir sehen, dass unsere Infrastruktur aus einer Kette verschiedener Proxy-Server mit unterschiedlichen Zuständigkeiten besteht. Wenn sich ein Client mit Cloudflare verbindet, um HTTPS-Traffic zu senden, trifft er zunächst auf unseren TLS-Entschlüsselungs-Proxy: Er entschlüsselt den TLS-Traffic, verarbeitet den HTTP-1-, -2- oder -3-Traffic und leitet ihn dann an unseren Proxy für die „Geschäftslogik“ weiter. Dieser ist dafür zuständig, alle Einstellungen für jeden Kunden zu laden und dann die Anfragen korrekt an andere vorgelagerte Dienste weiterzuleiten – und, was in unserem Fall noch wichtiger ist, er ist auch für die Sicherheitsfunktionen zuständig. Hier wird die L7-Angriffsabwehr abgewickelt.

Das Problem bei diesem Angriffsvektor ist, dass er bei jeder einzelnen Verbindung sehr schnell sehr viele Anfragen senden kann. Jede dieser Anfragen musste an den Proxy für die Geschäftslogik weitergeleitet werden, bevor wir die Möglichkeit hatten, sie zu blockieren. Da der Anfragedurchsatz unsere Proxy-Kapazität überstieg, erreichte die Verbindungsleitung zwischen diesen beiden Diensten bei einigen unserer Server ihre Belastungsgrenze.

Wenn dies geschieht, kann der TLS-Proxy keine Verbindung mehr zu seinem vorgeschalteten Proxy herstellen, weshalb einige Clients bei den schwerwiegendsten Angriffen eine einfache „502 Bad Gateway“-Fehlermeldung erhielten. Es ist wichtig zu beachten, dass die Protokolle, die zur Erstellung von HTTP-Analysen verwendet werden, ab sofort auch von unserem Proxy für die Geschäftslogik ausgegeben werden. Dies hat zur Folge, dass diese Fehler im Cloudflare-Dashboard nicht sichtbar sind. Unsere internen Dashboards zeigen, dass etwa 1 % der Anfragen während der ersten Angriffswelle (bevor wir Abwehrmaßnahmen ergriffen) betroffen waren, mit Spitzenwerten von etwa 12 % für einige Sekunden während der schwerwiegendsten Angriffswelle am 29. August. Das folgende Diagramm zeigt das Verhältnis dieser Fehler über einen Zeitraum von zwei Stunden, in dem dies geschah:

In den darauffolgenden Tagen haben wir hart daran gearbeitet, diese Zahl drastisch zu reduzieren, wie in diesem Beitrag näher erläutert wird. Dank der Änderungen in unserem Stack und unserer Abwehreinrichtungen, die die Größe dieser Angriffe erheblich reduzieren, liegt diese Zahl heute praktisch bei null:

499-Fehler und die Herausforderungen für die Gleichzeitigkeit von HTTP/2-Streams

Ein weiteres Phänomen, von dem einige Kunden berichten, ist die Zunahme von 499.Fehlermeldungen. Die Ursache hierfür ist etwas anders und hängt mit der maximalen Anzahl gleichzeitiger Streams in einer HTTP/2-Verbindung zusammen, die weiter oben in diesem Beitrag beschrieben wurde.

HTTP/2-Einstellungen werden zu Beginn einer Verbindung über SETTINGS-Frames ausgetauscht. Wird kein expliziter Parameter angegeben, gelten die Standardwerte. Sobald ein Client eine HTTP/2-Verbindung aufgebaut hat, kann er auf die SETTINGS eines Servers warten (langsam) oder er kann die Standardwerte annehmen und mit den Anfragen beginnen (schnell). Für SETTINGS_MAX_CONCURRENT_STREAMS ist der Standardwert praktisch unbegrenzt (Stream-IDs verwenden einen 31-Bit-Zahlenraum, und Anfragen verwenden ungerade Zahlen, sodass das tatsächliche Limit bei 1073741824 liegt). In der Spezifikation wird empfohlen, dass ein Server nicht weniger als 100 Streams anbietet. Clients sind in der Regel auf Schnelligkeit bedacht und warten daher nicht auf Servereinstellungen, was zu einer Art Wettlauf führt. Clients wetten darauf, welchen Grenzwert der Server auswählt; wenn sie sich irren, wird die Anfrage abgelehnt und muss erneut gestellt werden. Auf 1073741824 zu wetten ist ein bisschen albern. Stattdessen beschließen viele Clients, sich auf die Ausgabe von 100 gleichzeitigen Streams zu beschränken, in der Hoffnung, dass die Server die empfohlene Spezifikation befolgen. Wenn die Server einen Wert unter 100 wählen, schlägt dieses Client-Ratespiel fehl und die Streams werden zurückgesetzt.

Es gibt viele Gründe, warum ein Server einen Stream bei Überschreitung des Limits für die Anzahl gleichzeitiger Streams zurücksetzen kann. HTTP/2 ist streng und verlangt, dass ein Stream geschlossen wird, wenn Parsing- oder Logikfehler auftreten. 2019 entwickelte Cloudflare mehrere Abwehrmaßnahmen als Reaktion auf HTTP/2 DoS-Schwachstellen. Mehrere dieser Schwachstellen wurden durch das Fehlverhalten eines Clients verursacht, was den Server dazu veranlasste, einen Stream zurückzusetzen. Eine sehr effektive Strategie, um solche Clients einzudämmen, besteht darin, die Anzahl der Server-Resets während einer Verbindung zu zählen und, wenn diese einen bestimmten Schwellenwert überschreitet, die Verbindung mit einem GOAWAY-Frame zu schließen. Legitime Clients machen vielleicht ein oder zwei Fehler während einer Verbindung, und das ist akzeptabel. Ein Client, der zu viele Fehler macht, ist wahrscheinlich entweder defekt oder böswillig; das Schließen der Verbindung ist in beiden Fällen zielführend.

Als Reaktion auf DoS-Angriffe, die durch CVE-2023-44487, ermöglicht wurden, hat Cloudflare die Anzahl der gleichzeitig zugelassenen Streams auf 64 reduziert. Vor dieser Änderung war uns nicht bewusst, dass Clients nicht auf SETTINGS warten und stattdessen für die maximale Anzahl gleichzeitiger Streams 100 annehmen. Einige Webseiten, wie z. B. eine Bildergalerie, veranlassen einen Browser in der Tat dazu, gleich zu Beginn einer Verbindung 100 Anfragen zu senden. Leider mussten die 36 Streams, die über unserem Limit lagen, alle zurückgesetzt werden, was unsere durch Zählung aktivierten Abwehrmaßnahmen auslöste. Das bedeutete, dass wir die Verbindungen von legitimen Clients beendeten, was zu einem kompletten Seitenladefehler führte. Als wir dieses Interoperabilitätsproblem erkannten, änderten wir die maximale Anzahl der gleichzeitig zugelassenen Streams auf 100.

Diese Schritte hat Cloudflare gesetzt

2019 wurden mehrere DoS-Schwachstellen im Zusammenhang mit Implementierungen von HTTP/2 aufgedeckt. Cloudflare hat daraufhin eine Reihe von Erkennungs- und Abwehrmaßnahmen entwickelt und implementiert.  CVE-2023-44487 ist eine andere Ausprägung der HTTP/2-Schwachstelle. Um sie abzuwehren, konnten wir jedoch die bestehenden Schutzmaßnahmen erweitern, um vom Client gesendete RST_STREAM-Frames zu überwachen und Verbindungen zu schließen, wenn sie missbräuchlich verwendet werden. Legitime Client-Nutzungen für RST_STREAM sind davon nicht betroffen.

Neben einer direkten Korrektur haben wir mehrere Verbesserungen an der HTTP/2-Frame-Verarbeitung des Servers und am Code für die Anfragenabwicklung vorgenommen. Darüber hinaus wurden die Warteschlangen und die Scheduling-Funktion des Servers für die Geschäftslogik verbessert, um unnötige Arbeit zu vermeiden und die Reaktionsfähigkeit bei Widerrufen zu verbessern. Dadurch werden die Auswirkungen verschiedener potenzieller Missbrauchsmuster verringert und der Server erhält mehr Raum, um Anfragen zu bearbeiten, bevor er ausgelastet ist.

Angriffe einfacher abwehren

Cloudflare verfügte bereits über Systeme, um sehr große Angriffe mit weniger kostspieligen Methoden effizient abwehren zu können. Eines dieser Systeme heißt „IP Jail“ (weil IPs hier quasi „gefangen genommen“ werden). Bei hypervolumetrischen Angriffen sammelt dieses System die am Angriff beteiligten Client-IPs und verhindert, dass sie sich mit dem angegriffenen Objekt verbinden, entweder auf IP-Ebene oder in unserem TLS-Proxy. Dieses System benötigt jedoch einige Sekunden, um seine volle Wirkung zu entfalten; während dieser kostbaren Sekunden sind die Ursprünge bereits geschützt, aber unsere Infrastruktur muss immer noch alle HTTP-Anfragen aufnehmen. Da dieses neue Botnetz praktisch keine Anlaufzeit hat, müssen wir Angriffe neutralisieren können, bevor sie zu einem Problem werden können.

Zu diesem Zweck haben wir das IP-Jail-System erweitert, um unsere gesamte Infrastruktur zu schützen: Sobald eine IP darin „gefangen“ ist, kann sie sich nicht nur nicht mehr mit der angegriffenen Domain verbinden, sondern wir verbieten den entsprechenden IPs für einige Zeit auch die Nutzung von HTTP/2 für jede andere auf Cloudflare gehostete Domain. Da derartige Protokollmissbräuche mit HTTP/1.x nicht möglich sind, schränkt dies die Möglichkeiten des Angreifers ein, groß angelegte Angriffe auszuführen, während ein legitimer Client, der dieselbe IP-Adresse nutzt, in dieser Zeit nur einen sehr geringen Performance-Verlust erleiden würde. IP-basierte Abwehrmaßnahmen sind ein sehr hartes Mittel – deshalb müssen wir bei ihrem Einsatz in diesem Ausmaß äußerst vorsichtig sein und versuchen, Fehlalarme so weit wie möglich zu vermeiden. Außerdem ist die Lebensdauer einer bestimmten IP in einem Botnetz in der Regel kurz, so dass jede langfristige Abwehrmaßnahme wahrscheinlich mehr schadet als nützt. Die folgende Grafik zeigt den Wechsel der IPs bei den von uns beobachteten Angriffen:

Wir sehen: Viele neue IPs, die an einem bestimmten Tag entdeckt werden, verschwinden sehr schnell wieder.

Da alle diese Aktionen in unserem TLS-Proxy am Anfang unserer HTTPS-Pipeline stattfinden, spart dies im Vergleich zu unserem regulären L7-Abwehrsystem erhebliche Ressourcen. Dadurch konnten wir diese Angriffe viel besser abwehren, und die Zahl der zufälligen 502-Fehler, die von diesen Botnetzen verursacht werden, ist jetzt auf null gesunken.

Verbesserungen der Beobachtbarkeit

Auch im Bereich der Beobachtbarkeit nehmen wir Veränderungen vor. Es ist nicht zufriedenstellend, wenn Clients Fehler erhalten, ohne dass diese in der Kundenanalyse sichtbar sind. Glücklicherweise wurde bereits lange vor den jüngsten Angriffen ein Projekt zur Überarbeitung dieser Systeme eingeleitet. Damit kann jeder Dienst innerhalb unserer Infrastruktur seine eigenen Daten protokollieren, anstatt sich auf unseren Proxy für die Geschäftslogik zu verlassen, der die Protokolldaten konsolidiert und ausgibt. Dieser Vorfall hat gezeigt, wie wichtig diese Arbeit ist, und wir intensivieren unsere Bemühungen.

Wir arbeiten auch an einer besseren Protokollierung auf Verbindungsebene, damit wir solche Protokollmissbräuche viel schneller erkennen und unsere Fähigkeiten zur DDoS-Abwehr verbessern können.

Fazit

Auch wenn dies der jüngste rekordverdächtige Angriff war, wissen wir, dass es nicht der letzte sein wird. Die Angriffe werden immer raffinierter. Darum arbeiten wir bei Cloudflare unermüdlich daran, neue Bedrohungen proaktiv zu identifizieren und Gegenmaßnahmen in unserem globalen Netzwerk zu implementieren, damit unsere Millionen von Kunden sofort und automatisch geschützt sind.

Seit 2017 bietet Cloudflare allen Kunden kostenlosen und zeitlich unbefristeten DDoS-Schutz ohne Volumensbegrenzung. Darüber hinaus bieten wir eine Reihe zusätzlicher Sicherheitsfunktionen, die den Bedürfnissen von Unternehmen jeder Größe entsprechen. Kontaktieren Sie uns, wenn Sie sich nicht sicher sind, ob Sie geschützt sind, oder wenn Sie wissen möchten, wie Sie sich schützen können.

L'exploitation de la vulnérabilité zero-day HTTP/2 entraîne des attaques DDoS record

Post Syndicated from Grant Bourzikas original http://blog.cloudflare.com/fr-fr/zero-day-rapid-reset-http2-record-breaking-ddos-attack-fr-fr/


Plus tôt aujourd’hui, Cloudflare, Google et Amazon AWS ont révélé l’existence d’une nouvelle vulnérabilité zero-day, baptisée « HTTP/2 Rapid Reset ». Cette attaque exploite une faiblesse du protocole HTTP/2 afin de lancer d’immenses attaques hyper-volumétriques par déni de service distribué (DDoS). Au cours des derniers mois, Cloudflare a atténué un véritable barrage d’attaques de ce type, notamment une attaque trois fois plus importante que toutes les attaques que nous avions précédemment observées, qui a dépassé 201 millions de requêtes par seconde (r/s). Depuis la fin du mois d’août 2023, Cloudflare a atténué plus de 1 100 autres attaques dépassant 10 millions de r/s, dont 184 attaques plus vastes que la précédente attaque DDoS record que nous avions observée, de 71 millions de r/s.

Vous êtes victime d’une attaque ou avez besoin d’une protection supplémentaire ? Cliquez ici pour demander de l’aide.

Cette attaque zero-day a fourni aux acteurs malveillants un nouvel outil essentiel sur leur couteau suisse d’exploitations de vulnérabilités, leur permettant de lancer contre leurs victimes des attaques d’une ampleur encore jamais observée. Bien qu’elles soient parfois complexes et difficiles à combattre, ces attaques ont permis à Cloudflare de développer une technologie spécifique, permettant d’atténuer les effets de cette vulnérabilité zero-day.

Si vous utilisez Cloudflare pour l’atténuation des attaques DDoS HTTP, vous êtes protégé. Vous trouverez ci-dessous plus d’informations sur cette vulnérabilité, ainsi que des ressources et des recommandations sur les dispositions que vous pouvez prendre pour garantir votre sécurité.

Déconstruction de l’attaque : ce que chaque directeur de la sécurité doit savoir

Fin août 2023, l’équipe de Cloudflare a remarqué une nouvelle vulnérabilité zero-day, développée par un acteur malveillant inconnu, qui exploite le protocole standard HTTP/2 – un protocole fondamental, essentiel au fonctionnement d’Internet et de tous les sites web. Cette nouvelle attaque zero-day, baptisée Rapid Reset, exploite la fonction d’annulation de flux du protocole HTTP/2 en transmettant une requête, puis en l’annulant immédiatement, encore et encore.  

En automatisant à grande échelle ce schéma trivial (« requête, annulation, requête, annulation »), les acteurs malveillants parviennent à provoquer un déni de service, et ainsi, à entraîner l’arrêt de n’importe quel serveur ou application utilisant l’implémentation standard du protocole HTTP/2. Par ailleurs, il est important de noter que cette attaque record a été lancée avec un botnet de taille modeste, constitué d’environ 20 000 machines. Cloudflare détecte régulièrement des botnets d’une taille bien supérieure, comptant des centaines de milliers, voire des millions de machines. Le fait qu’un botnet de taille relativement moindre puisse générer un tel volume de requêtes, offrant la possibilité de neutraliser pratiquement tous les serveurs ou applications prenant en charge le protocole HTTP/2, souligne la gravité de la menace que représente cette vulnérabilité pour les réseaux non protégés.

Les acteurs malveillants ont utilisé des botnets conjointement à la vulnérabilité du protocole HTTP/2 afin d’amplifier les requêtes à des taux encore jamais observés. Suite à cette attaque, l’équipe de Cloudflare a observé des phénomènes d’instabilité intermittente à la périphérie du réseau. Bien que nos systèmes aient été en mesure d’atténuer l’immense majorité des attaques entrantes, le volume a surchargé certains composants de notre réseau, entraînant une altération des performances pour un petit nombre de clients, qui ont constaté des erreurs 4xx et 5xx intermittentes ; toutes ont été rapidement résolues.

Lorsque nous sommes parvenus à atténuer ces problèmes et à mettre fin aux attaques potentielles pour l’ensemble des clients, notre équipe a immédiatement lancé une procédure de divulgation responsable. Nous avons commencé à échanger avec des homologues de l’industrie afin d’évaluer comment nous pourrions coopérer pour préserver la continuité de notre mission et protéger l’importante proportion d’Internet reposant sur notre réseau, avant de divulguer cette vulnérabilité au grand public.

Nous couvrons les aspects techniques détaillés de l’attaque dans un article de blog distinct : HTTP/2 Rapid Reset : anatomie de l’attaque record.

Comment Cloudflare et l’industrie déjouent-ils cette attaque ?

Il n’existe pas de « divulgation parfaite ». Pour déjouer les attaques et réagir aux nouveaux incidents, les entreprises et les équipes de sécurité doivent adopter un état d’esprit supposant l’existence d’une violation : il existera toujours une nouvelle vulnérabilité zero-day, des groupes d’acteurs malveillants nouveaux et changeants et des attaques et des techniques inédites.

Cet état d’esprit consistant à supposer l’existence d’une violation constitue une fondation essentielle pour la diffusion d’informations et pour garantir, dans des situations telles que celle-ci, que l’Internet demeure sûr. Pendant que Cloudflare subissait et atténuait ces attaques, nous travaillions également avec des partenaires de l’industrie afin de garantir que cette dernière serait, dans son ensemble, capable de résister à cette attaque.  

Durant le processus d’atténuation de l’attaque, l’équipe de Cloudflare a développé une nouvelle technologie dédiée permettant d’arrêter ces attaques DDoS et d’améliorer encore nos mesures d’atténuation de cette attaque et d’autres futures attaques de très grande ampleur. Ces efforts ont considérablement amélioré nos capacités globales d’atténuation, ainsi que notre résilience. Si vous utilisez Cloudflare, nous pouvons vous assurer que vous êtes protégé.

Notre équipe a également alerté les partenaires développant les logiciels pour serveurs web, qui élaborent actuellement des correctifs afin d’assurer que cette vulnérabilité ne pourra pas être exploitée ; nous vous invitons à consulter leurs sites web pour plus d’informations.

Les divulgations ne sont jamais définitivement terminées. La raison d’être de Cloudflare est d’assurer un Internet meilleur, qui découle de situations telles que celle-ci. Lorsque nous avons l’occasion de coopérer avec les entreprises partenaires de l’industrie et les administrations afin d’assurer l’absence d’impacts généralisés pour l’ensemble d’Internet, nous contribuons à améliorer la cyber-résilience de chaque entreprise, quelle que soit sa taille ou son secteur d’activité.

Pour mieux comprendre les tactiques d’atténuation et les prochaines étapes de la mise en œuvre des correctifs, inscrivez-vous à notre webinaire.

Quelles sont les origines de l’attaque HTTP/2 Rapid Reset et de ces attaques record lancées contre Cloudflare ?

Il peut paraître étrange que Cloudflare ait été l’une des premières entreprises à observer ces attaques. Pourquoi des acteurs malveillants s’en prendraient-ils à une entreprise dont les systèmes de défense contre les attaques DDoS figurent parmi les plus robustes du monde ?  

En réalité, Cloudflare a souvent l’occasion d’observer des attaques avant qu’elles ne soient lancées contre des cibles plus vulnérables. Les acteurs malveillants doivent développer et tester leurs outils avant de les déployer « dans la nature ». Les acteurs malveillants qui détiennent des méthodes permettant de lancer des attaques record peuvent se heurter à d’importantes difficultés pour tester et comprendre l’ampleur et l’efficacité de leurs méthodes, car ils ne disposent pas de l’infrastructure nécessaire pour absorber les attaques qu’ils lancent. La transparence avec laquelle nous partageons les performances de notre réseau et les mesures des attaques présentées sur les graphiques de performances que nous diffusons publiquement ont vraisemblablement incité à ces acteurs malveillants à nous cibler afin de mieux comprendre les capacités de cette exploitation de vulnérabilité.

Toutefois, ces tests et la capacité de détecter précocement l’attaque nous aident à élaborer des mesures d’atténuation qui profitent à la fois à nos clients et à l’industrie dans son ensemble.

D’un directeur de la sécurité à un autre : que devez-vous faire ?

Je suis directeur de la sécurité depuis plus de 20 ans, durant lesquels j’ai été le destinataire d’innombrables divulgations et annonces semblables à celle-ci. Toutefois, qu’il s’agisse de Log4J, de Solarwinds, d’EternalBlue WannaCry/NotPetya, de Heartbleed ou de Shellshock, tous ces incidents de sécurité ont un point commun : celui de provoquer une explosion colossale, qui se répercutait dans le monde entier, offrant l’opportunité de perturber profondément toutes les entreprises que j’ai dirigées, quel que soit leur secteur d’activité ou leur taille.

Il s’agissait, dans de nombreux cas, d’attaques ou de vulnérabilités que nous n’avons pas été en mesure de maîtriser. Indépendamment de l’origine du problème, qu’il soit ou non imputable à un paramètre qui échappait à mon contrôle, ce qui a toujours distingué les initiatives couronnées de succès de celles dont l’issue nous a été défavorable, c’est la capacité de réagir lorsque des vulnérabilités zero-day et des exploitations de vulnérabilités telles que celle-ci sont identifiées.    

J’aimerais pouvoir dire que cette fois, l’attaque HTTP/2 Rapid Reset sera peut-être différente, mais ce n’est pas le cas. J’adresse ce message à tous les directeurs de la sécurité – que vous ayez, comme moi, l’expérience de décennies d’incidents de sécurité ou que ce soit votre premier jour à votre poste : le moment est venu de vous assurer d’être protégé et de mobiliser votre équipe de réponse aux cyber-incidents.

Nous avons préservé la confidentialité de l’information jusqu’à aujourd’hui, afin de laisser au plus grand nombre possible de fournisseurs de solutions de sécurité l’opportunité de réagir. À un moment donné, toutefois, l’approche responsable consiste à divulguer publiquement l’existence d’une menace zero-day comme celle-ci, et c’est aujourd’hui que nous devons le faire.Cela signifie qu’à partir d’aujourd’hui, les acteurs malveillants seront largement informés de l’existence de la vulnérabilité HTTP/2, et qu’il deviendra inévitablement facile de l’exploiter. Cela donnera le coup d’envoi d’une course entre défenseurs et acteurs malveillants : les premiers à appliquer un correctif contre les premiers à exploiter la vulnérabilité. Les entreprises doivent partir du principe que leurs systèmes seront testés et doivent prendre des mesures proactives afin d’assurer leur protection.

Cette situation me rappelle une vulnérabilité comme Log4J, en raison des nombreuses variantes qui apparaissent chaque jour et qui continueront à être finalisées au cours des semaines, des mois et des années à venir. À mesure que les chercheurs et les acteurs malveillants testent cette vulnérabilité, nous identifierons peut-être différentes variantes, avec des cycles d’exploitation de vulnérabilité encore plus courts, comportant des méthodes de contournement encore plus avancées.  

Et à l’instar de Log4J, la gestion de ce type d’incidents est complexe et exige bien plus que la simple exécution d’un correctif.Vous devez transformer la gestion de l’incident, l’application des correctifs et l’amélioration de vos protections de sécurité en processus continus ; en effet, si les correctifs correspondant à chaque variante d’une vulnérabilité permettent d’atténuer le risque, ils ne l’éliminent pas pour autant.

Je ne veux pas être alarmiste, mais je serai direct : vous devez prendre cette menace au sérieux. Considérez-la comme un incident actif à part entière, afin de vous assurer qu’aucune conséquence délétère n’affectera votre entreprise.

Recommandations pour une nouvelle norme en matière de gestion du changement

Bien qu’aucun événement de sécurité ne soit jamais identique à un autre, il est possible d’en tirer des enseignements. Aussi, aux directeurs de la sécurité, voici mes recommandations, que je vous invite à mettre en œuvre immédiatement ;pas uniquement dans cette situation, mais dans les années à venir :

  • Comprenez la connectivité externe de votre réseau et de celui de vos partenaires afin de contenir les menaces liées à tout système accessible depuis Internet, grâce aux mesures d’atténuation ci-dessous.
  • Comprenez vos dispositifs existants de protection de la sécurité, ainsi que les capacités dont vous disposez pour protéger, détecter et réagir à une attaque, et remédiez immédiatement à tous les incidents observés sur votre réseau.
  • Assurez-vous que votre solution de protection contre les attaques DDoS réside hors de votre datacenter, car si le trafic parvient à votre datacenter, il sera difficile d’atténuer l’attaque DDoS.
  • Assurez-vous de disposer d’une protection contre les attaques DDoS pour les applications (couche 7) et de pare-feu d’applications web. En outre, une bonne pratique consiste à vous assurer de disposer d’une protection complète contre les attaques DDoS pour le DNS, le trafic réseau (couche 3) et les pare-feu d’API.
  • Veillez à déployer des correctifs pour votre serveur web et votre système d’exploitation sur l’ensemble des serveurs web accessibles depuis Internet. Assurez-vous également que tous les systèmes d’automatisation, tels que les versions et images Terraform, aient reçu tous les correctifs nécessaires, afin que d’anciennes versions des serveurs web ne soient pas accidentellement déployées en production par le biais d’images sécurisées.
  • En dernier recours, envisagez de désactiver HTTP/2 et HTTP/3 (probablement vulnérable, lui aussi) afin d’atténuer la menace. Il s’agit d’une solution de dernier recours, car l’utilisation de HTTP/1.1 entraînera d’importants problèmes de performances.
  • Envisagez de faire appel à un fournisseur secondaire de services cloud de protection contre les attaques DDoS sur la couche 7, au niveau du périmètre, afin d’assurer la résilience.

Cloudflare s’est donné pour mission de contribuer à bâtir un Internet meilleur. Si vous êtes préoccupé par l’état actuel de votre protection contre les attaques DDoS, nous serons ravis de vous fournir gratuitement nos capacités de protection contre les attaques DDoS et notre résilience, afin d’atténuer toute tentative d’attaque de ce type. Nous sommes conscients du stress auquel vous devez faire face, car nous avons repoussé ces attaques au cours des 30 derniers jours et nous avons encore amélioré nos systèmes, déjà inégalés dans leur catégorie.

Si vous souhaitez en savoir plus, regardez notre webinaire expliquant les détails de la vulnérabilité zero-day et comment vous devez réagir à celle-ci. Contactez-nous si vous n’êtes pas sûr d’être protégé ou vous souhaitez comprendre comment vous pouvez l’être. Nous présentons également des informations techniques plus détaillées sur l’attaque dans un article de blog distinct : HTTP/2 Rapid Reset : anatomie de l’attaque record. Enfin, si vous êtes la cible d’une attaque ou si vous avez besoin d’une protection immédiate, veuillez contacter votre représentant Cloudflare local ou consulter la page https://www.cloudflare.com/fr-fr/under-attack-hotline/.

HTTP/2 Rapid Reset:解構破紀錄的攻擊

Post Syndicated from Lucas Pardue original http://blog.cloudflare.com/zh-tw/technical-breakdown-http2-rapid-reset-ddos-attack-zh-tw/


自 2023 年 8 月 25 日起,我們開始注意到很多客戶遭受到一些異常大型的 HTTP 攻擊。我們的自動化 DDoS 系統偵測到這些攻擊並加以緩解。但是,沒過多久,它們就開始達到破紀錄的規模,峰值最終剛好超過每秒 2.01 億次請求。這幾乎是之前記錄在案的最大規模攻擊的 3 倍。

正在遭受攻擊或需要額外保護?請按一下這裡以取得幫助。

而更加深入後發現,攻擊者能夠利用僅由 20,000 台機器組成的 Botnet 發起此類攻擊,而如今的 Botnet 規模可達數十萬或數百萬台機器。整個 web 網路通常每秒處理 10-30 億個請求,因此使用此方法可以將整個 web 網路的請求數量等級集中在少數目標上,而其實是可以達成的。

偵測和緩解

這是一種規模空前的新型攻擊手段,但 Cloudflare 的現有保護主要能夠吸收攻擊的壓力。我們一開始就注意到一些客戶流量影響 (在第一波攻擊期間約影響 1% 的請求); 如今,我們仍在持續改善緩解方法,以阻止對任何 Cloudflare 客戶發動的攻擊,而且不會影響我們的系統。

我們注意到這些攻擊,同時也有其他兩家主流的業內廠商(Google 和 AWS)發現相同的狀況。我們竭力強化 Cloudflare 的系統,以確保現今所有客戶都能免於此新型 DDoS 攻擊方法的侵害,而且沒有任何客戶受到影響。我們還與 Googel 和 AWS 合作,協調披露受影響廠商和關鍵基礎架構提供者遭受的攻擊。

此攻擊是透過濫用 HTTP/2 通訊協定部分功能和伺服器實作詳細資料才得以發動(請參閱 CVE-2023-44487 瞭解詳細資料)。因為攻擊會濫用 HTTP/2 通訊協定中的潛在弱點,所以我們認為任何實作 HTTP/2 的廠商都會遭受攻擊。這包括每部現代 Web 伺服器。我們與 Google 和 AWS 已經將攻擊方法披露給預期將實作修補程式的 Web 伺服器廠商。在這段期間,最佳防禦就是針對任何面向 Web 的網頁或 API 伺服器使用 DDoS 緩解服務(例如 Cloudflare)。

本文將深入探討 HTTP/2 通訊協定、攻擊者用於發動這些大規模攻擊的功能,以及我們為確保所有客戶均受到保護而採取的緩解策略。我們希望在發布這些詳細資料後,其他受影響的 Web 伺服器和服務即可取得實施緩解策略所需的資訊。此外,HTTP/2 通訊協定標準團隊和未來 Web 標準制定團隊,都能進一步設計出預防此類攻擊的功能。

RST 攻擊詳細資料

HTTP 是支援 Web 的應用程式通訊協定。HTTP 語意為所有版本的 HTTP 所共用;整體架構、術語及通訊協定方面,例如請求和回應訊息、方法、狀態碼、標頭和後端項目欄位、訊息內容等等。每個 HTTP 版本將定義如何將語意轉化為「有線格式」以透過網際網路交換。例如,客戶必須將請求訊息序列化為二進位資料並進行傳送,接著伺服器會將其剖析回可處理的訊息。

HTTP/1.1 採用文字形式的序列化。請求和回應訊息交換為 ASCII 字元串流,透過 TCP 等可靠的傳輸層傳送,並使用下列格式(其中的 CRLF 表示斷行和換行):

 HTTP-message   = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

例如,對 https://blog.cloudflare.com/ 非常簡單的 GET 請求在網路上看起來像這樣:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

回應如下所示:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

此格式框住網路上的訊息,表示可使用單一 TCP 連線來交換多個請求和回應。但是,該格式要求完整傳送每則訊息。此外,為使請求與回應正確關聯,需要嚴格排序;表示訊息會依次交換且無法多工處理。以下是 https://blog.cloudflare.com/ 和 https://blog.cloudflare.com/page/2/ 的兩個 GET 請求:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLFGET /page/2/ HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

回應如下:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>CRLFHTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

比起這些範例,網頁需要更複雜的 HTTP 互動。造訪 Cloudflare 部落格時,您的瀏覽器會載入多個指令碼、樣式及媒體資產。如果您使用 HTTP/1.1 造訪首頁並決定瀏覽至第 2 頁,則瀏覽器可從兩個選項中任選。在第 2 頁還無法開始前,將您不再需要的頁面等待所有排入佇列的回應,或者關閉 TCP 連線並開啟新連線以取消處理中的請求。這些都不是非常實用。瀏覽器通常會管理 TCP 連線集區(每個主機最多 6 個),然後在集區上實作複雜的請求分派邏輯,藉此解決這些限制。

HTTP/2 解決了許多 HTTP/1.1 的問題。每個 HTTP 訊息會序列化為一組具有類型、長度、標誌、串流識別碼 (ID) 及負載的 HTTP/2 框架。串流 ID 明確說明了網路上的哪個位元組適用於哪個訊息,並允許安全的多工處理和並行處理。串流具有雙向特性。用戶端會使用相同 ID 來傳送框架和具有框架的伺服器回應。

在 HTTP/2 中,https://blog.cloudflare.com 的 GET 請求會跨 Stream ID 1 交換,其中用戶端傳送一個 HEADERS 框架,伺服器則回應一個 HEADERS 框架,接著是一個或多個 DATA 框架。用戶端請求一律使用奇數的 Stream ID,因此後續請求會使用 Stream ID 3、5 等等。回應可以是任何順序,而且不同串流的框架可以交錯。

Stream 多工處理和並行處理是 HTTP/2 的強大功能。它們可更有效地使用單一 TCP 連線。HTTP/2 將資源最佳化,特別是搭配優先順序時擷取的資源。另一方面,與 HTTP/1.1 相比,讓用戶端輕鬆啟動大量平行工作,可能會增加伺服器資源的尖峰需求。這是阻斷服務的明顯手段。

為建立一些防護機制,HTTP/2 提供最大作用中並行串流的概念。SETTINGS_MAX_CONCURRENT_STREAMS 參數允許伺服器宣告其並行處理限制。例如,如果伺服器指出 100 的限制,則任何時間都只會有 100 個作用中請求。如果用戶端嘗試開啟超過此限制的串流,則須由使用 RST_STREAM 框架的伺服器拒絕。串流拒絕不會影響連線上的其他處理中串流。

實際情況會更複雜一點。串流具有生命週期。以下是 HTTP/2 串流狀態機器的圖表。用戶端和伺服器會管理自己的串流狀態檢視。HEADERS、DATA 及 RST_STREAM 框架會在傳送或接收時觸發轉換。雖然串流狀態可獨立檢視,但已完成同步。

HEADERS 和 DATA 框架包括 END_STREAM 標誌,在設定為數值 1 (true) 時,可觸發狀態轉換。

讓我們利用無訊息內容的 GET 請求範例來逐步解決此狀況。用戶端會在具有 END_STREAM 標誌的 HEADERS 框架設定為 1 時傳送請求。用戶端首先會將串流狀態從閒置轉換為開啟狀態,然後立即轉換為半關閉狀態。用戶端半關閉狀態表示無法再傳送 HEADERS 或 DATA,只會傳送 WINDOW_UPDATE、PRIORITY 或 RST_STREAM 框架,但是可接收任何框架。

伺服器接收並剖析 HEADERS 框架後,即會將串流狀態從閒置轉換為開啟及半關閉,以便與用戶端相符。伺服器半關閉狀態表示可傳送任何框架,但只會接收 WINDOW_UPDATE、PRIORITY 或 RST_STREAM 框架。

GET 回應包含訊息內容,因此伺服器傳送 HEADERS 時 END_STREAM 標誌設定為 0,傳送 DATA 時 END_STREAM 標誌設定為 1。DATA 框架會在伺服器上觸發從半關閉到關閉的串流轉換。當用戶端接收時,也會轉換為關閉。串流關閉後,無法傳送或接收任何框架。

將此生命週期套用回並行處理背景後,HTTP/2 指出:

處於「開啟」狀態或「半關閉」狀態的串流會計入允許端點開啟的最大串流數。這些狀態中的串流會計入在 SETTINGS_MAX_CONCURRENT_STREAMS 設定中宣告的限制。

理論上,並行處理限制很實用。但還是有阻礙其效率的實際因素,我們稍後將在部落格中介紹。

HTTP/2 請求取消

之前,我們介紹了處理中請求的用戶端取消。與 HTTP/1.1 相比,HTTP/2 支援這項作業的方式更有效率。不需要斷開整個連線,用戶端即可傳送單一串流的 RST_STREAM 框架。這會指示伺服器停止處理請求和中止回應,進而釋放伺服器資源及避免浪費頻寬。

我們來考量一下先前 3 個請求範例。這次用戶端在所有 HEADERS 傳送完畢後取消了串流 1 上的請求。伺服器則會在準備提供回應前剖析此 RST_STREAM 框架,轉而僅回應串流 3 和 5:

請求取消是實用的功能。例如,捲動具有多張影像的網頁時,Web 瀏覽器可以取消檢視區以外的影像,表示影像進入該區後的載入速度更快。比起 HTTP/1.1,HTTP/2 讓這個行為變得更有效率。

取消的請求串流會在整個串流生命週期中轉換。用戶端的 HEADERS 在 END_STREAM 標誌設定為 1 時,狀態會從閒置轉換到開啟和半關閉,然後 RST_STREAM 會立即產生半關閉到關閉的轉換。

回想一下,只有開啟或半開放狀態的串流會造成串流並行處理限制。當用戶端取消串流時,才能在其位置中開啟另一個串流,而且可以立即傳送另一個請求。這是 CVE-2023-44487 得以運作的關鍵。

導致阻斷服務的快速重設

HTTP/2 請求取消可能被濫用來快速重設無數串流。當 HTTP/2 伺服器處理用戶端傳送之 RST_STREAM 框架及斷開狀態的速度夠快時,此類快速重設就不會造成問題。當整理作業有任何種類的延遲或延滯時,問題就會開始突然出現。用戶端可能會處理太多因工作積壓而累積的請求,導致伺服器上的資源過度消耗。

常見的 HTTP 部署架構是在其他元件前執行 HTTP/2 Proxy 或負載平衡器。用戶端請求到達時即會快速分派,而且實際工作在其他位置以非同步活動完成。這可讓 Proxy 非常高效地處理用戶端流量。但是,此關注點分離會讓 Proxy 難以整理進行中的工作。因此,這些部署更有可能遇到快速重設造成的問題。

當 Cloudflare 的反向 Proxy 處理傳入的 HTTP/2 用戶端流量時,它們會將連線通訊端的資料複製到依序緩衝資料的緩衝區和程序。讀取每個請求時(HEADERS 和 DATA 框架),即會分派至上游服務。讀取 RST_STREAM 框架時,即會卸除請求的本機狀態並通知上游已取消該請求。重複該程序直到消耗掉整個緩衝區。但是,此邏輯可能被濫用:當惡意用戶端在連線初期開始傳送大型請求和重設鏈時,我們的伺服器會迫不急待讀取所有內容並在上游伺服器上建立壓力,直到能夠處理任何新的傳入請求為止。

特別強調一點,串流並行處理無法自行緩解快速重設。用戶端可以處理請求以建立高請求率,無論伺服器的 SETTINGS_MAX_CONCURRENT_STREAMS 選定值為何。

Rapid Reset 詳細分析

以下範例為使用嘗試提出共計 1,000 個請求的概念驗證用戶端來重現的 Rapid Reset。我使用了現成伺服器且沒有任何緩解措施;在測試環境中接聽連接埠 443。已使用 Wireshark 詳細分析流量並經過篩選,且為了清楚起見,僅顯示 HTTP/2 流量。下載該 pcap 以遵循。

由於框架太多,有點難看到。我們可以透過 Wireshark 統計資料 > HTTP2 工具取得快速摘要:

在封包 14 中,此追蹤的第一個框架為伺服器的 SETTINGS 框架,其宣告 100 的串流並行處理上限。在封包 15 中,用戶端會傳送一些控制框架並開始提出快速重設的請求。第一個 HEADERS 框架長度為 26 個位元組,所有後續的 HEADERS 則只有 9 個位元組。名稱為 HPACK 的壓縮技術造成了這項大小差異。封包 15 共包含 525 個請求,並往上至串流 1051。

有趣的是,串流 1051 的 RST_STREAM 不適合封包 15,所以我們在封包 16 看到了 404 回應的伺服器回應。接著在封包 17 中,用戶端的確傳送了 RST_STREAM,然後繼續傳送剩餘的 475 個請求。

請注意,雖然伺服器宣告了 100 個並行串流,用戶端傳送的封包還傳送了數量更多的 HEADERS 框架。用戶端不必等待任何從伺服器傳回的流量,唯一限制為可傳送的封包大小。此追蹤沒有任何伺服器 RST_STREAM 框架,表明伺服器並未觀察到並行的串流違規事件。

對客戶的影響

如上所述,取消請求時即會通知上游服務,而且可能在浪費太多資源前中止請求。這是此次攻擊的情況,其中大多數的惡意請求從未轉傳至原始伺服器。但是,這些攻擊的龐大規模並未造成一些影響。

首先,隨著傳入請求率達到前所未有的峰值,我們收到了用戶端所發現 502 錯誤數量漸增的報告。這發生在我們受影響程度最大的資料中心,目前正努力處理所有請求。雖然我們的網路旨在處理大型攻擊,這項特殊漏洞還是暴露了我們基礎架構中的弱點。我們來進一步探討細節,並將重點放在傳入請求到達我們其中一個資料中心時如何受到處理:

我們可以看到基礎架構由責任不同的各種 Proxy 伺服器組成。特別是,當用戶端連線至 Cloudflare 以傳送 HTTPS 流量時,會先到達我們的 TLS 解密 Proxy:可解密 TLS 流量、處理 HTTP 1、2 或 3 流量,然後將其轉傳至「商務邏輯」Proxy。這會負責為每個客戶載入所有設定,然後將請求正確路由至其他上游服務;在我們案例中更重要的是,這也會負責安全功能。此時會處理 L7 攻擊緩解。

此攻擊手段的問題是,它有辦法非常快速地在每一次連線中傳送大量請求。每個請求都必須轉傳至商務邏輯 Proxy,我們才有機會加以封鎖。隨著請求輸送量變得比我們的 Proxy 容量還要高,連線這兩項服務的管道在部分伺服器中都達到了其飽和程度。

此情況發生時,TLS Proxy 即無法再連線至它的上游 Proxy,因此在大多數嚴重攻擊期間,有些用戶端會看到裸機的「502 錯誤的閘道」錯誤。請務必注意,截至今日為止,我們的商務邏輯 Proxy 也會發出用於建立 HTTP 分析的記錄。後果就是 Cloudflare 儀表板鐘看不到這些錯誤。我們的內部儀表板顯示第一波攻擊期間約有 1% 請求受到影響,並在 8 月 29 日最嚴重的一次期間,達到幾秒約 12% 的峰值。下列圖表顯示此情況發生期間的兩小時內,這些錯誤的比率:

如本文稍後詳述的內容,我們在接下來幾天內努力將這個數字大幅減少。得益於我們堆疊中的變更及緩解措施,顯著減少了這些攻擊的規模,這個數字在今日實際上是零。

499 錯誤及 HTTP/2 串流並行處理的挑戰

部分客戶回報的另一個症狀為 499 錯誤有所增加。此情況的原因有點不同,而且與本文稍早詳述之 HTTP/2 連線中的串流並行處理上限相關。

HTTP/2 設定在連線開始時使用 SETTINGS 框架交換。在沒有接收明確參數的情況下,則適用於預設值。在用戶端建立 HTTP/2 連線後,即可等待伺服器的 SETTINGS(緩慢),或者假設預設值並開始提出請求(快速)。對於 SETTINGS_MAX_CONCURRENT_STREAMS,預設值其實沒有限制(串流 ID 使用 31 位元數的空格且請求使用奇數,因此實際限制為 1,073,741,824 次)。規格建議伺服器提供的串流不少於 100 個。用戶端一般偏向速度,所以請勿等待伺服器設定,其中會產生一些競爭條件。用戶端會在伺服器可能挑選的限制上賭一把;如果它們選錯,請求即會遭到拒絕且必須重試一次。要賭 1,073,741,824 個串流的話,有點愚蠢。取而代之的是,很多用戶端決定限制自身發出 100 個並行串流,並希望伺服器遵循規格建議。如果伺服器挑選的數字為 100 以下,表示用戶端賭輸,然後會重設串流。

伺服器可能將串流重設為超出並行處理限制的原因有很多。HTTP/2 很嚴格且在出現剖析或邏輯錯誤時要求串流關閉。在 2019 年,Cloudflare 制度了多項緩解措施以回應 HTTP/2 DoS 漏洞。那些漏洞有很多是因用戶端行為不當造成,並導致伺服器重設串流。若要壓制此類用戶端,計算連線期間的伺服器重設數目是非常有效的策略,還可以在超出部分閾值時,關閉具有 GOAWAY 框架的連線。合法用戶端可能會出現一或兩個連線錯誤,此為合理情況。如果用戶端出現太多錯誤,則可能處於損壞或惡意狀態,關閉連線可解決這兩種情況。

在回應 CVE-2023-44487 啟用的 DoS 攻擊時,Cloudflare 將串流並行處理上限減少至 64。進行此變更前,我們並不清楚用戶端不會等待 SETTINGS,而是假設並行處理為 100。有些網頁(例如影像庫)的確會讓瀏覽器在連線初期立即傳送 100 個請求。遺憾的是,36 個超出我們限制的串流全都需要重設,因而觸發我們的計算緩解措施。這表示我們關閉了合法用戶端上的連線,導致完整頁面載入失敗。在我們意識到此互通性問題時,我們就立即將串流並行處理上限變更 100。

Cloudflare 端採取的行動

在 2019 年,我們發現多項 DoS 漏洞與 HTTP/2 實作相關。Cloudflare 在回應中發展並部署了一系列偵測和緩解措施。CVE-2023-44487 是 HTTP/2 漏洞的不同表現。但是,為緩解此問題,我們能夠擴展現有保護以監控用戶端傳送的 RST_STREAM 框架,並且在連線受到濫用時將其關閉。RST_STREAM 在合法用戶端使用上不會受到影響。

除了直接修復之外,我們對伺服器的 HTTP/2 框架處理和請求分派代碼實作了多項改善。此外,商務邏輯伺服器收到了佇列和排程改善,可減少不不要的工作並改善取消的回應能力。這些可共同降低各種潛在濫用模式的影響,並且在飽和前為伺服器提供更多處理請求的空間。

提早緩解攻擊

Cloudflare 已配備可有效緩解非常大型攻擊的系統,而且是更經濟實惠的方法。其中一項稱為「IP Jail」。對於巨流量攻擊,此系統會收集參與攻擊的用戶端 IP,並阻止它們連線至受到攻擊的財產,無論是 IP 層級或位於我們的 TLS Proxy 中。但是,此系統需要幾秒才能充分發揮效果;在珍貴的幾秒之間,原始伺服器已受到保護,但我們的基礎架構還是需要吸收所有 HTTP 請求。由於這種新的殭屍網路實際上沒有啟動期間,因此我們能夠抵禦攻擊,以免造成問題。

為實現此目標,我們擴展了 IP Jail 系統以保護整個基礎架構:只要 IP「受到監禁」,不僅無法連線至受到攻擊的財產,我們還會在一段期間內禁止相應 IP 使用 HTTP/2 連線至 Cloudflare 上的其他網域。由於使用 HTTP/1.x 時無法濫用此類通訊協定,這限制了攻擊者執行大型攻擊的能力,而任何共用相同 IP 的合法用戶端在此期間內只會看到非常小幅度的效能降低。基於 IP 的緩解措施是非常遲鈍的工具;這就是為什麼我們在大規模採用並儘量設法避免誤判時必須極度謹慎。此外,殭屍網路中特定 IP 的生命週期通常很短,所以任何長期緩解措施有可能弊大於利。下圖顯示我們所見證攻擊中 IP 流失的情況:

如我們所見,很多在特定日期發現的新 IP 隨後都消失得非常快。

由於所有動作都發生在 HTTPS 管道開始處的 TLS Proxy 中,因此相較於常規的第 7 層緩解系統,這節省了大量資源。我們還可更加順暢地處理這些攻擊,目前由這些殭屍網路造成的隨機 502 錯誤數目已降至零。

可觀察性改善

我們做出變更的另一方面是可觀察性。向用戶端傳回錯誤卻未顯示於客戶分析中,令人很不滿意。幸運的是,早在近期的攻擊之前,這些系統的檢修專案已在進行中。最終讓我們基礎架構中的每項服務記錄自己的資料,而不是依賴商務邏輯 Proxy 整合並發出記錄資料。此事件強調了這項工作的重要性,而且我們正在加倍投入心力。

我們也在發展更好的連線層級記錄功能,以便更快速地找出此類通訊協定濫用,進而改善我們的 DDoS 緩解能力。

結論

雖然這是最新一次破紀錄的攻擊,但我們知道不只如此。隨著攻擊變得越來越複雜,Cloudflare 只有堅持不懈地主動識別新的威脅,同時為全球網路部署對策,才能讓我們數百萬名客戶獲得即時和自動的保護。

Cloudflare 自 2017 年起向我們所有客戶提供了免費、非計量且無限制的 DDoS 保護。此外,我們還有一系列額外的安全功能,符合所有規模的組織需求。如果您不確定自己是否受到保護或想瞭解如何受到保護,請聯絡我們。

HTTP/2 Rapid Reset: 기록적인 공격의 분석

Post Syndicated from Lucas Pardue original http://blog.cloudflare.com/ko-kr/technical-breakdown-http2-rapid-reset-ddos-attack-ko-kr/


Cloudfare에서는 2023년 8월 25일부터 다수의 고객을 향한 일반적이지 않은 일부 대규모 HTTP 공격을 발견했습니다. 이 공격은 우리의 자동 DDos 시스템에서 탐지하여 완화되었습니다. 하지만 얼마 지나지 않아 기록적인 규모의 공격이 시작되어, 나중에 최고조에 이르러서는 초당 2억 1백만 요청이 넘었습니다. 이는 우리 기록상 가장 대규모 공격이었던 이전의 공격의 거의 3배에 달하는 크기입니다.

공격을 받고 있거나 추가 보호가 필요하신가요? 여기를 클릭하여 도움을 받으세요.

우려되는 부분은 공격자가 머신 20,000개로 이루어진 봇넷만으로 그러한 공격을 퍼부을 수 있었다는 사실입니다. 오늘날의 봇넷은 수십만 혹은 수백만 개의 머신으로 이루어져 있습니다. 웹 전체에서 일반적으로 초당 10억~30억 개의 요청이 목격된다는 점을 생각하면, 이 방법을 사용했을 때 웹 전체 요청에 달하는 규모를 소수의 대상에 집중시킬 수 있다는 가능성도 완전히 배제할 수는 없습니다.

감지 및 완화

이는 전례 없는 규모의 새로운 공격 벡터였으나, Cloudflare는 기존 보호 기능을 통해 치명적인 공격을 대부분 흡수할 수 있었습니다. 처음에 목격된 충격은 초기 공격 웨이브 동안 고객 트래픽 요청의 약 1%에 영향을 주었으나, 현재는 완화 방법을 개선하여 시스템에 영향을 주지 않고 Cloudflare 고객을 향한 공격을 차단할 수 있습니다.

우리는 업계의 다른 주요 대기업인 Google과 AWS에서도 같은 시기에 이러한 공격이 있었음을 알게 되었습니다. 이에 따라 지금은 우리의 모든 고객을 이 새로운 DDoS 공격 방법으로부터 어떤 영향도 받지 않도록 보호하기 위하여 Cloudflare의 시스템을 강화했습니다. 또한 Google 및 AWS와 협력하여 영향을 받은 업체와 주요 인프라 제공 업체에 해당 공격을 알렸습니다.

이 공격은 HTTP/2 프로토콜과 서버 구현 세부 사항의 일부 주요 기능을 악용했기에 가능했습니다(자세한 내용은 CVE-2023-44487 참조). HTTP/2 프로토콜의 숨어 있는 약점을 파고들었던 공격이었기 때문에, HTTP/2을 구현한 업체라면 해당 공격의 대상이 될 것이라 판단하고 있습니다. 여기에는 요즘의 모든 웹 서버가 포함됩니다. 우리는 Google 및 AWS와 더불어 패치를 구현할 것이라 예상하고 있는 웹 서버 업체를 향한 해당 공격 방법을 공개해왔습니다. 그 동안 최고의 방어는 웹을 대면하는 웹과 API 서버의 프론트에 Cloudflare와 같이 DDoS 완화 서비스를 적용하는 것입니다.

이 포스팅에서는 HTTP/2 프로토콜의 세부 사항, 즉 공격자가 대규모 공격을 만들어내는 데 악용한 주요 기능과 모든 고객을 보호하기 위해 Couldfare가 채택한 완화 전략을 상세히 살펴봅니다. 우리의 희망은 이러한 세부 사항을 공개해 영향을 받는 다른 웹 서버와 서비스에서 완화 전략 구현에 필요한 정보를 갖추는 것입니다. 또한 이에 그치지 않고, HTTP/2 프로토콜 표준 팀과 미래의 웹 표준을 수립하는 팀에서 더 나은 설계를 내놓아 이와 같은 공격을 예방하는 것입니다.

RST 공격 세부 내용

HTTP는 웹을 구동하는 애플리케이션 프로토콜입니다. HTTP Semantics는 HTTP의 모든 버전, 즉 전반적 아키텍처, 용어, 프로토콜 측면(예: 요청 및 응답 메시지, 메서드, 상태 코드, 헤더 및 트레일러 필드, 메시지 내용 등)에서 공통입니다. 각 HTTP 버전은 인터넷에서 상호작용을 위해 “와이어 포맷”으로 시맨틱을 변환하는 방법을 정의합니다. 예를 들어 클라이언트가 요청 메시지를 바이너리 데이터로 직렬화한 후 전송하면, 서버는 이를 다시 처리할 수 있는 메시지로 다시 구문 분석합니다.

HTTP/1.1은 직렬화된 텍스트 형식을 사용합니다. 요청과 응답 메시지는 ASCII 문자의 스트림으로 교환되고, TCP처럼 안정적인 전송 계층을 통해 다음 형식(CRLF는 캐리지 리턴 및 줄바꿈을 의미)으로 전송됩니다.

 HTTP-message   = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

예를 들어, https://blog.cloudflare.com/ 에 대한 매우 간단한 GET 요청은 와이어에서 다음과 같이 표시됩니다:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

그리고 응답은 다음과 같습니다:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

이 형식은 와이어에서 메시지의 형식을 정의하는데, 이는 단일 TCP 연결을 사용하여 다수의 요청과 응답을 주고받을 수 있다는 의미입니다. 그러나 이 형식은 각 메시지를 전체로 보내야 합니다. 추가로 요청과 응답을 정확하게 상호 연결하려면 순서를 엄격하게 지켜야 합니다. 즉, 메시지는 직렬로 교환되고, 다중화될 수 없습니다. https://blog.cloudflare.com/과 https://blog.cloudflare.com/page/2/에 대한 두 개의 GET 요청은 다음과 같이 표시됩니다:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLFGET /page/2/ HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

응답은 다음과 같습니다.

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>CRLFHTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

웹 페이지에는 예시보다 더 복잡한 HTTP 상호작용이 필요합니다. Cloudflare 블로그를 방문할 때 브라우저는 여러 스크립트, 스타일, 미디어 에셋을 로드합니다. HTTP/1.1로 해당 페이지를 방문하고, 빠르게 다음 페이지로 넘어가고자 할 때, 브라우저는 2가지 선택지 중 하나를 고를 수 있습니다. 페이지가 시작하기도 전에 이제는 원하지 않는 다음 페이지에 대해 대기 중인 모든 응답을 기다리거나, TCP 연결을 닫고 새로운 연결을 열어 전송 중인 요청을 취소할 수 있습니다. 2가지 선택지 모두 그다지 실용적이지는 않습니다. 브라우저는 TCP 연결 풀(호스트당 최대 6개)을 관리하고 풀에서 복잡한 요청 전송 로직을 구현하며 이러한 제한을 준수합니다.

HTTP/2에서는 HTTP/1.1에서 발생한 문제 대부분이 해결됩니다. 각 HTTP 메시지는 유형, 길이, 플래그, 스트림 식별자(ID), 페이로드가 있는 HTTP/2 프레임 조합으로 직렬화됩니다. 스트림 ID는 와이어의 어떤 바이트가 어떤 메시지에 적용되는지 분명히 하는 동시에 안전하게 다중화하고 동시성을 부여합니다. 스트림은 양방향입니다. 클라이언트가 프레임을 전송하면, 서버는 같은 ID를 사용하는 프레임으로 응답합니다.

HTTP/2에서 https://blog.cloudflare.com에 대한 GET 요청은 스트림 ID 1을 통해 교환됩니다. 클라이언트가 1개의 HEADERS 프레임을 보내면 서버는 1개의 HEADERS 프레임과 뒤이어 1개 이상의 DATA 프레임으로 응답합니다. 클라이언트가 요청하는 스트림 ID는 항상 홀수이므로, 후속 요청은 스트림 ID 3, 5 등이 됩니다. 응답은 순서와 관계없이 전달되고, 다른 스트림의 프레임이 인터리빙될 수 있습니다.

스트림 다중화와 동시성은 HTTP/2의 강력한 주요 특징입니다. 두 이점은 단일 TCP 연결의 더욱 더 효율적인 사용을 지원합니다. HTTP/2는 우선순위 지정과 짝을 이룰 때 특히나 리소스 가져오기를 최적화합니다. 반대로 생각해보면, 클라이언트의 대규모 병렬 작업을 수월하게 시행할 수 있게 만들어 줌으로써 HTTP/1.1과 비교했을 때, 서버 리소스에 대한 피크 수요가 높아집니다. 이는 서비스 거부에 대한 분명한 벡터입니다.

HTTP/2는 약간의 방어 수단을 제공하기 위해 최대 활성 동시 스트림의 개념을 제시합니다. SETTINGS_MAX_CONCURRENT_STREAMS 매개변수는 서버가 자신의 동시성 제한을 알릴 수 있도록 합니다. 예를 들어, 서버에 100개로 제한을 둔다면, 어느 시점에서도 100개의 요청만이 활성화될 수 있습니다. 클라이언트가 제한을 초과하는 스트림을 열고자 한다면, 이 시도는 RST_STREAM 을 사용하는 서버에서 거부되어야 합니다. 스트림 거부는 연결 상의 이동 중인 다른 스트림에 영향을 주지 않습니다.

실제 이야기는 조금 더 복잡합니다. 스트림에는 수명 주기가 있습니다. 아래 HTTP/2 스트림 상태인 기기의 도표가 나와있습니다. 클라이언트와 서버는 스트림 상태인 자신의 뷰를 관리합니다. HEADERS, DATA, RST_STREAM 프레임은 전송되거나 수신될 때, 전환을 유발합니다. 스트림 상태의 뷰는 독립적이기는 하지만, 동기화됩니다.

HEADERS와 DATA 프레임에는 값이 1(true)로 설정되었을 때, 상태 전환을 일으킬 수 있는 END_STREAM이 포함되어 있습니다.

메시지 내용이 없는 GET 요청의 예시를 자세히 살펴보겠습니다. 클라이언트는 END_STREAM 플래그 조합을 1로 설정한 HEADERS 프레임으로 요청을 전송합니다. 클라이언트는 먼저 스트림 상태를 유휴에서 열림 상태로 전환한 다음, 곧바로 반 닫힘 상태로 전환합니다. 클라이언트의 반 닫힘 상태란 더 이상 HEADERS 또는 DATA를 보낼 수 없고, WINDOW_UPDATE, PRIORITY 또는 RST_STREAM 프레임만을 보낼 수 있는 상태를 말합니다. 하지만 클라이언트가 받는 프레임의 종류에는 제한이 없습니다.

서버가 HEADERS 프레임을 받아 구문 분석하고 나면 스트림 상태를 유휴에서 열림, 그리고 반 닫힘 상태로 전환해 클라이언트와 상태를 일치시킵니다. 서버가 반 닫힘 상태라는 의미는 어떤 프레임이든지 보낼 수 있지만, WINDOW_UPDATE, PRIORITY, RST_STREAM만 받을 수 있는 상태를 말합니다.

GET에 대한 응답에는 메시지 내용이 포함되므로 서버에서는 0으로 설정된 END_STREAM 플래그가 포함된 HEADERS를 보내고 난 다음, 1로 설정한 END_STREAM 플래그가 포함된 HEADERS를 보냅니다. DATA 프레임은 서버에서 스트림이 반 닫힘 상태에서 닫힘 상태로 전환되게 합니다. 클라이언트가 DATA 프레임을 받으면, 클라이언트 또한 닫힘 상태로 전환됩니다. 스트림이 닫히고 나면 어떤 프레임도 보내거나 받을 수 없습니다.

수명 주기를 동시성 컨텍스트에 다시 적용하면 HTTP/2는 다음과 같이 나타납니다:

“열림” 상태이거나 “반 닫힘” 상태인 스트림은 엔드포인트가 열 수 있도록 허용된 최대 스트림 수에 포함됩니다. 이 세 가지 상태 중 하나에 있는 스트림은 SETTINGS_MAX_CONCURRENT_STREAMS 설정에서 통지된 한도에 포함됩니다.

이론상, 동시성 제한은 유용합니다. 그렇지만, 그 효과를 방해하는 실용적인 요소가 있으며, 이는 블로그 뒷 부분에서 다룰 예정입니다.

HTTP/2 요청 취소

앞서 전송 중인 요청의 클라이언트 취소에 관해 설명했습니다. HTTP/2에서는 이를 HTTP/1.1보다 더 효율적인 방식으로 지원합니다. 클라이언트는 전체 연결을 끊지 않고도 단일 스트림에 대한 RST_STREAM 프레임을 보낼 수 있습니다. 이로 인해 서버는 요청 처리를 멈추고, 응답을 중단함으로써, 서버 리소스를 확보하고 대역폭 낭비를 방지할 수 있습니다.

앞선 예시인 3개의 요청을 살펴보겠습니다. 이번에는 클라이언트가 모든 HEADERS를 보내고 난 후에 스트림 1의 요청을 취소하는 경우를 가정해 보겠습니다. 서버는 응답을 보낼 준비를 하기 전에 이 RST_STREAM 프레임을 구문 분석하고 그 대신 스트림 3과 5에 대해서만 응답합니다.

요청 취소는 유용한 기능입니다. 예를 들어, 여러 이미지가 있는 웹 페이지를 스크롤할 때, 웹 브라우저는 뷰포트에서 벗어난 이미지를 취소할 수 있는데, 다시 말해 뷰포트로 들어오는 이미지는 더 빨리 로드된다는 의미입니다. HTTP/1.1과 비교했을 때 HTTP/2가 이러한 행위를 훨씬 더 효율적으로 수행합니다.

취소된 요청 스트림은 스트림 수명주기를 통해 빠르게 전환됩니다. END_STREAM 플래그가 1로 설정된 HEADERS는 클라이언트를 유휴 상태에서 열림, 반 닫힘 상태로 전환시키고, 이어서 RST_STREAM이 곧바로 반 닫힘 상태에서 닫힘 상태로 전환시킵니다.

열림 또는 반 닫힘 상태의 스트림만이 스트림 동시성 제한에 영향을 미친다는 점을 상기해 보세요. 클라이언트가 스트림을 취소하면 즉시 그 자리에 다른 스트림을 열 수 있고 바로 다른 요청을 보낼 수도 있습니다. 이는 CVE-2023-44487을 작동시키는 핵심입니다.

서비스 거부로 이어지는 Rapid Reset

HTTP/2 요청 취소는 무한한 스트림을 빠르게 초기화하는 데 악용될 수 있습니다. HTTP/2 서버가 클라이언트가 보낸 RST_STREAM 프레임을 처리할 수 있고, 충분히 빠르게 상태를 분해할 수 있다면, Rapid Reset은 문제가 되지 않습니다. 정리 과정에서 지연이나 처짐이 발생할 때 문제가 발생하기 시작합니다. 이때 클라이언트는 작업 백로그를 누적시키는 많은 요청으로 인해 이탈될 수 있으며, 이는 서버 리소스의 과도한 소모로 이어집니다.

일반적인 HTTP 배포 아키텍처는 다른 구성 요소보다 앞서서 HTTP/2 프록시 또는 부하 분산 장치를 실행할 수 있습니다. 클라이언트 요청이 도착하면 빠르게 전송되고, 실제 작업은 다른 곳에서 비동기 활동으로 이루어집니다. 이로 인해 프록시는 클라이언트 트래픽을 매우 효율적으로 처리할 수 있습니다. 그러나 이러한 분리로 인해 프록시가 처리 중인 작업은 정리하는 것이 어려워질 수 있습니다. 따라서 이러한 배포는 Rapid Reset로 인한 문제를 만날 가능성이 더 높습니다.

Cloudflare의 역프록시가 수신되는 HTTP/2 클라이언트 트래픽을 처리할 때, 연결의 소켓에서 버퍼로 데이터를 복사한 다음 버퍼에 있는 데이터를 순서대로 처리합니다. 각 요청을 읽으면(HEADER와 DATA 프레임) 이는 업스트림 서비스로 전송됩니다. RST_STREAM 프레임을 읽으면, 해당 요청에 대한 로컬 상태는 해체되고, 업스트림에서는 요청이 취소되었다는 알림을 받습니다. 버퍼를 비우고 버퍼 전체가 사용될 때까지 이를 반복합니다. 하지만 이 로직은 악용될 수 있습니다. 그 이유는 악의적 클라이언트가 연결을 시작할 때 엄청난 양의 요청과 초기화 체인을 보내기 시작하면, 우리의 서버는 의욕이 넘쳐서 체인을 모두 읽고, 업스트림 서버에 새롭게 수신되는 요청을 처리할 수 없는 시점까지 압력을 만들어내기 때문입니다.

짚고 넘어가야 하는 중요한 점은 그 자체의 스트림 동시성이 Rapid Reset를 완화시켜줄 수 없다는 것입니다. 클라이언트는 요청이 서버의 SETTINGS_MAX_CONCURRENT_STREAMS 설정 값과 관계 없이 높은 요청 속도를 만들어낼 수 있습니다.

Rapid Reset 분석

여기 총 1,000건의 요청을 생산하려는 개념 증명 클라이언트로 재생산된 Rapid Reset의 예가 있습니다. 여기서는 어떤 완화도 없는 상용 서버를 사용했으며, 테스트 환경에서는 443 포트가 수신 대기 중입니다. 트래픽은 Wireshark로 분석되며, 명확성을 위해 HTTP/2 트래픽만을 표시하도록 필터링됩니다. pcap을 다운로드하여 다음을 확인하세요.

프레임이 많으므로 트래픽을 확인하는 데 조금 어려울 수 있습니다. Wireshark 통계 > HTTP2 툴을 통한 빠른 요악을 받아볼 수 있습니다.

패킷 14에서 이 트레이스의 첫 번째 프레임은 서버의 SETTINGS 프레임으로, 최대 100개의 스트림 동시성을 알립니다. 패킷 15에서 클라이언트는 몇몇 제어 프레임을 보낸 다음 Rapid Reset이 되는 요청을 시작합니다. 첫 번째 HEADERS 프레임은 26바이트이고, 모든 후속 HEADERS는 9바이트에 불과합니다. 이 크기 차이는 HPACK이라는 압축 기술 덕분입니다. 패킷 15에는 총 525개의 요청이 포함되어 있으며, 스트림 1051까지 올라갑니다.

흥미롭게도 스트림 1051에 대한 RST_STREAM은 패킷 15에 맞지 않아 패킷 16에서 서버가 404로 응답하는 것을 볼 수 있습니다.  그 후에 클라이언트는 패킷 17에서 나머지 475개의 요청을 전송하기 전에 RST_STREAM을 전송합니다.

서버에서는 동시 스트림이 100개라고 알렸으나, 클라이언트에서 보낸 2개의 패킷 모두 그보다 훨씬 더 많은 HEADERS 프레임을 보냈습니다. 클라이언트는 서버로부터의 응답 트래픽을 기다릴 필요가 없었고, 보낼 수 있는 패킷의 크기에 따른 제한만을 받았습니다. 이 트레이스에서 서버의 RST_STREAM 프레임이 전혀 보이지 않는 것은 서버가 동시 스트림 위반을 관찰하지 못했음을 말해줍니다.

고객에게 미치는 영향

위에서 언급한 것과 같이 요청이 취소되면 업스트림 서비스는 알림을 전달받고, 너무 많은 리소스를 낭비하기 전에 요청을 중단할 수 있습니다. 이번 공격 케이스에서도 마찬가지였고, 대부분의 악의적 요청은 원본 서버로 전혀 포워딩되지 않았습니다. 그렇지만, 그 공격의 규모만으로도 일부 영향이 있었습니다.

첫째, 들어오는 요청의 속도가 이전에는 볼 수 없었던 최고치에 도달함에 따라, 고객의 502 오류 보고 횟수가 늘었다는 보고가 있었습니다. 이는 가장 지대한 영향을 받은 데이터 센터에서 모든 요청을 처리하기 위해 분투하는 과정에서 발생했습니다. 우리의 네트워크는 대규모 공격에 대응할 수 있도록 설계되었음에도, 이 특정한 취약점으로 인해 인프라의 약점이 노출되었습니다. 이제 더 세부 사항으로 들어가서, 데이터센터 중 한 곳에 공격이 발생했을 때, 들어오는 요청이 어떻게 처리되는지에 초점을 맞추어 보겠습니다.

Cloudflare 인프라는 각각 다른 책임을 맡은 여러 프록시 서버 체인으로 구성되어 있음을 확인할 수 있습니다. 특히 클라이언트가 HTTPS 트래픽을 전송하기 위해 Cloudflare에 연결하면 먼저 TLS 복호화 프록시에 연결됩니다. 프록시는 TLS 트래픽을 복호화하고 HTTP 1, 2 또는 3 트래픽을 처리한 다음, 이를 “비즈니스 로직” 프록시로 포워딩합니다. 이 프록시는 각 고객에 대한 모든 설정을 로드하고, 요청을 다른 업스트림 서비스로 정확하게 라우팅하는데, 이 케이스에서는 그보다 더 중요한 보안 기능도 담당합니다. L7 공격 완화도 이 프록시에서 처리됩니다.

이번 공격 벡터의 문제점은 모든 연결에서 매우 빠르게 다량의 요청을 보낼 수 있다는 사실입니다. 우리가 공격 벡터를 차단할 기회를 갖기도 전에 각 요청이 비즈니스 로직 프록시로 포워딩되어야 했습니다. 요청 처리량이 프록시 용량을 앞지르면서 이 두 서비스를 연결하는 채널이 우리의 일부 서버에서는 포화 상태에 도달했습니다.

이렇게 되면 TLS 프록시가 업스트림 프록시에 더 이상 연결될 수 없으며, 이것이 몇몇 클라이언트에서 가장 심각한 공격 중 소량의 “502 Bad Gateway” 오류가 발생했던 원인입니다. 주목해야 할 점은 오늘 현재 HTTP 분석을 생성하기 위해 사용하는 로그 또한 비즈니스 로직 프록시에서 전송된다는 사실입니다. 그 결과, 이러한 오류는 Cloudflare 대시보드에서 보이지 않습니다. 내부 대시보드에서는 초기 공격 웨이브(완화 조치를 구현하기 전) 중 약 1%의 요청이 영향을 받았으며, 가장 심각한 공격이 발생했던 8월 29일에는 수 초 동안 약 12%를 기록하며, 최고치를 달성했습니다. 다음 그래프에는 공격이 발생한 2시간 동안 오류의 비율이 나와있습니다.

이 글 아래에서 설명될 내용과 같이 그다음 날에는 이 숫자를 극적으로 낮추는 작업이 진행되었습니다. 스택의 변화와 이러한 공격 규모를 상당히 감소시킨 완화 조치 덕분에 현재 이 수치는 사실상 0입니다.

499 오류 및 HTTP/2 스트림 동시성의 문제

일부 고객이 알려온 또 다른 증상은 499 오류의 증가입니다. 그 이유는 조금 다른데, 이는 앞서 설명한 HTTP/2 연결의 최대 스트림 동시성 수와 관련이 있습니다.

HTTP/2 설정은 SETTINGS 프레임을 사용해 연결이 시작될 때 교환됩니다. 명시적 매개변수를 받지 않은 경우에는 기본값이 적용됩니다. 클라이언트가 HTTP/2 연결을 설정하고 나면, 서버의 SETTINGS(느림)를 기다리거나, 기본값을 가정하고 요청(빠름)을 시작할 수 있습니다. SETTINGS_MAX_CONCURRENT_STREAMS의 기본값은 사실상 무제한입니다(스트림 ID는 31비트 숫자 공간을 사용, 요청은 홀수를 사용하므로 실제 제한은 1073741824). 사양에서는 서버에서 100개 이상의 스트림을 제공하기를 권장합니다. 클라이언트는 일반적으로 속도에 편향되어 있으므로 서버 설정을 기다리지 않는 경향이 있으며, 이로 인해 약간의 경쟁 조건이 만들어집니다. 클라이언트는 서버에서 어떤 제한을 선택할지 도박을 하는 것과 같습니다. 잘못 선택한다면, 요청은 거부되고, 다시 시도해야 하기 때문입니다. 1073741824 스트림에 대한 도박은 다소 어리석은 일입니다. 그 대신 다수의 클라이언트는 서버가 사양 권장 사항을 따르기를 바라면서, 100개의 동시 스트림으로 제한할 것을 결정합니다. 서버가 100개 미만을 선택한다면, 클라이언트의 도박은 실패하고 스트림은 초기화됩니다.

서버가 동시성 제한을 초과한 스트림을 초기화하는 데는 여러가지 이유가 있습니다. HTTP/2는 프로토콜이 엄격하고, 구문 분석이 있거나 로직 오류가 있을 때 스트림을 닫아야 합니다. 2019년, Cloudflare에서는 HTTP/2 DoS 취약점에 대응해 몇 가지 완화 조치를 개발했습니다. 몇몇 취약점은 클라이언트의 올바르지 않은 행동, 서버에서 스트림을 초기화하도록 이끄는 클라이언트가 그 원인이었습니다. 이러한 클라이언트를 단속하는 매우 효과적인 방법은 연결 중 서버 초기화 횟수를 세고, 몇몇 임계값을 넘을 때 GOAWAY 프레임으로 연결을 끊는 것입니다. 합법적인 클라이언트라면 연결 시 한두 가지 정도의 실수는 할 수 있습니다. 클라이언트에서 너무 많은 실수를 범한다면, 문제가 있거나 악의를 가진 경우이며, 연결을 끊으면 두 가지 케이스가 모두 해결됩니다.

Cloudflare에서는 CVE-2023-44487으로 활성화된 DoS 공격에 대응하는 동안, 최대 스트림 동시성을 64개로 줄였습니다. 이러한 변화를 주기 전에는 클라이언트에서 SETTINGS를 기다리지 않고 100개의 동시성을 가정한다는 사실을 알지 못했습니다. 이미지 갤러리와 같은 일부 웹 페이지는 연결 시작 시에 곧바로 브라우저가 100개의 요청을 보내도록 하기도 합니다. 하지만, 우리의 제한을 초과한 36개의 스트림은 모두 초기화되어야 했으며, 이는 카운팅 완화 조치의 시행 조건으로 작용했습니다. 이는 합법적인 클라이언트와의 연결을 끊게 만들어 페이지 가져오기의 완전한 실패로 이어졌습니다. 따라서 이 상호운용성 문제를 인지하자마자 최대 스트림 동시성 수를 100개로 변경했습니다.

Cloudflare 측의 조치

2019년, HTTP/2 구현과 관련한 몇 가지 DoS 취약점이 발견되었습니다. Cloudflare에서는 이에 대한 대응으로 일련의 감지 및 완화 조치를 개발하고 배포했습니다. CVE-2023-44487은 HTTP/2 취약점의 다른 표현입니다. 하지만, 이를 완화하기 위해 기존의 보호 기능을 확장하여 클라이언트가 전송한 RST_STREAM 프레임을 모니터링하고, 악용되는 경우 연결을 닫을 수 있었습니다. 합법적인 클라이언트의 RST_STREAM 사용은 영향을 받지 않습니다.

우리는 직접적인 수정에 그치치 않고, 서버의 HTTP/2 프레임 처리 및 요청 전송 코드에도 몇 가지 개선점을 구현했습니다. 추가로, 비즈니스 로직 서버의 대기열 및 스케줄링 또한 개선해서, 불필요한 작업을 줄이고 취소 응답성을 높일 수 있었습니다. 이러한 개선 모두에 힘입어 다양한 잠재적 남용 패턴의 영향이 줄어들고 서버가 포화 상태에 이르기 전에 요청을 처리할 수 있는 공간이 더 확보됩니다.

공격의 조기 완화

Cloudflare에서는 더욱 저렴한 방식으로 대규모 공격을 효율적으로 완화할 수 있는 시스템을 이미 갖추고 있습니다. 그중 하나가 “IP Jail”입니다. IP Jail은 대규모 볼류메트릭 공격 시 공격에 참여하는 클라이언트 IP를 수집하고, 해당 IP 레벨이나 TLS 프록시에서 공격받은 위치와의 연결을 끊습니다. 하지만 이 시스템이 온전히 효과를 발휘하기 위해서는 몇 초가 필요합니다. 이 귀중한 시간에 원본은 보호받지만, 인프라는 여전히 모든 HTTP 요청을 받아들여야 합니다. 이 새로운 봇넷은 사실상 램프업 기간이 없으므로 우리는 문제가 되기 전에 공격을 무력화할 수 있는 능력을 갖추어야 합니다.

우리는 이를 구현하기 위해 전체 인프라를 보호하는 IP Jail 시스템을 확장했습니다. 일단 IP가 “구속되면”, 공격받은 위치로의 연결이 차단될 뿐만 아니라, 해당 IP는 일정 시간 Cloudflare의 다른 도메인에 HTTP/2를 사용하는 것도 금지됩니다. 이러한 프로토콜의 악용은 HTTP/1.x로는 불가능하므로, 공격자는 대규모 공격을 퍼부을 수 있는 능력이 제한되는 반면, 동일한 IP를 공유하는 합법적인 클라이언트는 해당 시간 아주 미세한 성능 저하만을 겪습니다. IP 기반의 완화 조치는 매우 무딘 도구이며, 그렇기 때문에 해당 규모로 사용할 때는 극도로 신중을 기해야 하며, 가능한 한 긍정 오류를 피해야 합니다. 또한 봇넷에서 특정 IP의 수명은 일반적으로 짧으므로, 장기간의 완화 조치는 장점보다 단점이 더 많을 수도 있습니다. 다음 그래프에는 우리가 목격한 공격 중 급격한 변화가 나와있습니다.

그래프에서 확인할 수 있듯이, 다수의 새로운 IP가 특정한 날 이후 매우 빠르게 사라집니다.

이 모든 조치는 HTTPS 파이프라인의 시작 부분에 있는 TLS 프록시에서 이루어지므로 우리의 일반 L7 완화 시스템과 비교했을 때 상당한 리소스를 절약할 수 있습니다. 이로 인해 훨씬 더 원활하게 공격에 대응할 수 있었고, 이제 봇넷으로 인한 무작위 502 오류 수는 0개가 되었습니다.

관찰 가능성 개선

Cloudflare에서 변화를 만들어 가고 있는 영역은 관찰 가능성입니다. 고객 분석에서 보이지 않고, 고객에게 오류를 돌려주는 상황은 만족할 수 없는 부분입니다. 다행스럽게도 최근 공격이 발생하기 훨씬 이전부터 해당 시스템을 정비하는 프로젝트가 진행 중이었습니다. 프로젝트의 궁극적인 방향은 비즈니스 로직 프록시에 의존하여 로그 데이터를 통합하고 방출하는 것이 아닌, 인프라 내의 각 서비스가 자체 데이터를 로깅할 수 있는 것입니다. 이번 사고로 인해 해당 작업의 중요성이 대두되었기에, 노력을 배가하고 있습니다.

또한 이러한 프로토콜 악용을 훨씬 더 빠르게 발견해 DDoS 완화 기능을 개선할 수 있는 연결 수준의 로깅 개선 업무도 작업 중입니다.

결론

이 사고는 가장 최근의 기록적인 공격이었지만, 이번이 마지막은 아닐 것이라는 사실은 잘 알고 있습니다. 공격이 점점 더 정교해짐에 따라 Cloudflare에서는 새로운 위협을 적극적으로 식별해서 수백만 고객이 즉각적이고 자동적으로 보호받을 수 있도록 전역 네트워크에 대응책을 배포하는 등 끊임없는 노력을 기울이고 있습니다.

Cloudflare는 2017년부터 고객에게 무료로 무제한 DDoS 방어를 제공해 왔습니다. 이와 더불어, 모든 규모의 조직 니즈에 맞는 광범위한 부가 보안 기능 또한 제공합니다. 보호받고 있는지 확신할 수 없거나 어떻게 보호받을 수 있는지 알고 싶다면 이곳으로 문의하세요.

Resultados de la vulnerabilidad HTTP/2 Zero-Day en ataques DDoS sin precedentes

Post Syndicated from Grant Bourzikas original http://blog.cloudflare.com/es-es/zero-day-rapid-reset-http2-record-breaking-ddos-attack-es-es/


Hoy temprano, Cloudflare, Google y Amazon AWS, divulgaron la existencia de una nueva vulnerabilidad zero-day que se conoce como ataque “HTTP/2 Rapid Reset”. Este ataque aprovecha un punto débil en el protocolo HTTP/2 para generar enormes ataques hipervolumétricos por denegación de servicio distribuido (DDoS). Cloudflare ha mitigado un aluvión de estos ataques en los últimos meses, incluso uno tres veces más grande que cualquier ataque anterior que hayamos observado, que superó las 201 millones de solicitudes por segundo (rps). Desde fines de agosto de 2023, Cloudflare ha mitigado otros más de 1100 ataques con más de 10 millones de rps — y 184 ataques fueron de una magnitud mayor a nuestro récord de ataques DDoS previos de 71 millones de rps.

¿Estás siendo blanco de un ataque o necesitas mayor protección? Si necesitas ayuda, haz clic aquí.

Este zero-day brindó a los ciberdelincuentes una nueva herramienta fundamental en su navaja suiza de vulnerabilidades para aprovecharse de sus víctimas y atacarlas a una magnitud que nunca habíamos visto. Si bien a veces estos ataques son complejos y difíciles de combatir, brindaron a Cloudflare la oportunidad de desarrollar tecnología con el propósito de mitigar los efectos de la vulnerabilidad zero-day.

Si utilizas Cloudflare para la mitigación de HTTP DDoS, estás protegido. A continuación, incluimos más información sobre esta vulnerabilidad, recursos y recomendaciones sobre lo que puedes hacer para protegerte.

Deconstrucción del ataque: qué deben saber los directores de seguridad (CSO)

A fines de agosto de 2023, nuestro equipo de Cloudflare advirtió una nueva vulnerabilidad zero-day desarrollada por un ciberdelincuente desconocido que aprovecha los puntos débiles del protocolo HTTP/2 — un protocolo fundamental para que funcionen Internet y todos los sitios web. Este nuevo ataque de la vulnerabilidad zero-day, conocido como Rapid Reset, aprovecha la función de cancelación de flujo de HTTP/2 al enviar una solicitud y cancelarla de inmediato, y haciéndolo una y otro vez.  

Al automatizar este simple patrón “solicitar, cancelar, solicitar, cancelar” a escala, los ciberdelincuentes pueden generar una denegación de servicio y provocar la caída de cualquier servidor o aplicación ejecutando la implementación estándar de HTTP/2. Además, un aspecto fundamental que se debe tener en cuenta con respecto a este ataque sin precedentes es que utilizó un botnet de tamaño mediano, de aproximadamente 20 000 máquinas. Cloudflare periódicamente detecta botnets que son órdenes de magnitud mayores que esto — que incluye cientos de miles e incluso millones de máquinas. Que un botnet relativamente pequeño genere un volumen tan grande de solicitudes, con la posibilidad de inhabilitar casi todos los servidores o aplicaciones que admiten HTTP/2, indica lo amenazante que resulta esta vulnerabilidad para las redes que no están protegidas.

Los ciberdelincuetes utilizaron botnets en tándem con la vulnerabilidad HTTP/2 para amplificar las solicitudes a un ritmo que nunca habíamos visto antes. A raíz de esto, nuestro equipo de Cloudflare sufrió una inestabilidad intermitente en el perímetro. Si bien nuestros sistemas pudieron mitigar la abrumadora mayoría de ataques entrantes, el volumen sobrecargó algunos componentes de nuestra red, y afectó el rendimiento de una pequeña cantidad de clientes con errores 4xx y 5xx intermitentes — los cuales fueron resueltos en su totalidad.

Una vez que mitigamos con éxito estos problemas y detuvimos los potenciales ataques a todos los clientes, nuestro equipo lanzó de inmediato un proceso de divulgación responsable. Iniciamos conversaciones con nuestros pares de la industria para analizar de qué manera podíamos trabajar juntos para proteger el gran porcentaje de Internet que depende de nuestra red antes de divulgar esta vulnerabilidad al público en general.

Cubrimos la información técnica del ataque de manera más detallada en la publicación de un blog por separado: HTTP/2 Rapid Reset: deconstrucción de un ataque sin precedentes.

¿Cómo Cloudflare y la industria están combatiendo este ataque?

No existe algo como una “divulgación perfecta”. Combatir ataques y responder a los incidentes que surgen exige que las organizaciones y los equipos de seguridad asuman que siempre existe la posibilidad de una filtración — porque siempre habrá otro zero-day, y siempre surgen nuevas técnicas y nuevos ciberdelincuentes, y nuevas técnicas y ataques que nunca antes se habían registrado.

Esta idea de que siempre existe la posibilidad de potenciales ataques es la clave para compartir información y asegurar de que en instancias como esta Internet seguirá siendo segura. Mientras Cloudflare estaba sufriendo y mitigando estos ataques, también trabajábamos con socios de la industria para garantizar que todo el sector pudiera resistir este ataque.  

Durante el proceso de mitigación de este ataque, nuestro equipo de Cloudflare desarrolló una nueva tecnología para detener estos ataques DDoS y mejorar nuestras propias mitigaciones tanto para este como para otros ataques de escala masiva. Estas iniciativas han aumentado de manera significativa nuestra resiliencia y nuestras capacidades de mitigación general. Si estás usando Cloudflare, estamos seguros de que estás protegido.

Nuestro equipo también alertó a los socios de software del servidor web que está desarrollando parches para garantizar que esta vulnerabilidad no sea aprovechada — revisa sus sitios web para obtener más información.

Las divulgaciones nunca ocurren una única vez. La esencia de Cloudflare es garantizar un mejor servicio de Internet, que proviene de hechos como estos. Cuando tenemos la oportunidad de trabajar con nuestros socios de la industria y con los gobiernos para garantizar que no se extienda el impacto en Internet, estamos haciendo lo que nos corresponde para mejorar la resiliencia informática de cada organización, independientemente de la magnitud o la verticalidad.

Para comprender mejor las tácticas de mitigación y los próximos pasos sobre el parcheado, inscríbete en nuestro seminario web.

¿Cuáles son los orígenes de HTTP/2 Rapid Reset y estos ataques sin precedentes sobre Cloudflare?

Puede parecer extraño que Cloudflare haya sido una de las primeras empresas que vieron estos ataques. ¿Por qué los ciberdelincuentes atacarían a una empresa que tiene una de las defensas más sólidas del mundo contra los ataques DDoS?  

La realidad es que Cloudflare suele ver los ataques antes de que se dirijan a objetivos más vulnerables. Los ciberdelincuentes necesitan desarrollar y probar sus herramientas antes de implementarlas en toda la red. A los ciberdelincuentes que utilizan métodos de ataques sin precedentes les puede resultar sumamente difícil probar y entender la magnitud y la efectividad de estos, porque no tienen la infraestructura para absorber los ataques que están lanzando. Debido a la transparencia que compartimos sobre nuestro rendimiento en la red y las mediciones de los ataques que podrían recopilar de nuestros gráficos públicos sobre rendimiento, este ciberdelincuente probablemente estaba usándonos como objetivo para comprender las capacidades del ataque.

Pero esa prueba, y la capacidad para ver el ataque en una fase temprana, nos ayuda a desarrollar mitigaciones para el ataque que benefician tanto a nuestros clientes como a la industria en general.

De director de seguridad a director de seguridad: ¿Qué deberías hacer?

Hace más de 20 años que soy director de seguridad, y he recibido incontables divulgaciones y anuncios como este. Pero independientemente de si se trataba de Log4J, Solarwinds, EternalBlue WannaCry/NotPetya, Heartbleed o Shellshock, todos estos incidentes de seguridad tenían aspectos en común. Una tremenda explosión que se multiplica en todo el mundo y crea la ocasión para interrumpir por completo cualquiera de las organizaciones que he dirigido — independientemente de la industria o de la magnitud.

Muchos de estos fueron ataques o vulnerabilidades que podríamos haber no controlado. Pero independientemente de si el problema surgió de algo que estaba bajo mi control o no, lo que ha distinguido las iniciativas exitosas que he dirigido de las que no estaban a nuestro favor fue la capacidad para responder cuando vulnerabilidades zero-day y ataques como este son identificados.    

Si bien desearía poder decir que Rapid Reset puede ser diferente esta vez, no lo es. Esta vez, apelo a todos los directores de seguridad — independientemente de si han visto los incidentes de seguridad que yo he visto durante décadas o si se trata de alguien en su primer día en el trabajo — para garantizar que estén protegidos y respalden a sus equipos de respuesta de incidentes informáticos.

Hemos mantenido la información reservada hasta hoy para dar a todos los proveedores de seguridad la oportunidad de reaccionar. Sin embargo, en algún punto, tenemos la responsabilidad de hacer públicas las amenazas zero-day como esta. Hoy es ese día. Esto significa que después de hoy, los ciberdelincuentes estarán muy al tanto de la vulnerabilidad HTTP/2; e inevitablemente se convertirá en algo simple para aprovechar y lanzar la carrera entre defensores y atacantes — crear parches primero frente a aprovechar primero. Las organizaciones deberían suponer que los sistemas serán probados y tomar medidas preventivas para garantizar la protección.

Para mí, esto es algo parecido a una vulnerabilidad como Log4J, debido a la cantidad de variantes que están surgiendo diariamente, y seguiremos obteniendo resultados en las semanas, meses y años venideros. A medida que investigadores y ciberdelincuentes experimenten con esta vulnerabilidad, podemos descubrir diferentes variantes con ciclos de aprovechamiento aún más cortos que contienen aún más atajos avanzados.  

Y al igual que con Log4J, gestionar incidentes como este no es tan simple como “ejecutar el parche y listo”. Debes convertir la gestión del incidente, el parcheo y la evolución de las protecciones de seguridad en procesos constantes — porque los parches para cada variante de una vulnerabilidad reducen el riesgo, pero no lo eliminan.

No quiero ser alarmista, pero voy a ser directo: esto es algo que se debe tomar muy en serio. Esto se debe tratar como un incidente completamente activo para garantizar que no ocurra nada en sus organizaciones.

Recomendaciones para un nuevo estándar de cambio

Si bien ningún evento de seguridad es idéntico al siguiente, se pueden aprender lecciones. A los directores de seguridad, les sugiero implementar de inmediato mis recomendaciones. No solo en esta instancia, sino también para el futuro:

  • Comprender su conectividad externa y la conectividad externa de la red de sus socios para solucionar los sistemas conectados a Internet con las siguientes mitigaciones.
  • Comprender su protección de seguridad actual y las capacidades que tienen que proteger, detectar un ataque y responder a este, y solucionar de inmediato los problemas que tienen en la red.
  • Garantizar que su protección DDoS esté fuera de sus centro de datos, porque si el tráfico llega a sus centros de datos, resultará difícil mitigar el ataque DDoS.
  • Garantizar que tienen protección contra DDoS para aplicaciones (capa 7) y garantizar que tienen firewall para aplicaciones web. Además, como práctica recomendada, garantizar que tienen protección DDoS total para DNS y firewalls para el tráfico de red (capa 3) y API
  • Garantizar que el servidor web y los parches del sistema operativo están implementados en todos los servidores web conectados a Internet. Además, garantizar que toda la automatización como las estructuras e imágenes Terraform estén completamente parcheadas para que las versiones anteriores de servidores web no se implementen sobre las imágenes seguras por accidente.
  • Como último recurso, consideren desactivar HTTP/2 y HTTP/3 (probablemente también vulnerable) para mitigar la amenaza. Esto solo debe hacerse como último recurso, porque habrá problemas significativos de rendimiento si bajan de nivel a HTTP/1.1
  • Consideren un proveedor secundario de DDoS L7 en la nube en el perímetro para lograr resiliencia.

La misión de Cloudflare es ayudar a mejorar el servicio de Internet para todos. Si te preocupa el estado actual de tu protección DDoS, nos complace ofrecerte de manera gratuita nuestras capacidades y resiliencia para DDoS para que puedas mitigar los intentos de un ataque DDoS. Sabemos la tensión por la que estás atravesando, ya que hemos estado luchando contra estos ataques durante los últimos 30 días y hemos hecho que nuestros sistemas, los mejores en su tipo, sean aún mejores.

Si necesitas más información, mira nuestro seminario web con los detalles de zero-day y cómo responder. Comunícate con nosotros si no estás seguro si estás protegido o quieres saber cómo estarlo. También tenemos más información técnica del ataque con más detalles en la publicación de otro blog: HTTP/2 Rapid Reset: deconstrucción de un ataque sin precedentes. Por último, si estás siendo objetivo del ataque o necesitas protección inmediata, comunícate con tu representante local de Cloudflare o visita https://www.cloudflare.com/under-attack-hotline/.

HTTP/2 Zero-Day-Sicherheitslücke führt zu rekordverdächtigen DDoS-Angriffen

Post Syndicated from Grant Bourzikas original http://blog.cloudflare.com/de-de/zero-day-rapid-reset-http2-record-breaking-ddos-attack-de-de/


Heute hat Cloudflare zusammen mit Google und Amazon AWS die Existenz einer neuartigen Zero-Day-Schwachstelle bekannt gegeben, die als „HTTP/2 Rapid Reset“-Angriff bezeichnet wird. Dieser Angriff nutzt eine Schwachstelle im HTTP/2-Protokoll aus, um enorme, hypervolumetrische Distributed Denial of Service (DDoS)-Angriffe zu generieren. Cloudflare hat in den letzten Monaten eine Flut dieser Angriffe abgewehrt, einschließlich eines Angriffs, der dreimal so groß war wie der größte Angriff, den wir bisher jemals verzeichnet hatten, und der 201 Millionen Anfragen pro Sekunde (rps) überstieg. Seit Ende August 2023 hat Cloudflare mehr als 1.100 weitere Angriffe mit über 10 Millionen rps abgewehrt – und 184 Angriffe, die unseren bisherigen DDoS-Rekord von 71 Millionen rps übertrafen.

Sie werden angegriffen oder benötigen zusätzlichen Schutz? Klicken Sie hier, um Hilfe zu erhalten.

Diese Zero-Day-Schwachstelle gab den Bedrohungsakteuren ein wichtiges neues Werkzeug in ihrem Werkzeugkasten an Schwachstellen an die Hand, mit dem sie ihre Opfer in einem noch nie dagewesenen Ausmaß ausnutzen und angreifen können. Diese Angriffe waren mitunter komplex und schwierig zu bekämpfen. Cloudflare bot sich dadurch jedoch die Gelegenheit, eine speziell konzipierte Technologie zu entwickeln, um die Auswirkungen der Zero-Day-Schwachstelle abzuwehren.

Wenn Sie Cloudflare für die HTTP-DDoS-Abwehr nutzen, sind Sie geschützt. Im Folgenden finden Sie weitere Informationen zu dieser Sicherheitslücke sowie Ressourcen und Empfehlungen, was Sie tun können, um sich zu schützen.

Alle Einzelheiten zum Angriff: Was jeder CSO wissen muss

Ende August 2023 entdeckte unser Team bei Cloudflare eine neue Zero-Day-Sicherheitslücke, die von einem unbekannten Bedrohungsakteur entwickelt wurde und das Standard-HTTP/2-Protokoll ausnutzt – ein grundlegendes Protokoll, das entscheidend dafür ist, wie das Internet und alle Websites funktionieren. Dieser neuartige Angriff auf eine Zero-Day-Sicherheitslücke namens „Rapid Reset“ nutzt die Stream-Abbruchfunktion von HTTP/2 aus, indem er eine Anfrage sendet und diese sofort wieder abbricht.  

Durch die Automatisierung dieses trivialen Musters von „Anfrage, Abbruch, Anfrage, Abbruch“-Musters im großen Stil sind Bedrohungsakteure in der Lage, eine Denial-of-Service-Situation herbeizuführen und jeden Server oder jede Anwendung, auf dem/der die Standardimplementierung von HTTP/2 läuft, lahmzulegen. Ein wichtiger Aspekt des Rekordangriffs ist die Tatsache, dass es sich um ein Botnetz von bescheidener Größe handelte, das aus etwa 20.000 Rechnern bestand. Cloudflare entdeckt regelmäßig Botnets, die um Größenordnungen größer sind als diese – sie bestehen aus Hunderttausenden und sogar Millionen von Rechnern. Die Tatsache, dass ein relativ kleines Botnet eine so große Menge an Anfragen ausgeben kann, die das Potenzial haben, nahezu jeden Server oder jede Anwendung, die HTTP/2 unterstützt, lahmzulegen, unterstreicht, wie bedrohlich diese Sicherheitslücke für ungeschützte Netzwerke ist.

Bedrohungsakteure nutzten Botnets in Verbindung mit der HTTP/2-Schwachstelle, um Anfragen in einem noch nie dagewesenen Ausmaß zu verstärken. Infolgedessen erlebte unser Team bei Cloudflare eine zeitweilige Instabilität der Edge. Obwohl unsere Systeme die meisten eingehenden Angriffe abwehren konnten, überlastete das Volumen einige Komponenten in unserem Netzwerk und beeinträchtigte die Performance einer kleinen Anzahl von Kunden mit zeitweiligen 4xx- und 5xx-Fehlern, die alle schnell behoben werden konnten.

Nachdem wir diese Probleme erfolgreich abgewehrt und potenzielle Angriffe für alle Kunden gestoppt hatten, leitete unser Team sofort einen Prozess zur verantwortungsvollen Offenlegung ein. Wir haben Gespräche mit Branchenkollegen aufgenommen, um herauszufinden, wie wir zusammenarbeiten können, um unser Ziel voranzubringen und den großen Anteil des Internets zu schützen, der auf unser Netzwerk angewiesen ist, bevor wir diese Schwachstelle der Öffentlichkeit bekannt geben.

Auf die technischen Details des Angriffs gehen wir in einem separaten Blogartikel näher ein: Alle Einzelheiten über HTTP/2 Rapid Reset.

Wie wehren Cloudflare und die Branche diesen Angriff ab?

Eine „perfekte Offenlegung“ gibt es nicht. Die Bekämpfung von Angriffen und die Reaktion auf neue Vorfälle erfordert von Unternehmen und Sicherheitsteams eine Denkweise, die einen Datenverstoß annimmt – denn es wird immer wieder neue Zero-Day-Angriffe, neue Gruppen von Bedrohungsakteuren und noch nie dagewesene neue Angriffe und Techniken geben.

Diese Denkweise ist eine wichtige Grundlage für den Informationsaustausch und gewährleistet in Fällen wie diesem, dass das Internet sicher bleibt. Während Cloudflare diese Angriffe verzeichnete und abwehrte, arbeiteten wir auch mit Branchenpartnern zusammen, um zu gewährleisten, dass die Branche als Ganzes diesem Angriff standhalten konnte.  

Im Zuge der Abwehr dieses Angriffs entwickelte unser Cloudflare-Team eine neue Technologie, um diese DDoS-Angriffe zu stoppen und unsere eigenen Abwehrmaßnahmen für diesen und andere zukünftige Angriffe großen Ausmaßes weiter zu verbessern. Diese Bemühungen haben unsere allgemeinen Abwehrmöglichkeiten und unsere Ausfallsicherheit insgesamt erheblich verbessert. Wenn Sie Cloudflare verwenden, sind wir sicher, dass Sie geschützt sind.

Unser Team hat auch Webserver-Softwarepartner benachrichtigt, die Patches entwickeln, um sicherzustellen, dass diese Sicherheitslücke nicht ausgenutzt werden kann – weitere Informationen finden Sie auf deren Websites.

Die Offenlegung ist nie ein Selbstläufer. Die Hauptaufgabe von Cloudflare ist es, für ein besseres Internet zu sorgen – genau das erreichen Fälle wie diese. Wenn wir die Möglichkeit haben, mit unseren Branchenpartnern und Behörden zusammenzuarbeiten, um sicherzustellen, dass es keine weitreichenden Auswirkungen auf das Internet gibt, tragen wir dazu bei, die Ausfallsicherheit jedes Unternehmens zu erhöhen, unabhängig von dessen Größe oder Branche.

Um ein besseres Verständnis der Abwehrtaktiken und der nächsten Schritte beim Patching erfahren möchten, registrieren Sie sich für unser Webinar.

Was sind die Ursprünge des HTTP/2 Rapid Reset und dieser rekordverdächtigen Angriffe auf Cloudflare?

Es mag seltsam erscheinen, dass Cloudflare eines der ersten Unternehmen war, das von diesen Angriffen betroffen war. Warum sollten Bedrohungsakteure ein Unternehmen angreifen, das über einige der weltweit robustesten Abwehrmechanismen gegen DDoS-Angriffe verfügt?  

Tatsächlich verzeichnet Cloudflare Angriffe oft, bevor sie auf anfälligere Ziele gerichtet werden. Bedrohungsakteure müssen ihre Tools entwickeln und testen, bevor sie sie in freier Wildbahn einsetzen. Bedrohungsakteure, die über rekordverdächtige Angriffsmethoden verfügen, können nur schwer testen und nachvollziehen, wie groß und effektiv sie sind, da sie nicht über die Infrastruktur verfügen, um die Angriffe, die sie starten, aufzufangen. Aufgrund der Transparenz, die wir in Bezug auf unsere Netzwerk-Performance bieten, und der Messungen der Angriffe, die sie aus unseren öffentlichen Performance-Diagrammen ablesen konnten, nahm dieser Bedrohungsakteur wahrscheinlich uns ins Visier, um das Potenzial des Exploits zu verstehen.

Aber diese Tests und die Möglichkeit, Angriffe frühzeitig zu erkennen, helfen uns, Abwehrmaßnahmen zu entwickeln, die sowohl unseren Kunden als auch der gesamten Branche zugute kommen.

Von CSO zu CSO: Was sollten Sie tun?

Ich bin seit über 20 Jahren CSO und habe unzählige Offenlegungen und Ankündigungen wie diese miterlebt. Aber ob Log4J, Solarwinds, EternalBlue WannaCry/NotPetya, Heartbleed, oder Shellshock, alle diese Sicherheitsvorfälle haben etwas gemeinsam. Eine gewaltige Explosion, die sich über die ganze Welt ausbreitet und die Gelegenheit bietet, alle von mir geleiteten Organisationen völlig aus dem Gleichgewicht zu bringen – unabhängig von der Branche oder der Größe.

Viele davon waren Angriffe oder Schwachstellen, die wir möglicherweise nicht kontrollieren konnten. Aber unabhängig davon, ob das Problem durch etwas entstanden ist, das in meinem Einflussbereich lag oder nicht: Was jede erfolgreiche Initiative, die ich geleitet habe, von denen unterschied, die nicht zu unseren Gunsten ausfielen, war die Fähigkeit, rasch zu reagieren, wenn Zero-Day-Schwachstellen und Exploits wie diese entdeckt wurden.    

Ich wünschte, ich könnte sagen, dass es bei Rapid Reset diesmal anders sein könnte, aber das ist nicht der Fall. Ich rufe alle CSOs auf – ganz gleich, ob Sie die jahrzehntelangen Sicherheitsvorfälle miterlebt haben, die ich erlebt habe, oder ob dies Ihr erster Tag im Job ist – jetzt ist der richtige Zeitpunkt, um sicherzustellen, dass Sie geschützt sind, und Ihr Team zur Vorfallsreaktion aufzustellen.

Wir haben die Informationen bis heute unter Verschluss gehalten, um möglichst vielen Sicherheitsanbietern die Möglichkeit zu geben, zu reagieren. Irgendwann ist es jedoch verantwortungsvoll, Zero-Day-Bedrohungen wie diese bekannt zu machen. Heute ist es soweit. Das bedeutet, dass die Bedrohungsakteure nach dem heutigen Tag weitgehend über die HTTP/2-Schwachstelle Bescheid wissen werden; und es wird unweigerlich trivial werden, sie auszunutzen. Dadurch beginnt der Wettlauf zwischen Verteidigern und Angreifern – patcht das Unternehmen schneller – oder werden die Angreifer noch schneller zuschlagen? Unternehmen sollten davon ausgehen, dass die Systeme getestet werden, und proaktive Maßnahmen ergreifen, um den Schutz zu gewährleisten.

Für mich erinnert dies an eine Schwachstelle wie Log4J, da täglich zahlreiche Varianten auftauchen und in den kommenden Wochen, Monaten und Jahren noch weitere hinzukommen werden. Wenn mehr Forscher und Bedrohungsakteure mit der Schwachstelle experimentieren, werden wir möglicherweise verschiedene Varianten mit noch kürzeren Ausnutzungszyklen finden, die noch fortschrittlichere Umgehungen enthalten.  

Und genau wie bei Log4J ist die Bewältigung solcher Vorfälle nicht einfach mit der Ausführung eines Patches zu bewerkstelligen. Sie müssen das Störfallmanagement, das Patchen und die Weiterentwicklung Ihrer Sicherheitsvorkehrungen zu kontinuierlichen Prozessen machen – denn die Patches für jede Variante einer Schwachstelle verringern Ihr Risiko, aber sie beseitigen es nicht.

Ich will keine Panikmache betreiben, aber ich sage es ganz direkt: Sie müssen das ernst nehmen. Behandeln Sie dies als aktiven Vorfall, um sicherzustellen, dass Ihrem Unternehmen nichts passiert.

Empfehlungen für einen neuen Veränderungsprozess

Kein Sicherheitsvorfall gleicht dem anderen, aber es gibt Lehren, die man daraus ziehen kann. Werte CSOs: Hier sind meine Empfehlungen, die sofort umgesetzt werden müssen. Nicht nur in diesem Fall, sondern auch in den kommenden Jahren:

  • Machen Sie sich mit der externen Konnektivität Ihres externen Netzwerks und des Netzwerks Ihrer Partner vertraut, um alle Systeme, die mit dem Internet verbunden sind, mit den nachstehenden Abwehrmaßnahmen zu schützen.
  • Machen Sie sich ein Bild von Ihrem bestehenden Sicherheitsschutz und den Möglichkeiten, die Sie zum Schutz, zur Erkennung und zur Reaktion auf einen Angriff haben, und beheben Sie sofort alle Probleme in Ihrem Netzwerk.
  • Stellen Sie sicher, dass sich Ihr DDoS-Schutz außerhalb Ihres Rechenzentrums befindet, denn wenn der Traffic in Ihr Rechenzentrum gelangt, wird es schwierig sein, den DDoS-Angriff abzuwehren.
  • Stellen Sie sicher, dass Sie über DDoS-Schutz für Anwendungen (Layer 7) und über Web Application Firewalls verfügen. Stellen Sie außerdem sicher, dass Sie über einen vollständigen DDoS-Schutz für DNS, Netzwerk-Traffic (Layer 3) und API-Firewalls verfügen, um eine optimale Vorgehensweise zu gewährleisten.
  • Stellen Sie sicher, dass Webserver- und Betriebssystem-Patches auf allen internetfähigen Webservern installiert sind. Stellen Sie außerdem sicher, dass alle Automatisierungen wie Terraform-Builds und -Images vollständig gepatcht sind, damit ältere Versionen von Webservern nicht versehentlich über die sicheren Images in der Produktion eingesetzt werden.
  • Als letzten Ausweg können Sie HTTP/2 und HTTP/3 (wahrscheinlich ebenfalls anfällig) deaktivieren, um die Bedrohung abzuwehren. Dies ist nur ein letzter Ausweg, da es zu erheblichen Performance-Problemen kommen wird, wenn Sie auf HTTP/1.1 zurückstufen.
  • Ziehen Sie einen sekundären, cloudbasierten DDoS-L7-Anbieter am Perimeter in Betracht, um die Ausfallsicherheit zu erhöhen.

Cloudflare hat es sich zur Aufgabe gemacht, ein besseres Internet zu schaffen. Wenn Sie mit Ihrem aktuellen DDoS-Schutz nicht zufrieden sind, stellen wir Ihnen gerne kostenlos unsere DDoS-Fähigkeiten und Ausfallsicherheit zur Verfügung, um alle Versuche eines erfolgreichen DDoS-Angriffs abzuwehren. Wir kennen den Stress, dem Sie ausgesetzt sind, denn wir haben diese Angriffe in den letzten 30 Tagen abgewehrt und unsere ohnehin schon erstklassigen Systeme noch weiter verbessert.

Wenn Sie mehr erfahren möchten, sehen Sie sich unser Webinar an. Darin erfahren Sie mehr über den Zero-Day und wie Sie darauf reagieren können. Kontaktieren Sie uns, wenn Sie sich nicht sicher sind, ob Sie geschützt sind, oder wenn Sie wissen möchten, wie Sie sich schützen können. Weitere technische Details zu dem Angriff finden Sie in einem eigenen Blogbeitrag: Alle Einzelheiten über HTTP/2 Rapid Reset. Noch etwas: Falls Sie angegriffen werden oder sofortigen Schutz benötigen, wenden Sie sich bitte an einen unserer Cloudflare-Mitarbeitenden vor Ort oder besuchen Sie https://www.cloudflare.com/de-de/under-attack-hotline/.

HTTP/2 Zero-Day 漏洞导致破纪录的 DDoS 攻击

Post Syndicated from Grant Bourzikas original http://blog.cloudflare.com/zh-cn/zero-day-rapid-reset-http2-record-breaking-ddos-attack-zh-cn/


今天早些时候,Cloudflare 与 Google 和 Amazon AWS 一起披露了一个名为 “HTTP/2 Rapid Reset” 攻击的新型 zero-day 漏洞的存在。此攻击利用 HTTP/2 协议中的弱点来生成巨大的超容量分布式拒绝服务 (DDoS) 攻击。近几个月来,Cloudflare 缓解了一系列攻击,其中一次攻击规模是我们之前观察到的任何攻击的三倍,每秒超过 2.01 亿个请求 (rps)。自 2023 年 8 月底以来,Cloudflare 已缓解了超过 1,100 起 RPS 超过 1000 万的其他攻击,其中 184 起攻击超过了我们之前 7100 万 RPS 的 DDoS 记录。

受到攻击或需要额外保护?单击此处获取帮助。

这个 zero-day 漏洞为威胁行为者提供了一个重要的新工具,即漏洞中的瑞士军刀,能够以前所未有的规模利用和攻击受害者。虽然这些攻击有时非常复杂且难以应对,但正是因为它们,Cloudflare 才有机会开发专用技术来缓解 zero-day 漏洞的影响。

如果您使用 Cloudflare 进行 HTTP DDoS 缓解,那么您已经受到保护。下面,我们将提供有关此漏洞的更多信息,以及如何确保自身安全的资源和建议。

解构攻击:每位 CSO 需要了解的内容

2023 年 8 月下旬,我们的 Cloudflare 团队注意到一个新的 zero-day 漏洞,该漏洞由未知威胁行为者开发,它所利用的标准 HTTP/2 协议是一种基本协议,对互联网和所有网站的正常运作至关重要。这种新型 zero-day 漏洞攻击被称为“Rapid Reset”,它利用 HTTP/2 的流取消功能,反复发送请求并立即取消该请求。  

透过大规模自动执行这种简单的“请求、取消、请求、取消”模式,威胁行为者能够建立拒绝服务并摧毁任何运行 HTTP/2 标准实施的服务器或应用程序。此外,关于这起破纪录的攻击,还有一个重要事项需要注意,它涉及一个中等规模的僵尸网路,由大约 20,000 台机器组成。 Cloudflare 会定期检测比这大几个数量级的僵尸网路——包括数十万甚至数百万台机器。对于一个相对较小的僵尸网络来说,输出如此大量的请求,有可能使几乎所有支持 HTTP/2 的服务器或应用程序瘫痪,这凸显了此漏洞对未受保护的网络的威胁有多大。

威胁行为者利用僵尸网络和 HTTP/2 漏洞,以前所未有的速度放大请求。因此,我们的 Cloudflare 团队经历了一些间歇性的边缘不稳定。虽然我们的系统能够缓解绝大多数传入攻击,但流量使我们网络中的某些组件过载,从而影响了少数客户的性能并出现间歇性 4xx 和 5xx 错误——所有这些都很快得到了解决。

在我们成功缓解了这些问题并阻止了所有客户的潜在攻击后,我们的团队立即启动了负责任的披露流程。在向公众公布这一漏洞之前,我们与业界同行进行了对话,探讨如何合作才能帮助我们完成使命,并保护依赖我们网络的大部分互联网用户的安全。

我们在另一篇博文中详细介绍了这次攻击的技术细节:HTTP/2 Rapid Reset:解构破纪录的攻击。

Cloudflare 和业界是如何遏止此次攻击的?

没有所谓的“完美披露”。阻止攻击和响应新出现的事件需要组织和安全团队以假定泄露的心态生活——因为总会有另一个 zero-day 漏洞、演变而来的新威胁行为者群体,以及前所未见的新型攻击和技术。

这种“假定泄露”的心态是信息共享和确保在这种情况下互联网保持安全的关键基础。在 Cloudflare 经历并缓解这些攻击的同时,我们还与行业合作伙伴合作,以确保整个行业能够抵御这种攻击。  

在缓解此攻击的过程中,我们的 Cloudflare 团队开发并专门构建了新技术来阻止这些 DDoS 攻击,并进一步改进我们针对此攻击和未来其他大规模攻击的缓解措施。这些努力显著提高了我们的整体缓解能力和弹性。如果您正在使用 Cloudflare,我们相信您会受到保护。

我们的团队还提醒正在开发补丁的 Web 服务器软件合作伙伴,以确保此漏洞不会被利用——请查看他们的网站以获取更多信息。

披露绝不是一劳永逸的。Cloudflare 的命脉是确保更好的互联网,这源于诸如此类的实例。我们有机会与行业合作伙伴和政府合作,确保互联网不会受到广泛影响,因此,我们正在尽自己的一份力量来提高每个组织的网络弹性,无论其规模或垂直领域如何。

要进一步了解缓解策略和后续修补措施,请登记参加我们的网络研讨会。

HTTP/2 Rapid Reset 和这些针对 Cloudflare 的破纪录攻击的起源是什么?

Cloudflare 是最先受到这些攻击的公司之一,这似乎有些奇怪。为什么威胁行为者要攻击一家拥有世界上最强大的 DDoS 攻击防御系统的公司?  

现实情况是,Cloudflare 经常在攻击转向更脆弱的目标之前就发现了它们。威胁行为者需要先开发和测试他们的工具,然后再将其实际部署。拥有破纪录攻击方法的威胁行为者可能会难以测试和了解它们的规模和有效性,因为他们没有基础结构来承担他们发起的攻击。由于我们分享网络性能的透明度,以及他们可以从我们的公开性能图表中收集到攻击测量结果,该威胁行为者很可能通过攻击我们来了解该漏洞的功能。

但这种测试以及尽早发现攻击的能力可以帮助我们开发针对攻击的缓解措施,从而使我们的客户和整个行业受益。

各位首席安全官的应对措施:您应该怎么做?

我担任首席安全官已有 20 多年,经历过无数次类似的披露和公告。但无论是 Log4J、Solarwinds、EternalBlue WannaCry/NotPetya、Heartbleed,还是 Shellshock,所有这些安全事件都有一个共同点。巨大的爆炸波及全球,并有可能彻底颠覆我所领导的任何组织——无论行业或规模如何。

其中许多是我们可能无法控制的攻击或漏洞。但无论问题的起因是否在我的控制范围之内,我所领导的任何成功计划与不利计划的区别在于,当识别这样的 zero-day 漏洞和利用时,我们能够做出回应。    

虽然我希望我可以说这次的 Rapid Reset 可能会有所不同,但事实并非如此。我呼吁所有的首席安全官,无论您是像我一样经历了数十年的安全事件,还是刚刚上任,现在都需要确保您受到保护,并支持您的网络事件响应团队 。

直到今天,我们一直对这些信息进行限制,以便让尽可能多的安全供应商有机会做出反应。不过,在某些时候,公开披露这样的 zero-day 威胁才是负责任的做法。今天就是公开的日子。这意味着今天之后,威胁行为者将在很大程度上意识到 HTTP/2 漏洞;攻击者将能够轻松利用这一漏洞,防御者与攻击者之间的竞赛也将无可避免——是先得到修补还是先被利用。组织应假定系统将受到攻击,并采取主动措施来进行保障。

对我来说,这让人想起像 Log4J 这样的漏洞,因为每天都会出现许多变体,并将在未来几周、几个月和几年内继续发挥作用。随着越来越多的研究人员和威胁行为者对该漏洞进行实验,我们可能会发现具有更短利用周期的不同变体,其中包含更高级的绕过方法。  

就像 Log4J 一样,管理此类事件并不像“运行补丁,大功告成”那么简单。您需要将事件管理、修补和发展安全保护转变为持续的流程,因为针对每个漏洞变体的修补程序可以降低您的风险,但并不能消除风险。

我无意危言耸听,但我要直截了当地说:你们必须认真对待这件事。将此视为一个完全活动的事件,以确保您的组织不会发生任何事情。

新变革标准的建议

虽然安全事件各不相同,但还是可以从中吸取教训。首席安全官们,以下是我提出的必须立即实施的建议。不仅是针对此次漏洞,今后几年也是如此:

  • 了解您的外部网络和合作伙伴网络的连接情况,利用以下缓解措施修复任何面向互联网的系统。
  • 了解您现有的安全保护措施以及保护、检测和应对攻击的能力,并立即修复网络中存在的任何问题。
  • 确保 DDoS 防护位于数据中心之外,因为如果流量进入数据中心,将很难缓解 DDoS 攻击。
  • 确保您拥有针对应用程序(第 7 层)的 DDoS 防护,并确保您拥有 Web 应用程序防火墙。此外,作为最佳实践,确保您拥有针对 DNS、网络流量(第 3 层)和 API 防火墙的完整 DDoS 防护。
  • 确保在所有面向互联网的 Web 服务器上都部署了 Web 服务器和操作系统补丁。此外,请确保所有自动化(例如 Terraform 构建和映像)都已完全修补,以便旧版本的 Web 服务器不会意外地通过安全映像部署到生产环境中。
  • 在万不得已的情况下,可以考虑关闭 HTTP/2 和 HTTP/3(可能也容易受到攻击)以减轻威胁。这只是最后的手段,因为如果降级到 HTTP/1.1,会出现严重的性能问题。
  • 考虑在周边使用基于云的辅助 DDoS L7 提供商以提高弹性。

Cloudflare 的使命是帮助构建更好的互联网。如果您担心当前的 DDoS 防护状态,我们非常乐意免费为您提供我们的 DDoS 功能和弹性,以缓解任何成功的 DDoS 攻击尝试。我们知道您面临的压力,因为我们在过去 30 天里抵御了这些攻击,并使我们本已一流的系统变得更好。

如果您有兴趣了解更多信息,请观看我们的网络研讨会,了解 zero-day 的详细信息以及应对方式。如果您不确定自己是否受到保护或想了解如何受到保护,请联系我们。我们还在另一篇博文中详细介绍了这次攻击的更多技术细节:HTTP/2 Rapid Reset:解构破纪录的攻击。最后,如果您是攻击目标或需要立即保护,请联系您当地的 Cloudflare 代表或访问 https://www.cloudflare.com/zh-cn/under-attack-hotline/。

HTTP/2 zero-day脆弱性により史上最大のDDoS攻撃が発生

Post Syndicated from Grant Bourzikas original http://blog.cloudflare.com/ja-jp/zero-day-rapid-reset-http2-record-breaking-ddos-attack-ja-jp/


本日未明、Cloudflareは、GoogleおよびAmazon AWSとともに、「HTTP/2 Rapid Reset」攻撃と名付けられた新種の脆弱性(zero-day )の存在を公表しました。この攻撃は、HTTP/2プロトコルの弱点を悪用し、巨大で超ボリューメトリックな分散サービス妨害(DDoS)攻撃を発生させます。Cloudflareはここ数カ月間、こうした嵐のような攻撃の軽減に取り組んでいました。その中には 、1秒間に2億100万リクエスト(rps)を超える、弊社がこれまでに観測した最大の攻撃の3倍ほどの規模となる攻撃も含まれています。2023年8月末以降、Cloudflareはその他の1,000万rpsを超える攻撃を1,100回以上軽減しましたが、この間DDoSの最大記録である7,100万rpsを超える攻撃が184回にも及びました。

攻撃を受けていますか?それとも、保護を追加したいですか?ヘルプを受けるには、こちらをクリックしてください。

攻撃を受けていますか?それとも、保護を追加したいですか? ヘルプを受けるには、こちらをクリックしてください。

このzero-dayは、脅威アクターたちに、脆弱性の解析ツールであるスイスアーミーナイフを悪用して被害者を攻撃することができる、今までにない全く新しいツールを提供したのです。 これらの攻撃に対する対処は複雑で困難を伴うものでしたが、このような攻撃は、Cloudflareにとって、zero-dayの脆弱性の影響を軽減する特別な技術開発の機会となりました。

Cloudflareを使用しているのであれば、HTTPのDDoSは軽減され、保護されています。 以下、この脆弱性に関する詳細情報と、安全確保のためのリソースと推奨事項を掲載します。

攻撃のデコンストラクション(脱構築):すべてのCSOが知るべきこと

2023年8月下旬、弊社のチーム(Cloudflare zero-day)は、Standard HTTP/2プロトコル(インターネットとすべてのWebサイトが機能するために重要な基本プロトコル)を悪用する、未知の脅威行為者によって開発された新たな脆弱性を観測しました。Rapid Resetと名付けられたこの新しいzero-day 脆弱性攻撃は、HTTP/2のStreamキャンセル機能を利用し、リクエストを送信して即座にキャンセルすることを何度も繰り返すものです。  

この単純な「リクエスト、キャンセル、リクエスト、キャンセル」パターンを大規模に自動化することで、脅威アクターはサービス拒否を作り出し、HTTP/2の実装(Standard )を実行しているサーバーやアプリケーションを停止させることができるのです。 さらに、この記録的な攻撃について注目すべき重要な点は、およそ20,000台のマシンで構成される控えめな規模のボットネットが関与していたことです。 Cloudflareは、数十万台から数百万台のマシンで構成される、これよりも桁違いに大規模なボットネットを定期的に検出しています。 比較的小規模なボットネットが、HTTP/2をサポートするほぼすべてのサーバーやアプリケーションを無力化してしまうほどの可能性を秘め、これほど大量のリクエストを出力するという事実は、この脆弱性が無防備なネットワークにとっていかに脅威となるかを強調しています。

脅威アクターはHTTP/2の脆弱性とボットネットを併用し、これまでにない速度でリクエストを増幅させました。 その結果、Cloudflareのチームは、断続的にエッジが不安定になるという体験をしました。 当社のシステムは圧倒的多数の着信攻撃を軽減することができましたが、その量はネットワーク内のいくつかのコンポーネントに過負荷をかけ、断続的に4xxおよび5xxエラーが発生し、少数のお客様のパフォーマンスに影響を与えました。

これらの問題を軽減し、すべての顧客に対する潜在的な攻撃を停止させることに成功した後、弊社のチームは直ちに責任ある情報開示プロセスを開始しました。 この脆弱性を一般に公表する前に、どのように弊社のミッションを前進させ、弊社のネットワークに依存しているインターネットの大部分を保護するために協力できるかについて、同業者と話し合いました。

この攻撃の技術的な詳細については、別のブログ記事で取り上げています。 HTTP/2 Rapid Reset: 記録的な攻撃のデコンストラクション(脱構築)。

Cloudflareと業界はこの攻撃をどのように阻止しているのでしょうか?

「完全な情報開示」というものは存在しません。 攻撃を阻止し、新たなインシデントに対応するためには、組織やセキュリティチームが常に侵害を想定したマインドセットが必要です。なぜなら、zero-day 、新たな進化を遂げる脅威アクターグループ、今までにはないような斬新な攻撃やテクニックが常に存在するからです。

この「違反を想定」するマインドセットは、情報共有のための重要な基盤であり、インターネットの安全性を確保するものとなります。 Cloudflareは、このような攻撃を経験・軽減しつつ、業界全体がこの攻撃に耐えられることを保証するために、業界のパートナーと協力します。  

この攻撃を軽減する過程で、弊社のCloudflareチームは、このような DDoS攻撃を阻止するための新技術を開発・構築し、この攻撃のみならず今後発生するその他の大規模な攻撃に対しても、弊社独自の軽減策をさらに改善してきました。 こうした取り組みにより、全体的な軽減能力と回復力が大幅に向上した。 Cloudflareを使用している場合、保護されていると確信しています。

また、この脆弱性を悪用されないようにするためのパッチを開発しているWebサーバーソフトウェアパートナーにも警告を発しました。 — 詳細は同社のWebサイトを参照してください。

情報開示は1回で終わりません。 Cloudflareの生命線は、より良いインターネットを確保することであり、それはこのような事例から生じています。 インターネットに広範な影響が及ばないよう、業界パートナーや政府と協力する機会があれば、規模や業種を問わず、あらゆる組織のサイバー耐性を向上させる弊社の役割を果たします。

パッチを適用する際の緩和策や次のステップに関する理解を深めるために、弊社のウェビナーにご参加ください 。

HTTP/2 Rapid Resetと、Cloudflare に対するこれらの記録的な攻撃のオリジンは何ですか?

Cloudflareが、こうした攻撃を最初に観測した企業のひとつであることは奇妙に思えるかもしれません。 DDoS攻撃に対して世界で最も強固な防御を持つ企業を、なぜ脅威アクターが攻撃するのでしょうか?  

実際、Cloudflareは、攻撃がより脆弱なターゲットに向けられる前に、時折攻撃を観測します。 脅威アクターは、ツールを実際の攻撃のためにデプロイする前に、ツールを開発し、テストする必要があります。 記録的な攻撃手法を持つ脅威アクターにとって、その攻撃手法がどれほど大規模で効果的なものかをテストし、把握することは極めて困難といえるでしょう。その攻撃を受け止めるだけのインフラストラクチャがないからです。弊社はネットワークパフォーマンスに関する透明性を共有し、公開されているパフォーマンスチャートから攻撃の測定値を得ることがでるため、この脅威アクターは悪用能力を把握するために弊社をターゲットにしたと考えられます。

しかしこのテストと、攻撃の早期発見能力は、弊社の攻撃緩和策の開発に役立ち、顧客と業界全体の両方に利益をもたらすことになるのです。

CSOからCSOへ:何をすべきですか?

私は20年以上CSOを務めており、このような情報開示や発表を数え切れないほど経験しました。しかし 、 Log4J で あれ、 Solarwindsであれ、 EternalBlue WannaCry/NotPetyaであれ、Heartbleed であれ、 Shellshock であれ、セキュリティインシデントには共通点があります。凄まじい爆発が世界中に波及し、私が率いたあらゆる組織を完全に混乱させるおそれがあるのです—業界や規模に関わりなくです。

これらの多くは、私たちが制御できなかったかもしれない攻撃や脆弱性だったのです。 しかし、この問題が私の制御できるところから生じたか否かにかかわらず、私が主導して成功したイニシアチブを、私たちに有利に傾かなかった多層防御と区別したのは、このようなzero-day脆弱性やエクスプロイトが特定されたときに対応する能力だったのです。    

今回のRapid Resetは違うと言いたいところですが、そうではありません。 私はすべてのCSOにこう呼びかけています—私のように何十年もセキュリティインシデントを経験してきた人であっても、今日が勤務初日という人であっても、サイバーインシデント対応チームを立ち上げ、確実な保護対策を取るべきです—今こそその時なのです。

できるだけ多くのセキュリティベンダーに対して対応する機会を与えるため、今日まで情報を制限してきました。 しかし、ある時点で、このようなzero-day脅威を公開する責任が生じました。 今日がその日なのです。 つまり、今日以降、脅威アクターはHTTP/2の脆弱性をかなりの部分把握することになるので、その悪用は必然的に容易になり、防御側と攻撃側の間の競争—パッチを当てるのが先か、悪用するのが先かが始まるのです。 組織は、システムがテストされることを想定し、確実に保護するための事前対策を講じるべきなのです。

これはLog4Jのような脆弱性を思い出させます。多くの亜種が日々出現し、そして今後数週間、数カ月、数年と出現し続けることでしょう。 より多くのリサーチャーや脅威アクターがこの脆弱性を試すようになれば、さらに高度なバイパスを含む、より短い悪用サイクルを持つ別の亜種が見つかるかもしれません。  

Log4Jと同様、このようなインシデントの管理は「パッチを当てて完了」というような単純なものではありません。 インシデント管理、パッチ適用、セキュリティ保護の進化を、継続的なプロセスに変える必要があるのです。なぜなら、脆弱性の亜種ごとにパッチを適用してリスクを軽減させることはできても、解消されるわけではないからです。

警鐘を鳴らすつもりはないですが、単刀直入に言います。これを真剣に受け止めてください。 組織に何も起こらないように、必ずアクティブなインシデントとして扱ってください。

新たな変更基準のための推奨事項

セキュリティー上の出来事は、一つとして同じものはなく、またそれらから多くのことが学べます。 CSOの皆さん、すぐに実行に移さなければならない推奨事項をここでお伝えします。 今回だけでなく、この先何年間にも渡って実行してください。

  • 外部ネットワークおよびパートナーネットワークの外部接続を理解し、インターネットに接続しているシステムは次の緩和策を実施してください。
  • 既存のセキュリティ保護と、保護すべき能力を理解し、攻撃を検出し、対応し、ネットワークに問題があれば直ちに修復します。
  • DDoS攻撃対策が、必ずデータセンターの外にあるようにしてください。トラフィックがデータセンターに到達してしまうと、DDoS攻撃を軽減することが難しくなるからです。
  • DDoS攻撃対策アプリケーション(レイヤー7)、およびWebアプリケーションファイアウォールを確保してください。 さらに、ベストプラクティスとして、DNS、ネットワークTraffic(レイヤー3)、APIファイアウォールに対する完全なDDoS攻撃対策を確実に保持してください。
  • Webサーバーおよびオペレーティングシステムのパッチが、インターネットに接続しているWebサーバーに導入されているようにします。 また、Terraformのビルドやイメージのようなすべての自動化が完全にパッチされていることを確認し、旧バージョンのWebサーバが誤ってセキュアなイメージ上でプロダクションにデプロイされないようにします。
  • 最後の手段として、脅威を軽減するためにHTTP/2とHTTP/3(これも脆弱である可能性が高い)をオフにすることを検討してください。  なぜなら、HTTP/1.1にダウングレードすると、パフォーマンスに大きな問題が生じるからです。
  • レジリエンスを持たせるために、セカンダリでクラウドベースの DDoS L7 プロバイダーをペリメータ―(境界)で検討してください。

Cloudflareのミッションは、より良いインターネットの構築を支援することです。 DDoS攻撃対策の現状に不安を感じるお客様には、DDoS攻撃を軽減するために、弊社のDDoS能力とレジリエンスを無料で提供させていただきます。この30日間、弊社はこのような攻撃と戦いながら、クラス最高のシステムをさらに向上させてきました。

さらに詳しくお知りになりたい方は、zero-dayの詳細と対応方法に関するウェビナーをご覧ください。保護されているかどうか不明な場合、またはどのように保護されるのか知りたい場合は、お問い合わせください。また、この攻撃の技術的な詳細につきましては、別のブログ記事HTTP/2 Rapid Reset: 記録的な攻撃を脱構築するで詳しく解説しております。最後に、攻撃の標的にされている場合、または早急な保護が必要な場合は、お近くのCloudflare 担当者にお問い合わせいただくか、 https://www.cloudflare.com/ja-jp/under-attack-hotline/をご覧ください。

HTTP/2 Zero-Day 漏洞導致破紀錄的 DDoS 攻擊

Post Syndicated from Grant Bourzikas original http://blog.cloudflare.com/zh-tw/zero-day-rapid-reset-http2-record-breaking-ddos-attack-zh-tw/


今天早些時候,Cloudflare 與 Google 和 Amazon AWS 一起披露了一個新型 zero-day 漏洞的存在,名為「HTTP/2 Rapid Reset」攻擊。此攻擊利用 HTTP/2 通訊協定中的弱點來產生巨大的超容量分散式阻斷服務 (DDoS) 攻擊。近幾個月來,Cloudflare 緩解了一系列此類攻擊,其中包括一起比我們之前觀察到的任何攻擊規模大三倍的攻擊,每秒要求數 (rps) 超過 2.01 億。自 2023 年 8 月底以來,Cloudflare 緩解了超過 1,100 起 rps 超過 1000 萬的其他攻擊,其中 184 起攻擊超過了我們之前 7100 萬 rps 的 DDoS 記錄。

正在遭受攻擊或需要額外保護?請按一下這裡以取得幫助.

這個 zero-day 漏洞為威脅執行者提供了一個重要的新工具,即漏洞中的瑞士軍刀,能夠以前所未有的規模利用和攻擊受害者。雖然這些攻擊有時非常複雜且難以應對,但正是因為它們,Cloudflare 才有機會開發專用技術來減輕 zero-day 漏洞的影響。

如果您使用 Cloudflare 進行 HTTP DDoS 緩解,則會受到保護。我們在下文提供了有關此漏洞的更多資訊,以及有關您可以採取哪些措施來保護自己的資源和建議。

解構攻擊:每個 CSO 需要瞭解的事情

2023 年 8 月下旬,我們的 Cloudflare 團隊注意到一個由未知威脅執行者開發的新 zero-day 漏洞,它所利用的標準 HTTP/2 通訊協定是一種基本通訊協定,對網際網路和所有網站的正常運作至關重要。這種新穎的 zero-day 漏洞攻擊稱為 Rapid Reset,它利用 HTTP/2 的串流取消功能,一次又一次地傳送要求並立即取消它。  

透過大規模自動執行這種簡單的「要求、取消、要求、取消」模式,威脅執行者能夠建立阻斷服務並摧毀任何執行 HTTP/2 標準實作的伺服器或應用程式。此外,關於這起破紀錄的攻擊,還有一個重要事項需要注意,它涉及一個中等規模的殭屍網路,由大約 20,000 台機器組成。Cloudflare 會定期偵測比它大幾個數量級的殭屍網路 — 包括數十萬甚至數百萬台機器。對於一個相對較小的殭屍網路來說,輸出如此大量的要求,有可能使幾乎所有支援 HTTP/2 的伺服器或應用程式癱瘓,這凸顯了此漏洞對未受保護的網路的威脅有多大。

威脅執行者將殭屍網路與 HTTP/2 漏洞結合使用,以我們從未見過的速度放大了要求。因此,我們的 Cloudflare 團隊經歷了某種間歇性的邊緣不穩定。雖然我們的系統能夠緩解絕大部分傳入的攻擊,但這些流量會使我們網路中的部分元件過載,從而影響少數客戶的效能,並出現間歇性的 4xx 和 5xx 錯誤,而所有這些錯誤都被迅速解決了。

在我們為所有客戶成功緩解這些問題並阻止潛在攻擊之後,我們的團隊立即開始了負責任的披露程序。我們與業內同行進行了對話,看看我們如何共同努力,幫助推進我們的使命,並在向公眾發布此漏洞之前保護依賴我們網路的大部分網際網路。

我們在另一篇部落格文章中更詳細地介紹了該攻擊的技術細節:HTTP/2 Rapid Reset:解構破紀錄的攻擊。

Cloudflare 和業界如何遏止這種攻擊?

「完美的披露」並不存在。而遏止攻擊和回應新出現的事件需要組織和網路安全團隊以假定違規的心態生活 — 因為總會有另一個 zero-day 漏洞、新發展的威脅執行者團體以及前所未見的新穎攻擊和技術。

這種「假定違規」的心態是資訊分享以及在這種情況下確保網際網路保持安全的重要基礎。在 Cloudflare 遭遇並緩解這些攻擊的同時,我們也與業界合作夥伴合作,以確保整個產業能夠抵禦這種攻擊。  

在緩解此攻擊的過程中,我們的 Cloudflare 團隊開發並專門構建了新技術來阻止這些 DDoS 攻擊,並進一步改進了我們自己的緩解措施來應對此攻擊和未來其他大規模攻擊。這些努力顯著提高了我們的整體緩解功能和復原能力。如果您使用 Cloudflare,我們相信您會受到保護。

我們的團隊也提醒正在開發修補程式以確保此漏洞不會被利用的 Web 伺服器軟體合作夥伴 — 請檢查網站以獲取更多資訊。

披露絕不是一勞永逸的事情。Cloudflare 的命脈是確保更好的網際網路,而這源於諸如此類的實例。當我們有機會與業界合作夥伴和政府合作,以確保網際網路不會受到廣泛影響時,我們正在盡自己的一份力量來提高每個組織的網路復原能力,無論其規模多大或類別為何。

若要深入瞭解緩解策略和下一步修補行動,請報名參加我們的網路研討會。

HTTP/2 Rapid Reset 和這些針對 Cloudflare 的破紀錄攻擊的起因是什麼?

奇怪的是,Cloudflare 竟然是最早目睹這些攻擊的公司之一。為什麼威脅執行者會攻擊一間擁有世界上最強大的 DDoS 攻擊防禦能力的公司?  

實際情況是,Cloudflare 經常在攻擊轉向更脆弱的目標之前就發現了攻擊。威脅執行者在將工具部署到外部環境之前,需要先進行開發和測試。威脅執行者雖然掌握了破紀錄攻擊方法,但很難測試並瞭解攻擊的規模和有效性,因為他們沒有基礎架構可以承受他們發起的攻擊。由於我們分享網路效能的透明度,而且他們可以從我們的公開效能圖表中收集到攻擊測量結果,因此,威脅執行者很可能針對我們發起攻擊,藉此來瞭解該漏洞利用的功能。

但這項測試以及提早發現攻擊的能力,有助於我們針對攻擊開發緩解措施,從而使我們的客戶和整個產業受益。

從 CSO 到 CSO:您應該怎麼做?

我擔任了 20 多年的 CSO,接受過無數這樣的披露和公告。不過,無論是 Log4J、Solarwinds、EternalBlue WannaCry/NotPetya、Heartbleed 還是 Shellshock,所有這些安全事件都有一個共通性。一場大爆炸在全球蔓延並創造機會,徹底顛覆了我所領導的任何組織,無論產業或規模如何。

其中許多攻擊或漏洞都是我們無法控制的。但無論問題的起因是否在我的控制範圍之內,我所領導的任何成功計畫與那些不利於我們的計畫的區別在於,當識別這樣的 zero-day 漏洞和利用時,我們能夠做出回應。    

雖然我希望我可以說這次的 Rapid Reset 可能會有所不同,但事實並非如此。無論你們是像我這樣經歷過數十年安全事件的洗禮,還是第一天從事這項工作,我都呼籲所有的 CSO,此刻正是確保你們受到保護,並支援網路事件回應團隊的時候。

我們直到今天才公開這些資訊,以讓盡可能多的安全廠商有機會做出反應。然而,在某些時候,公開披露這樣的 zero-day 威脅才是真正負責任的行為。而今天就是那一天。這意味著在今天之後,威脅執行者大多會意識到 HTTP/2 漏洞;而且,利用和啟動防禦者與攻擊者之間的競賽將不可避免地變得微不足道 — 先修補與先利用。組織應假設系統會遭受測試,並採取主動措施以確保保護。

對我來說,這會讓我想起像 Log4J 這樣的漏洞,由於每天都出現許多變體,因此,在未來幾週、幾個月甚至幾年內會不斷地取得成果。隨著越來越多的研究人員和威脅執行者對此漏洞進行實驗,我們可能會發現利用週期更短的不同變體,其中包含更高級的繞過方法。  

就像 Log4J 一樣,管理此類事件並不像「執行修補程式,現在就完成了」那麼簡單。您需要將事件管理、修補和發展安全保護措施轉變為持續進行的流程,這是因為針對每個漏洞變體的修補程式可以降低您的風險,但並不能消除風險。

我無意危言聳聽,但我會直接說:你必須認真對待此事。將此事視為一個完全活動的事件,以確保您的組織平安無事。

對新變革標準的建議

雖然沒有任何一個安全事件會與下一個完全相同,但我們可以從中汲取一些教訓。CSO 們,以下是我的建議,必須立即實施。不僅在這種情況下,而且在未來的幾年中也一樣:

  • 瞭解您的合作夥伴網路的外部連線,來透過以下緩解措施補救任何面向網際網路的系統。
  • 瞭解您現有的安全保護措施以及您擁有的用於保護、偵測和回應攻擊的功能,並立即修復您網路中遇到的任何問題。
  • 確保將 DDoS 保護部署在您的資料中心外部,因為如果流量到達資料中心,DDoS 攻擊將很難緩解。
  • 確保您為應用程式(第 7 層)提供 DDoS 保護,並確保部署了 Web 應用程式防火牆。此外,作為最佳做法,請確保您為 DNS、網路流量(第 3 層)和 API 防火牆提供完整的 DDoS 保護
  • 確保在所有面向網際網路的 Web 伺服器上部署 Web 伺服器和作業系統修補程式。此外,請確保所有自動化(例如,Terraform)組建和映像均已完全修補,這樣舊版 Web 伺服器就不會意外地透過安全映像部署到生產環境中。
  • 最後一招,請考慮關閉 HTTP/2 和 HTTP/3(可能也易受攻擊)來緩解威脅。這只是萬不得已才能使用的手段,因為如果降級到 HTTP/1.1,將會出現重大的效能問題
  • 考慮在邊界使用基於雲端的輔助 DDoS 第 7 層提供者以提高復原能力。

Cloudflare 的使命是幫助構建更好的網際網路。如果您擔心目前的 DDoS 保護狀態,我們非常樂意免費為您提供 DDoS 功能和復原能力,以緩解任何成功的 DDoS 攻擊嘗試。我們知道您所面臨的壓力,因為我們在過去 30 天內擊退了這些攻擊,並使我們本已最佳的系統變得更加完美。

如果您有興趣瞭解更多資訊,請觀看我們的網路研討會,以詳細瞭解 zero-day 漏洞以及如何應對。如果您不確定自己是否受到保護或想瞭解如何受到保護,請與我們聯絡。我們也在另一篇部落格文章中更詳細地介紹了有關該攻擊的更多技術細節: HTTP/2 Rapid Reset:解構破紀錄的攻擊。最後,如果您成為攻擊目標或需要即時保護,請聯絡您當地的 Cloudflare 代表或造訪https://www.cloudflare.com/zh-tw/under-attack-hotline/。

HTTP/2 Rapid Reset:解构这场破纪录的攻击

Post Syndicated from Lucas Pardue original http://blog.cloudflare.com/zh-cn/technical-breakdown-http2-rapid-reset-ddos-attack-zh-cn/


从 2023 年 8 月 25 日开始,我们开始注意到一些异常大量的 HTTP 攻击袭击了我们的许多客户。我们的自动化 DDoS 系统检测到并缓解了这些攻击。然而,没过多久,它们就开始达到破纪录的规模 – 最终达到了每秒 2.01 亿次请求的峰值。此数量几乎是我们以前最大攻击记录数量的 3 倍。

受到攻击或需要额外保护? 单击此处获取帮助。

而更令人担忧的是,攻击者能够利用一个只有 20,000 台机器的僵尸网络发起这样的攻击。而如今有的僵尸网络由数十万或数百万台机器组成。整个 web 网络通常每秒处理10-30 亿个请求,因此使用此方法可以将整个 web 网络的请求数量等级集中在少数目标上,而这并非不可想象。

检测和缓解

这是一种规模空前的新型攻击手段,Cloudflare 现有的保护措施在很大程度上能够抵御这种攻击的冲击。虽然最初我们看到了对客户流量的一些影响(在第一波攻击期间影响了大约1% 的请求),但今天我们已经能够改进我们的缓解方法,以阻止任何针对Cloudflare 客户的攻击,并保证自身的系统正常运行。

我们注意到这些攻击的同时,谷歌和 AWS 这两大行业巨头也发现了同样的情况。我们努力加固 Cloudflare 的系统,以确保目前我们所有的客户都能免受这种新的 DDoS 攻击方法的影响,而不会对客户造成任何影响。我们还与谷歌和 AWS 共同参与了向受影响的供应商和关键基础设施提供商披露攻击事件的协调工作。

这种攻击是通过滥用 HTTP/2 协议的某些功能和服务器实施详细信息实现的(详情请参见 CVE-2023-44487)。由于该攻击滥用了 HTTP/2 协议中的一个潜在弱点,我们认为实施了 HTTP/2 的任何供应商都会受到攻击。这包括所有现代网络服务器。我们已经与谷歌和 AWS 一起向网络服务器供应商披露了攻击方法,我们希望他们能够实施补丁。与此同时,最好的防御方法是在任何面向网络的 Web 服务器或 API 服务器前面使用诸如 Cloudflare 之类的 DDoS 缓解服务。

这篇文章深入探讨了 HTTP/2 协议的详细信息、攻击者利用来实施这些大规模攻击的功能,以及我们为确保所有客户受到保护而采取的缓解策略。我们希望通过公布这些详细信息,其他受影响的 Web 服务器和服务能够获得实施缓解策略所需的信息。此外,HTTP/2 协议标准团队以及开发未来 Web 标准的团队可以更好地设计这些标准,以防止此类攻击。

RST 攻击详细信息

HTTP 是为 Web 提供支持的应用协议。HTTP 语义对于所有版本的 HTTP 都是通用的 — 整体架构、术语和协议方面,例如请求和响应消息、方法、状态代码、标头和尾部字段、消息内容等等。每个单独的 HTTP 版本都定义了如何将语义转换为“有线格式”以通过 Internet 进行交换。例如,客户端必须将请求消息序列化为二进制数据并发送,然后服务器将其解析回它可以处理的消息。

HTTP/1.1 使用文本形式的序列化。请求和响应信息以 ASCII 字符流的形式进行交换,通过可靠的传输层(如 TCP)发送,使用以下格式(其中 CRLF 表示回车和换行):

 HTTP-message   = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

例如,对于 https://blog.cloudflare.com/ 的一个非常简单的 GET 请求在线路上将如下所示:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

响应将如下所示:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

这种格式在线路上构造消息,这意味着可以使用单个 TCP 连接来交换多个请求和响应。但是,该格式要求每条消息都完整发送。此外,为了正确地将请求与响应关联起来,需要严格的排序;这意味着消息是串行交换的并且不能多路复用。https://blog.cloudflare.com/ 和 https://blog.cloudflare.com/page/2/ 的两个 GET 请求将是:

GET / HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLFGET /page/2/ HTTP/1.1 CRLFHost: blog.cloudflare.comCRLFCRLF

With the responses:

HTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>CRLFHTTP/1.1 200 OK CRLFServer: cloudflareCRLFContent-Length: 100CRLFtext/html; charset=UTF-8CRLFCRLF<100 bytes of data>

Web 页面需要比这些示例更复杂的 HTTP 交互。访问 Cloudflare 博客时,您的浏览器将加载多个脚本、样式和媒体资产。如果您使用 HTTP/1.1 访问首页,然后很快决定导航到第 2 页,您的浏览器可以从两个选项中进行选择。要么在第 2 页开始之前等待对您不再需要的页面的所有已排入队列的响应,要么通过关闭 TCP 连接并打开一个新连接来取消进行中的请求。这两种方法都不太实用。浏览器往往通过管理 TCP 连接池(每台主机最多 6 个连接)并在池上实现复杂的请求分派逻辑来绕过这些限制。

HTTP/2 解决了 HTTP/1.1 的许多问题。每个 HTTP 消息都被序列化为一组 HTTP/2 帧,这些帧具有类型、长度、标志、流标识符 (ID) 和有效负载。流 ID 清楚地表明线路上的哪些字节适用于哪个消息,从而允许安全的多路复用和并发。流是双向的。客户端发送帧,服务器使用相同的 ID 回复帧。

在 HTTP/2 中,我们对 https://blog.cloudflare.com 的 GET 请求将通过流 ID 1 交换,客户端发送一个 HEADERS 帧,服务器使用一个 HEADERS 帧进行响应,后跟一个或多个 DATA 帧。客户端请求始终使用奇数流 ID,因此后续请求将使用流 ID 3、5 等。可以以任何顺序提供响应,并且来自不同流的帧可以交织。

流多路复用和并发是 HTTP/2 的强大功能。它们可以更有效地使用单个 TCP 连接。HTTP/2 优化了资源获取,尤其是在与优先排序相结合时。另一方面,与 HTTP/1.1 相比,让客户端更容易启动大量并行工作会增加对服务器资源的峰值需求。这显然是拒绝服务的一个载体。

为了提供一些防护措施,HTTP/2 提供了最大活动并发流的概念。SETTINGS_MAX_CONCURRENT_STREAMS 参数允许服务器公布其并发限制。例如,如果服务器声明限制为 100,那么任何时候都最多只能有 100 个请求处于活动状态。如果客户端试图打开超过此限制的流,服务器一定会使用 RST_STREAM 帧拒绝它。流拒绝不会影响连接上的其他正在进行中的流。

真实情况要复杂一些。流有生命周期。下面是 HTTP/2 流状态机的示意图。客户端和服务器管理各自的流状态视图。当发送或接收 HEADERS、DATA 和 RST_STREAM 帧时,它们会触发转换。虽然流状态的视图是独立的,但它们是同步的。

HEADERS 和 DATA 帧包含一个 END_STREAM 标志,当设置为 1 (true) 时,可触发状态转换。

让我们通过一个没有消息内容的 GET 请求示例来解决这个问题。客户端以 HEADERS 帧的形式发送请求,并将 END_STREAM 标志设置为 1。客户端首先将流从空闲状态转换为打开状态,然后立即转换为半关闭状态。客户端半关闭状态意味着它不能再发送HEADERS或DATA,只能发送 WINDOW_UPDATE、PRIORITY 或 RST_STREAM 帧。然而,它可以接收任何帧。

一旦服务器接收并解析了 HEADERS 帧,它就会将流状态从空闲转变为打开,然后半关闭,因此它与客户端匹配。服务器半关闭状态意味着它可以发送任何帧,但只能接收 WINDOW_UPDATE、PRIORITY 或 RST_STREAM 帧。

对 GET 的响应包含消息内容,因此服务器发送 END_STREAM 标志设置为 0 的 HEADERS,然后发送 END_STREAM 标志设置为 1 的 DATA。DATA 帧触发服务器上流从半关闭到关闭的转换。当客户端收到它时,它也会转换为关闭状态。一旦流关闭,就无法发送或接收任何帧。

将此生命周期应用回并发上下文中,HTTP/2 指出:

处于“打开”状态或任一种“半关闭”状态的流计入允许端点打开的最大流数量。处于这三种状态中任何一种状态的流都将计入在 SETTINGS_MAX_CONCURRENT_STREAMS 设置中公布的限制。

理论上,并发限制是有用的。不过,也有一些实际因素会影响它的效果,我们将在这篇博文的后面部分讲述。

HTTP/2 请求取消

在前文中,我们谈到了客户端取消正在进行的请求的问题。与 HTTP/1.1 相比,HTTP/2 支持这种方式的效率要高得多。客户端无需中断整个连接,只需针对单个流发送一个 RST_STREAM 帧。这将指示服务器停止处理该请求并中止响应,从而释放服务器资源并避免浪费带宽。

让我们来看看前面 3 个请求的例子。这一次,客户端在发送完所有 HEADERS 帧后,取消了针对流 1 的请求。服务器在准备好提供响应之前,会解析此 RST_STREAM 帧,并改为只响应流 3 和流 5:

取消请求是一个非常有用的功能。例如,当滚动包含多个图像的网页时,网络浏览器可以取消落在视口之外的图像,这意味着进入视口的图像可以更快地加载。与 HTTP/1.1 相比,HTTP/2 使这种行为更加高效。

被取消的请求流会快速过渡整个流生命周期。 END_STREAM 标志设置为 1 的客户端 HEADERS 状态从空闲状态转换为打开状态再到半关闭状态,然后 RST_STREAM 立即导致从半关闭状态转换为关闭状态。

回想一下,只有处于打开或半关闭状态的流才会影响流并发限制。当客户端取消流时,它立即能够在其位置打开另一个流,并可以立即发送另一个请求。这就是 CVE-2023-44487 能够发挥作用的关键所在。

快速重置导致拒绝服务

HTTP/2 请求取消可能被滥用来快速重置无限数量的流。当 HTTP/2 服务器能够足够快地处理客户端发送的 RST_STREAM 帧并拆除状态时,这种快速重置不会导致问题。当整理工作出现任何延误或滞后时,问题就会开始出现。客户端可能会处理大量请求,从而导致工作积压,从而导致服务器上资源的过度消耗。

常见的 HTTP 部署架构会在其他组件前面运行 HTTP/2 代理或负载平衡器。当客户端请求到达时,它会被快速分派,而实际工作则作为异步活动在其他地方完成。这样,代理就能非常高效地处理客户端流量。然而,这种关注点的分离会使代理难以整理正在处理的作业。因此,这些部署更有可能遇到快速重置造成的问题。

Cloudflare 的反向代理处理传入的 HTTP/2 客户端流量时,会将数据从连接的套接字复制到缓冲区,并按顺序处理缓冲的数据。在读取每个请求(HEADERS 和 DATA 帧)时,它会被分派到上游服务。读取 RST_STREAM 帧时,请求的本地状态会被删除,并通知上游请求已被取消。如此循环往复,直到整个缓冲区中的数据处理完毕。然而,这种逻辑可能会被滥用:当恶意客户端开始发送大量请求链,并在连接开始时重置时,我们的服务器就会迫不及待地读取所有请求,给上游服务器造成压力,以至于无法处理任何新的传入请求。

需要强调的是,流并发本身并不能缓解快速重置。无论服务器选择的 SETTINGS_MAX_CONCURRENT_STREAMS 值是多少,客户端可以不断发送请求以创建高请求率。

快速重置剖析

以下是使用概念验证客户端尝试发出总共 1000 个请求的快速重置示例。我使用了现成的服务器,没有任何缓解措施; 在测试环境中侦听端口 443。为了清楚起见,使用 Wireshark 剖析流量并进行过滤以仅显示 HTTP/2 流量。下载 pcap 以进行后续操作。

要看清楚有点难,因为有很多帧。我们可以通过 Wireshark 的“统计 > HTTP2”工具快速获得摘要:

在此跟踪中,数据包 14 中的第一个帧是服务器的 SETTINGS 帧,它标明最大流并发为 100。在数据包 15 中,客户端发送了几个控制帧,然后开始发出会快速重置的请求。第一个 HEADERS 帧长 26 字节,而随后的所有 HEADERS 帧都只有 9 字节。这种大小差异是由于一种名为 HPACK 的压缩技术造成。数据包 15 总共包含 525 个请求,最高可达 1051 个流。

有趣的是,流 1051 的 RST_STREAM 帧并未包含在数据包 15 中,因此在数据包 16 中,我们看到服务器传回 404 响应。然后,在数据包 17 中,客户端发送 RST_STREAM,然后继续发送余下的 475 个请求。

请注意,虽然服务器声明有 100 个并发流,但客户端发送的两个数据包的 HEADERS 帧数远超此值。客户端无需等待服务器的任何返回流量,它只受限于它可以发送的数据包大小。在此跟踪中未发现服务器 RST_STREAM 帧,表明服务器未发现并发流违规。

对客户的影响

如上所述,当请求被取消时,上游服务会收到通知,并中止请求以免浪费过多资源。这次攻击就是这种情况,大多数恶意请求从未被转发到源服务器。然而,这些攻击的规模很大,确实造成了一些影响。

首先,当传入请求的速度达到前所未有的峰值时,我们收到了客户端发现 502 错误增多的报告。这种情况发生在我们受影响最大的数据中心,彼时它们正在努力处理所有请求。虽然我们的网络可以应对大规模攻击,但这一特殊漏洞暴露了我们基础设施中的薄弱环节。让我们深入探讨一下详细信息,重点关注当传入的请求到达我们的数据中心之一时如何处理:

我们可以看到我们的基础设施由一系列具有不同职责的不同代理服务器组成。特别是,当客户端连接到 Cloudflare 发送 HTTPS 流量时,它首先会命中我们的 TLS 解密代理:它解密 TLS 流量,处理 HTTP 1、2 或 3 流量,然后将其转发到我们的“业务逻辑”代理。它负责加载每个客户的所有设置,然后将请求正确路由到其他上游服务 – 更重要的是,在我们的例子中,它还负责安全功能。这是处理 L7 攻击缓解的地方。

这种攻击手段的问题在于,它能在每个连接中快速发送大量请求。每个请求都必须转发到业务逻辑代理,我们才有机会阻止它。当请求吞吐量超过我们代理的处理能力时,连接这两项服务的管道在我们的一些服务器中达到了饱和水平。

当发生这种情况时,TLS 代理就无法再连接到其上游代理,因此在最严重的攻击中,一些客户端会看到“502 Bad Gateway”错误。值得注意的是,到目前为止,用于创建 HTTP 分析的日志也是由我们的业务逻辑代理发布的。这样做的后果是,在 Cloudflare 仪表板中看不到这些错误。我们的内部仪表板显示,在最初的攻击浪潮中(在我们实施缓解措施之前),约有 1% 的请求受到影响,在 8 月 29 日最严重的一次攻击中,有几秒钟的峰值达到了约 12%。下图显示了出现这种情况时的两小时内这些错误的比率:

在接下来的几天里,我们努力大幅减少了这一数字,详见本帖下文。由于我们的堆栈发生了变化,而且我们的缓解措施大大降低了这些攻击的规模,如今这一数字实际上为零。

499 错误和 HTTP/2 流并发挑战

一些客户报告的另一个症状是 499 错误增加。造成这种情况的原因有些不同,与本贴前面详述的 HTTP/2 连接中的最大流并发相关。

HTTP/2 设置在连接开始时使用 SETTINGS 帧进行交换。如果没有收到明确的参数,则会使用默认值。客户端建立 HTTP/2 连接后,可以等待服务器的 SETTINGS(慢),也可以使用默认值开始发出请求(快)。对于 SETTINGS_MAX_CONCURRENT_STREAMS,默认值实际上是无限的(流 ID 使用 31 位数字空间,请求使用奇数,因此实际限制是 1073741824)。规范建议服务器提供不少于 100 个数据流。客户端通常偏向于速度,因此不会等待服务器设置,这就造成了一些竞争情况。客户端会赌服务器可能选择的限制;如果客户端赌错了,请求将被拒绝,并且客户端必须重试。在 1073741824 个流上赌有点傻。取而代之,许多客户端决定将自己限制在发布 100 个并发流,希望服务器遵循规范建议。如果服务器选择低于 100 的数值,则客户端赌错了,流将被重置。

服务器重置超出并发限制的流的原因有很多。HTTP/2 是严格的,在出现解析或逻辑错误时会要求关闭流。在 2019 年,Cloudflare 针对 HTTP/2 DoS 漏洞开发了多个缓解措施。其中几个漏洞是由客户端行为不当导致服务器重置流造成的。遏制此类客户端的一个非常有效的策略是对在连接期间服务器重置的次数进行计数,当次数超过某个阈值时,就使用 GOAWAY 帧关闭连接。合法客户可能会在一次连接中犯一两个错误,这是可以接受的。如果客户端犯错误的次数过多,它很可能是损坏的客户端或恶意客户端,关闭连接可以解决这两种情况。

在应对由 CVE-2023-44487 引发的 DoS 攻击时,Cloudflare 将最大流并发降至 64。在进行此更改之前,我们并不知道客户端不会等待 SETTINGS,而是假设并发为 100。某些 Web 页面(如图片库)确实会导致浏览器在连接开始时立即发送 100 个请求。不幸的是,超过限制的 36 个流都需要重置,这触发了我们的计数缓解措施。这意味着我们关闭了合法客户端的连接,导致页面加载完全失败。我们意识到这个互操作性问题后,立即将最大流并发更改为 100。

Cloudflare 方面的行动

在 2019 年,发现了几个与 HTTP/2 实现相关的 DoS 漏洞。作为回应,Cloudflare 开发并部署了一系列检测和缓解措施。CVE-2023-44487 是 HTTP/2 漏洞的另一种表现形式。不过,为了缓解它,我们能够扩展现有的保护,以监控客户端发送的 RST_STREAM 帧,并在它们被用于滥用时关闭连接。客户端对 RST_STREAM 的合法使用不受影响。

除了直接修复外,我们还对服务器的 HTTP/2 帧处理和请求分派代码进行了多项改进。此外,业务逻辑服务器还改进了队列和分派,减少了不必要的工作,提高了对取消操作的响应速度。这些措施多管齐下,减轻了各种潜在滥用模式的影响,并为服务器在饱和前处理请求提供了更多空间。

尽早缓解攻击

Cloudflare 已经部署了一套系统,可以通过成本较低的方法有效缓解超大型攻击。其中一个系统名为 IP Jail。对于超容量攻击,该系统会收集参与攻击的客户端 IP,并阻止它们连接到受攻击的财产(无论是在 IP 级别还是在我们的 TLS 代理中)。然而,该系统需要几秒钟才能完全生效; 在这宝贵的几秒钟内,源头已经受到保护,但我们的基础设施仍然需要吸收所有 HTTP 请求。由于这种新的僵尸网络实际上没有启动期,因此我们需要能够在攻击成为问题之前将其消灭。

为此,我们扩展了 IP Jail 系统,以保护我们的整个基础设施:一旦一个 IP 被“监禁”,它不仅会被阻止连接到受攻击的资产,我们还会禁止相应的 IP 在一段时间内使用 HTTP/2 连接到 Cloudflare 上的任何其他域。因此,无法通过使用 HTTP/1.x 来滥用协议。这就限制了攻击者实施大规模攻击的能力,而共用同一 IP 的任何合法客户端在此期间只会看到非常小的性能下降。基于 IP 的缓解措施是一种非常笨拙的工具 – 这就是为什么我们在这种规模下使用它们时必须非常小心,并尽可能避免误报。此外,僵尸网络中给定 IP 的寿命通常很短,因此任何长期缓解措施都可能弊大于利。下图显示了我们目睹的攻击中 IP 的变化情况:

我们可以看到,在某一天发现的许多新 IP 后来很快就消失了。

由于所有这些操作都在 HTTPS 管道开始时在我们的 TLS 代理中发生,因此与常规的 L7 缓解系统相比,可以节省大量资源。这使我们能够更顺利地应对这些攻击,现在这些僵尸网络造成的随机 502 错误数量已降至零。

攻击可观测性改进

我们正在改变的另一个方面是可观察性。将错误返回到客户端但在客户分析中不可见这种情况令人不满。幸运的是,早在最近的袭击发生之前,就有一个项目正在对这些系统进行全面检查。它最终将允许我们基础设施中的每个服务记录自己的数据,而不是依赖我们的业务逻辑代理来整合和发布日志数据。这次事件凸显了这项工作的重要性,我们将加倍努力。

我们也在努力改进连接层面的日志记录,使我们能够更快地发现此类协议滥用,从而提高我们的 DDoS 缓解能力。

总结

虽然这是最近一次破纪录的攻击,但我们知道这不会是最后一次。随着攻击的不断复杂化,Cloudflare 坚持不懈地努力,积极主动地识别新的威胁,并在我们的全球网络中部署应对措施,使我们的数百万客户能够立即自动地受到保护。

自从 2017 年以来,Cloudflare 一直为我们的所有客户提供免费、不计量且无限制的 DDoS 防护。此外,我们还提供一系列附加安全功能,以满足各种规模组织的需求。如果您不确定自己是否受到保护,或想了解如何才能受到保护,请联系我们。

Model Extraction Attack on Neural Networks

Post Syndicated from Bruce Schneier original https://www.schneier.com/blog/archives/2023/10/model-extraction-attack-on-neural-networks.html

Adi Shamir et al. have a new model extraction attack on neural networks:

Polynomial Time Cryptanalytic Extraction of Neural Network Models

Abstract: Billions of dollars and countless GPU hours are currently spent on training Deep Neural Networks (DNNs) for a variety of tasks. Thus, it is essential to determine the difficulty of extracting all the parameters of such neural networks when given access to their black-box implementations. Many versions of this problem have been studied over the last 30 years, and the best current attack on ReLU-based deep neural networks was presented at Crypto’20 by Carlini, Jagielski, and Mironov. It resembles a differential chosen plaintext attack on a cryptosystem, which has a secret key embedded in its black-box implementation and requires a polynomial number of queries but an exponential amount of time (as a function of the number of neurons).

In this paper, we improve this attack by developing several new techniques that enable us to extract with arbitrarily high precision all the real-valued parameters of a ReLU-based DNN using a polynomial number of queries and a polynomial amount of time. We demonstrate its practical efficiency by applying it to a full-sized neural network for classifying the CIFAR10 dataset, which has 3072 inputs, 8 hidden layers with 256 neurons each, and about 1.2 million neuronal parameters. An attack following the approach by Carlini et al. requires an exhaustive search over 2256 possibilities. Our attack replaces this with our new techniques, which require only 30 minutes on a 256-core computer.

Delegating permission set management and account assignment in AWS IAM Identity Center

Post Syndicated from Jake Barker original https://aws.amazon.com/blogs/security/delegating-permission-set-management-and-account-assignment-in-aws-iam-identity-center/

In this blog post, we look at how you can use AWS IAM Identity Center (successor to AWS Single Sign-On) to delegate the management of permission sets and account assignments. Delegating the day-to-day administration of user identities and entitlements allows teams to move faster and reduces the burden on your central identity administrators.

IAM Identity Center helps you securely create or connect your workforce identities and manage their access centrally across AWS accounts and applications. Identity Center requires accounts to be managed by AWS Organizations. Administration of Identity Center can be delegated to a member account (an account other than the management account). We recommend that you delegate Identity Center administration to limit who has access to the management account and use the management account only for tasks that require the management account.

Delegated administration is different from the delegation of permission sets and account assignments, which this blog covers. For more information on delegated administration, see Getting started with AWS IAM Identity Center delegated administration. The patterns in this blog post work whether Identity Center is delegated to a member account or remains in the management account.

Permission sets are used to define the level of access that users or groups have to an AWS account. Permission sets can contain AWS managed policies, customer managed policies, inline policies, and permissions boundaries.

Solution overview

As your organization grows, you might want to start delegating permissions management and account assignment to give your teams more autonomy and reduce the burden on your identity team. Alternatively, you might have different business units or customers, operating out of their own organizational units (OUs), that want more control over their own identity management.

In this scenario, an example organization has three developer teams: Red, Blue, and Yellow. Each of the teams operate out of its own OU. IAM Identity Center has been delegated from the management account to the Identity Account. Figure 1 shows the structure of the example organization.

Figure 1: The structure of the organization in the example scenario

Figure 1: The structure of the organization in the example scenario

The organization in this scenario has an existing collection of permission sets. They want to delegate the management of permission sets and account assignments away from their central identity management team.

  • The Red team wants to be able to assign the existing permission sets to accounts in its OU. This is an accounts-based model.
  • The Blue team wants to edit and use a single permission set and then assign that set to the team’s single account. This is a permission-based model.
  • The Yellow team wants to create, edit, and use a permission set tagged with Team: Yellow and then assign that set to all of the accounts in its OU. This is a tag-based model.

We’ll look at the permission sets needed for these three use cases.

Note: If you’re using the AWS Management Console, additional permissions are required.

Use case 1: Accounts-based model

In this use case, the Red team is given permission to assign existing permission sets to the three accounts in its OU. This will also include permissions to remove account assignments.

Using this model, an organization can create generic permission sets that can be assigned to its AWS accounts. It helps reduce complexity for the delegated administrators and verifies that they are using permission sets that follow the organization’s best practices. These permission sets restrict access based on services and features within those services, rather than specific resources.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "sso:CreateAccountAssignment",
            "sso:DeleteAccountAssignment",
            "sso:ProvisionPermissionSet"
        ],
        "Resource": [
            "arn:aws:sso:::instance/ssoins-<sso-ins-id>",
            "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/*",
            "arn:aws:sso:::account/112233445566",
            "arn:aws:sso:::account/223344556677",
            "arn:aws:sso:::account/334455667788"

        ]
    }
  ]
}

In the preceding policy, the principal can assign existing permission sets to the three AWS accounts with the IDs 112233445566, 223344556677 and 334455667788. This includes administration permission sets, so carefully consider which accounts you allow the permission sets to be assigned to.

The arn:aws:sso:::instance/ssoins-<sso-ins-id> is the IAM Identity Center instance ID ARN. It can be found using either the AWS Command Line Interface (AWS CLI) v2 with the list-instances API or the AWS Management Console.

Use the AWS CLI

Use the AWS Command Line Interface (AWS CLI) to run the following command:

aws sso-admin list-instances

You can also use AWS CloudShell to run the command.

Use the AWS Management Console

Use the Management Console to navigate to the IAM Identity Center in your AWS Region and then select Choose your identity source on the dashboard.

Figure 2: The IAM Identity Center instance ID ARN in the console

Figure 2: The IAM Identity Center instance ID ARN in the console

Use case 2: Permission-based model

For this example, the Blue team is given permission to edit one or more specific permission sets and then assign those permission sets to a single account. The following permissions allow the team to use managed and inline policies.

This model allows the delegated administrator to use fine-grained permissions on a specific AWS account. It’s useful when the team wants total control over the permissions in its AWS account, including the ability to create additional roles with administrative permissions. In these cases, the permissions are often better managed by the team that operates the account because it has a better understanding of the services and workloads.

Granting complete control over permissions can lead to unintended or undesired outcomes. Permission sets are still subject to IAM evaluation and authorization, which means that service control policies (SCPs) can be used to deny specific actions.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Effect": "Allow",
        "Action": [
            "sso:AttachCustomerManagedPolicyReferenceToPermissionSet",
            "sso:AttachManagedPolicyToPermissionSet",
            "sso:CreateAccountAssignment",
            "sso:DeleteAccountAssignment",
            "sso:DeleteInlinePolicyFromPermissionSet",
            "sso:DetachCustomerManagedPolicyReferenceFromPermissionSet",
            "sso:DetachManagedPolicyFromPermissionSet",
            "sso:ProvisionPermissionSet",
            "sso:PutInlinePolicyToPermissionSet",
            "sso:UpdatePermissionSet"
        ],
        "Resource": [
            "arn:aws:sso:::instance/ssoins-<sso-ins-id>",
            "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/ps-1122334455667788",
            "arn:aws:sso:::account/445566778899"
        ]
    }
  ]
}

Here, the principal can edit the permission set arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/ps-1122334455667788 and assign it to the AWS account 445566778899. The editing rights include customer managed policies, AWS managed policies, and inline policies.

If you want to use the preceding policy, replace the missing and example resource values with your own IAM Identity Center instance ID and account numbers.

In the preceding policy, the arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/ps-1122334455667788 is the permission set ARN. You can find this ARN through the console, or by using the AWS CLI command to list all of the permission sets:

aws sso-admin list-permission-sets --instance-arn <instance arn from above>

This permission set can also be applied to multiple accounts—similar to the first use case—by adding additional account IDs to the list of resources. Likewise, additional permission sets can be added so that the user can edit multiple permission sets and assign them to a set of accounts.

Use case 3: Tag-based model

For this example, the Yellow team is given permission to create, edit, and use permission sets tagged with Team: Yellow. Then they can assign those tagged permission sets to all of their accounts.

This example can be used by an organization to allow a team to freely create and edit permission sets and then assign them to the team’s accounts. It uses tagging as a mechanism to control which permission sets can be created and edited. Permission sets without the correct tag cannot be altered.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sso:CreatePermissionSet",
                "sso:DescribePermissionSet",
                "sso:UpdatePermissionSet",
                "sso:DeletePermissionSet",
                "sso:DescribePermissionSetProvisioningStatus",
                "sso:DescribeAccountAssignmentCreationStatus",
                "sso:DescribeAccountAssignmentDeletionStatus",
                "sso:TagResource"
            ],
            "Resource": [
                "arn:aws:sso:::instance/ssoins-<sso-ins-id>"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "sso:DescribePermissionSet",
                "sso:UpdatePermissionSet",
                "sso:DeletePermissionSet"
                	
            ],
            "Resource": "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/Team": "Yellow"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": [
                "sso:CreatePermissionSet"
            ],
            "Resource": "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/*",
            "Condition": {
                "StringEquals": {
                    "aws:RequestTag/Team": "Yellow"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "sso:TagResource",
            "Resource": "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/Team": "Yellow",
                    "aws:RequestTag/Team": "Yellow"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": [
                "sso:CreateAccountAssignment",
                "sso:DeleteAccountAssignment",
                "sso:ProvisionPermissionSet"
            ],
            "Resource": [
                "arn:aws:sso:::instance/ssoins-<sso-ins-id>",
                "arn:aws:sso:::account/556677889900",
                "arn:aws:sso:::account/667788990011",
                "arn:aws:sso:::account/778899001122"
            ]
        },
        {
            "Sid": "InlinePolicy",
            "Effect": "Allow",
            "Action": [
                "sso:GetInlinePolicyForPermissionSet",
                "sso:PutInlinePolicyToPermissionSet",
                "sso:DeleteInlinePolicyFromPermissionSet"
            ],
            "Resource": [
                "arn:aws:sso:::instance/ssoins-<sso-ins-id>"
            ]
        },
        {
            "Sid": "InlinePolicyABAC",
            "Effect": "Allow",
            "Action": [
                "sso:GetInlinePolicyForPermissionSet",
                "sso:PutInlinePolicyToPermissionSet",
                "sso:DeleteInlinePolicyFromPermissionSet"
            ],
            "Resource": "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/Team": "Yellow"
                }
            }
        }
    ]
}

In the preceding policy, the principal is allowed to create new permission sets only with the tag Team: Yellow, and assign only permission sets tagged with Team: Yellow to the AWS accounts with ID 556677889900, 667788990011, and 778899001122.

The principal can only edit the inline policies of the permission sets tagged with Team: Yellow and cannot change the tags of the permission sets that are already tagged for another team.

If you want to use this policy, replace the missing and example resource values with your own IAM Identity Center instance ID, tags, and account numbers.

Note: The policy above assumes that there are no additional statements applying to the principal. If you require additional allow statements, verify that the resulting policy doesn’t create a risk of privilege escalation. You can review Controlling access to AWS resources using tags for additional information.

This policy only allows the delegation of permission sets using inline policies. Customer managed policies are IAM policies that are deployed to and are unique to each AWS account. When you create a permission set with a customer managed policy, you must create an IAM policy with the same name and path in each AWS account where IAM Identity Center assigns the permission set. If the IAM policy doesn’t exist, Identity Center won’t make the account assignment. For more information on how to use customer managed policies with Identity Center, see How to use customer managed policies in AWS IAM Identity Center for advanced use cases.

You can extend the policy to allow the delegation of customer managed policies with these two statements:

{
    "Sid": "CustomerManagedPolicy",
    "Effect": "Allow",
    "Action": [
        "sso:ListCustomerManagedPolicyReferencesInPermissionSet",
        "sso:AttachCustomerManagedPolicyReferenceToPermissionSet",
        "sso:DetachCustomerManagedPolicyReferenceFromPermissionSet"
    ],
    "Resource": [
        "arn:aws:sso:::instance/ssoins-<sso-ins-id>"
    ]
},
{
    "Sid": "CustomerManagedABAC",
    "Effect": "Allow",
    "Action": [
        "sso:ListCustomerManagedPolicyReferencesInPermissionSet",
        "sso:AttachCustomerManagedPolicyReferenceToPermissionSet",
        "sso:DetachCustomerManagedPolicyReferenceFromPermissionSet"
    ],
    "Resource": "arn:aws:sso:::permissionSet/ssoins-<sso-ins-id>/*",
    "Condition": {
        "StringEquals": {
            "aws:ResourceTag/Team": "Yellow"
        }
    }
}

Note: Both statements are required, as only the resource type PermissionSet supports the condition key aws:ResourceTag/${TagKey}, and the actions listed require access to both the Instance and PermissionSet resource type. See Actions, resources, and condition keys for AWS IAM Identity Center for more information.

Best practices

Here are some best practices to consider when delegating management of permission sets and account assignments:

  • Assign permissions to edit specific permission sets. Allowing roles to edit every permission set could allow that role to edit their own permission set.
  • Only allow administrators to manage groups. Users with rights to edit group membership could add themselves to any group, including a group reserved for organization administrators.

If you’re using IAM Identity Center in a delegated account, you should also be aware of the best practices for delegated administration.

Summary

Organizations can empower teams by delegating the management of permission sets and account assignments in IAM Identity Center. Delegating these actions can allow teams to move faster and reduce the burden on the central identity management team.

The scenario and examples share delegation concepts that can be combined and scaled up within your organization. If you have feedback about this blog post, submit comments in the Comments section. If you have questions, start a new thread on AWS Re:Post with the Identity Center tag.

Want more AWS Security news? Follow us on Twitter.

Jake Barker

Jake Barker

Jake is a Senior Security Consultant with AWS Professional Services. He loves making security accessible to customers and eating great pizza.

Roberto Migli

Roberto Migli

Roberto is a Principal Solutions Architect at AWS. Roberto supports global financial services customers, focusing on security and identity and access management. In his free time he enjoys building electronics gadgets and spending time with his family.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Post Syndicated from João Tomé original http://blog.cloudflare.com/internet-traffic-patterns-in-israel-and-palestine-following-the-october-2023-attacks/

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

On Saturday, October 7, 2023, attacks from the Palestinian group Hamas launched from the Gaza Strip against the south of Israel started a new conflict in the region. Israel officially declared that it is at war the next day. Cloudflare's data shows that Internet traffic was impacted in different ways, both in Israel and Palestine, with two networks (autonomous systems) in the Gaza Strip going offline a few hours after the attacks. Subsequently, on October 9, two additional networks also experienced outages. We also saw an uptick in cyberattacks targeting Israel, including a 1.26 billion HTTP requests DDoS attack, and Palestine.

Starting with general Internet traffic trends, there was a clear increase in Internet traffic right after the attacks reportedly began (03:30 UTC, 06:30 local time). Traffic spiked at around 03:35 UTC (06:35 local time) in both Israel (~170% growth compared with the previous week) and Palestine (100% growth).

That growth is consistent with other situations, where we’ve seen surges in Internet traffic when countrywide events occur and people are going online to check for news, updates, and more information on what is happening, with social media and messaging also playing a role. However, in Palestine, that traffic growth was followed by a clear drop in traffic around 08:00 UTC (11:00 local time).

Internet traffic patterns in Israel and Palestine following the October 2023 attacks
Internet traffic patterns in Israel and Palestine following the October 2023 attacks

The Palestine uptick in traffic after the Hamas attacks started is more visible when only looking at HTTP requests. Requests in Palestine dropped on Saturday and Sunday, October 7 and 8, as much as 20% and 25%, respectively.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Palestine's outages and Internet impact

What drove the drop in Internet traffic in Palestine? Our data shows that two Gaza Strip related networks (autonomous systems or ASNs) were offline on that October 7 morning. Fusion (AS42314) was offline from 08:00 UTC, but saw some recovery after 17:00 UTC the next day; this only lasted for a few hours, given that it went back offline after 12:00 UTC this Monday, October 9.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

It was the same scenario for DCC North (AS203905), but it went offline after 10:00 UTC and with no recovery of traffic observed as of Monday, October 9. These Internet disruptions may be related to power outages in the Gaza Strip.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

During the day on October 7, other Palestinian networks saw less traffic than usual. JETNET (AS199046) had around half of the usual traffic after 08:00 UTC, similar to SpeedClick (AS57704), which had around 60% less traffic. After 14:15 on October 9, traffic to those networks dropped sharply (a 95% decrease compared with the previous week), showing only residual traffic.

When looking more closely at the Gaza Strip specifically, we can see that some districts or governorates had a drop in HTTP requests a few hours after the first Hamas attacks. The Gaza Governorate was impacted, with traffic dropping on October 7, 2023, after 09:15 UTC. On October 9, at 18:00 UTC, traffic was 46% lower than in the previous week. (Note: there were spikes in traffic during Friday, October 6, several hours before the attacks, but it is unclear what caused those spikes.)

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

The Deir al-Balah Governorate (on October 9, at 18:00 UTC, traffic was 46% lower than in the previous week) and the Khan Yunis Governorate (50% lower) also both experienced similar drops in traffic:

Internet traffic patterns in Israel and Palestine following the October 2023 attacks
Internet traffic patterns in Israel and Palestine following the October 2023 attacks

In the Rafah Governorate traffic dropped after 19:00 UTC on October 8 (and on October 9, at 18:00 UTC, traffic was 65% lower than in the previous week).

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Other Palestinian governorates in the West Bank did not experience the same impact to Internet traffic.

Spikes in Internet traffic in Israel

In Israel, Internet traffic surged to ~170% as compared to the previous week right after the Hamas attacks on October 7 at around 03:35 UTC (06:35 local time), and again at around 16:00 UTC (19:00 local time), with ~80% growth compared to the previous week. In both cases, the increase was driven by mobile device traffic.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

There was also increased traffic, as compared with usual levels, on Sunday, October 8, with notable spikes at around 06:00 (09:00 local time) and 12:00 UTC (15:00 local time), seen in the HTTP requests traffic graph below.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Mobile device traffic drove the Saturday, October 7 spikes in traffic, with the daily mobile device usage percentage reaching its highest in the past two months, reaching 56%.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Looking at specific Israel districts, traffic looks similar to the nationwide perspective.

Cyber attacks targeting Israel

Cyber attacks are frequent, recurrent, and are not necessarily dependent on actual wars on the ground, as our 2023 attacks landscape clearly showed. However, it is not unusual to see cyberattacks launched in tandem with ground assaults. We saw that in Ukraine, an uptick in cyber attacks started just before war began there on February 24, 2022, and were even more constant, and spread to other countries after that day.

In Israel, we saw a clear uptick in cyber attacks earlier this year, with another wave of notable attacks on October 7 and October 8, 2023, after the Hamas attacks. The largest ones were DDoS attacks targeting Israeli newspapers. One attack on October 8, reached 1.26 billion daily requests blocked by Cloudflare as DDoS attacks, and the other reached 346 million daily requests on October 7, and 332 million daily requests the following day.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Looking at these DDoS attacks in terms of requests per second, one of the impacted sites experienced a peak of 1.1 million requests per second on October 8 at 02:00 UTC, and the other Israeli newspaper saw a peak of 745k requests per second at around 06:00 the same day.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

In Palestine, we also saw application layer DDoS attacks, but not as big. The main one in the past three months was on October 7, 2023, targeting a Palestine online newspaper, reaching 105 million daily requests.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Looking at these most notable DDoS attacks targeting Palestine in terms of requests per second (rps), the most impacted site (a Palestinian newspaper) experienced a peak of 214k requests per second at around 17:20 UTC on October 7.

Internet traffic patterns in Israel and Palestine following the October 2023 attacks

Follow Cloudflare Radar for up to date information

We will continue to monitor trends related to this conflict. You can use Cloudflare Radar to check for up to date Internet traffic patterns, including those related to Israel and Palestine. Follow Cloudflare Radar on social media at @CloudflareRadar (Twitter/X), cloudflare.social/@radar (Mastodon), and radar.cloudflare.com (Bluesky).

AWS Weekly Roundup: AWS Control Tower, Amazon Bedrock, Amazon OpenSearch Service, and More (October 9, 2023)

Post Syndicated from Antje Barth original https://aws.amazon.com/blogs/aws/aws-weekly-roundup-aws-control-tower-amazon-bedrock-amazon-opensearch-service-and-more-october-9-2023/

Pumpkins

As the Northern Hemisphere enjoys early fall and pumpkins take over the local farmers markets and coffee flavors here in the United States, we’re also just 50 days away from re:Invent 2023! But before we officially enter pre:Invent sea­­son, let’s have a look at some of last week’s exciting news and announcements.

Last Week’s Launches
Here are some launches that got my attention:

AWS Control Tower – AWS Control Tower released 22 proactive controls and 10 AWS Security Hub detective controls to help you meet regulatory requirements and meet control objectives such as encrypting data in transit, encrypting data at rest, or using strong authentication. For more details and a list of controls, check out the AWS Control Tower user guide.

Amazon Bedrock – Just a week after Amazon Bedrock became available in AWS Regions US East (N. Virginia) and US West (Oregon), Amazon Bedrock is now also available in the Asia Pacific (Tokyo) AWS Region. To get started building and scaling generative AI applications with foundation models, check out the Amazon Bedrock documentation, explore the generative AI space at community.aws, and get hands-on with the Amazon Bedrock workshop.

Amazon OpenSearch Service – You can now run OpenSearch version 2.9 in Amazon OpenSearch Service with improvements to search, observability, security analytics, and machine learning (ML) capabilities. OpenSearch Service has expanded its geospatial aggregations support in version 2.9 to gather insights on high-level overview of trends and patterns and establish correlations within the data. OpenSearch Service 2.9 now also comes with OpenSearch Service Integrations to take advantage of new schema standards such as OpenTelemetry and supports managing and overlaying alerts and anomalies onto dashboard visualization line charts.

Amazon SageMaker – SageMaker Feature Store now supports a fully managed, in-memory online store to help you retrieve features for model serving in real time for high throughput ML applications. The new online store is powered by ElastiCache for Redis, an in-memory data store built on open-source Redis. The SageMaker developer guide has all the details.

Also, SageMaker Model Registry added support for private model repositories. You can now register models that are stored in private Docker repositories and track all your models across multiple private AWS and non-AWS model repositories in one central service, simplifying ML operations (MLOps) and ML governance at scale. The SageMaker Developer Guide shows you how to get started.

Amazon SageMaker Canvas – SageMaker Canvas expanded its support for ready-to-use models to include foundation models (FMs). You can now access FMs such as Claude 2, Amazon Titan, and Jurassic-2 (powered by Amazon Bedrock) as well as publicly available models such as Falcon and MPT (powered by SageMaker JumpStart) through a no-code chat interface. Check out the SageMaker Developer Guide for more details.

For a full list of AWS announcements, be sure to keep an eye on the What’s New at AWS page.

Other AWS News
Here are some additional blog posts and news items that you might find interesting:

Behind the scenes on AWS contributions to open-source databases – This post shares some of the more substantial open-source contributions AWS has made in the past two years to upstream databases, introduces some key contributors, and shares how AWS approaches upstream work in our database services.

Fast and cost-effective Llama 2 fine-tuning with AWS Trainium – This post shows you how to fine-tune the Llama 2 model from Meta on AWS Trainium, a purpose-built accelerator for LLM training, to reduce training times and costs.

Code Llama code generation models from Meta are now available via Amazon SageMaker JumpStart – You can now deploy Code Llama FMs, developed by Meta, with one click in SageMaker JumpStart. This post walks you through the details.

Upcoming AWS Events
Check your calendars and sign up for these AWS events:

Build On AWS - Generative AIBuild On Generative AI – Season 2 of this weekly Twitch show about all things generative AI is in full swing! Every Monday, 9:00 US PT, my colleagues Emily and Darko look at new technical and scientific patterns on AWS, invite guest speakers to demo their work, and show us how they built something new to improve the state of generative AI. In today’s episode, Emily and Darko discussed how to translate unstructured documents into structured data. Check out show notes and the full list of episodes on community.aws.

AWS Community Days – Join a community-led conference run by AWS user group leaders in your region: DMV (DC, Maryland, Virginia) (October 13), Italy (October 18), UAE (October 21), Jaipur (November 4), Vadodara (November 4), and Brasil (November 4).

AWS InnovateAWS Innovate: Every Application Edition – Join our free online conference to explore cutting-edge ways to enhance security and reliability, optimize performance on a budget, speed up application development, and revolutionize your applications with generative AI. Register for AWS Innovate Online Americas and EMEA on October 19 and AWS Innovate Online Asia Pacific & Japan on October 26.

AWS re:Invent 2023AWS re:Invent (November 27 – December 1) – Join us to hear the latest from AWS, learn from experts, and connect with the global cloud community. Browse the session catalog and attendee guides and check out the re:Invent highlights for generative AI.

You can browse all upcoming in-person and virtual events.

That’s all for this week. Check back next Monday for another Weekly Roundup!

— Antje

This post is part of our Weekly Roundup series. Check back each week for a quick roundup of interesting news and announcements from AWS!

Using AWS AppSync and AWS Lake Formation to access a secure data lake through a GraphQL API

Post Syndicated from Rana Dutt original https://aws.amazon.com/blogs/big-data/using-aws-appsync-and-aws-lake-formation-to-access-a-secure-data-lake-through-a-graphql-api/

Data lakes have been gaining popularity for storing vast amounts of data from diverse sources in a scalable and cost-effective way. As the number of data consumers grows, data lake administrators often need to implement fine-grained access controls for different user profiles. They might need to restrict access to certain tables or columns depending on the type of user making the request. Also, businesses sometimes want to make data available to external applications but aren’t sure how to do so securely. To address these challenges, organizations can turn to GraphQL and AWS Lake Formation.

GraphQL provides a powerful, secure, and flexible way to query and retrieve data. AWS AppSync is a service for creating GraphQL APIs that can query multiple databases, microservices, and APIs from one unified GraphQL endpoint.

Data lake administrators can use Lake Formation to govern access to data lakes. Lake Formation offers fine-grained access controls for managing user and group permissions at the table, column, and cell level. It can therefore ensure data security and compliance. Additionally, this Lake Formation integrates with other AWS services, such as Amazon Athena, making it ideal for querying data lakes through APIs.

In this post, we demonstrate how to build an application that can extract data from a data lake through a GraphQL API and deliver the results to different types of users based on their specific data access privileges. The example application described in this post was built by AWS Partner NETSOL Technologies.

Solution overview

Our solution uses Amazon Simple Storage Service (Amazon S3) to store the data, AWS Glue Data Catalog to house the schema of the data, and Lake Formation to provide governance over the AWS Glue Data Catalog objects by implementing role-based access. We also use Amazon EventBridge to capture events in our data lake and launch downstream processes. The solution architecture is shown in the following diagram.

Appsync and LakeFormation Arch itecture diagram

Figure 1 – Solution architecture

The following is a step by step description of the solution:

  1. The data lake is created in an S3 bucket registered with Lake Formation. Whenever new data arrives, an EventBridge rule is invoked.
  2. The EventBridge rule runs an AWS Lambda function to start an AWS Glue crawler to discover new data and update any schema changes so that the latest data can be queried.
    Note: AWS Glue crawlers can also be launched directly from Amazon S3 events, as described in this blog post.
  3. AWS Amplify allows users to sign in using Amazon Cognito as an identity provider. Cognito authenticates the user’s credentials and returns access tokens.
  4. Authenticated users invoke an AWS AppSync GraphQL API through Amplify, fetching data from the data lake. A Lambda function is run to handle the request.
  5. The Lambda function retrieves the user details from Cognito and assumes the AWS Identity and Access Management (IAM) role associated with the requesting user’s Cognito user group.
  6. The Lambda function then runs an Athena query against the data lake tables and returns the results to AWS AppSync, which then returns the results to the user.

Prerequisites

To deploy this solution, you must first do the following:

git clone [email protected]:aws-samples/aws-appsync-with-lake-formation.git
cd aws-appsync-with-lake-formation

Prepare Lake Formation permissions

Sign in to the LakeFormation console and add yourself as an administrator. If you’re signing in to Lake Formation for the first time, you can do this by selecting Add myself on the Welcome to Lake Formation screen and choosing Get started as shown in Figure 2.

Figure 2 – Add yourself as the Lake Formation administrator

Otherwise, you can choose Administrative roles and tasks in the left navigation bar and choose Manage Administrators to add yourself. You should see your IAM username under Data lake administrators with Full access when done.

Select Data catalog settings in the left navigation bar and make sure the two IAM access control boxes are not selected, as shown in Figure 3. You want Lake Formation, not IAM, to control access to new databases.

Lake Formation data catalog settings

Figure 3 – Lake Formation data catalog settings

Deploy the solution

To create the solution in your AWS environment, launch the following AWS CloudFormation stack:  Launch Cloudformation Stack

The following resources will be launched through the CloudFormation template:

  • Amazon VPC and networking components (subnets, security groups, and NAT gateway)
  • IAM roles
  • Lake Formation encapsulating S3 bucket, AWS Glue crawler, and AWS Glue database
  • Lambda functions
  • Cognito user pool
  • AWS AppSync GraphQL API
  • EventBridge rules

After the required resources have been deployed from the CloudFormation stack, you must create two Lambda functions and upload the dataset to Amazon S3. Lake Formation will govern the data lake that is stored in the S3 bucket.

Create the Lambda functions

Whenever a new file is placed in the designated S3 bucket, an EventBridge rule is invoked, which launches a Lambda function to initiate the AWS Glue crawler. The crawler updates the AWS Glue Data Catalog to reflect any changes to the schema.

When the application makes a query for data through the GraphQL API, a request handler Lambda function is invoked to process the query and return the results.

To create these two Lambda functions, proceed as follows.

  1. Sign in to the Lambda console.
  2. Select the request handler Lambda function named dl-dev-crawlerLambdaFunction.
  3. Find the crawler Lambda function file in your lambdas/crawler-lambda folder in the git repo that you cloned to your local machine.
  4. Copy and paste the code in that file to the Code section of the dl-dev-crawlerLambdaFunction in your Lambda console. Then choose Deploy to deploy the function.
Copy and paste code into the Lambda function

Figure 4 – Copy and paste code into the Lambda function

  1. Repeat steps 2 through 4 for the request handler function named dl-dev-requestHandlerLambdaFunction using the code in lambdas/request-handler-lambda.

Create a layer for the request handler Lambda

You now must upload some additional library code needed by the request handler Lambda function.

  1. Select Layers in the left menu and choose Create layer.
  2. Enter a name such as appsync-lambda-layer.
  3. Download this package layer ZIP file to your local machine.
  4. Upload the ZIP file using the Upload button on the Create layer page.
  5. Choose Python 3.7 as the runtime for the layer.
  6. Choose Create.
  7. Select Functions on the left menu and select the dl-dev-requestHandler Lambda function.
  8. Scroll down to the Layers section and choose Add a layer.
  9. Select the Custom layers option and then select the layer you created above.
  10. Click Add.

Upload the data to Amazon S3

Navigate to the root directory of the cloned git repository and run the following commands to upload the sample dataset. Replace the bucket_name placeholder with the S3 bucket provisioned using the CloudFormation template. You can get the bucket name from the CloudFormation console by going to the Outputs tab with key datalakes3bucketName as shown in image below.

Figure 5 – S3 bucket name shown in CloudFormation Outputs tab

Figure 5 – S3 bucket name shown in CloudFormation Outputs tab

Enter the following commands in your project folder in your local machine to upload the dataset to the S3 bucket.

cd dataset
aws s3 cp . s3://bucket_name/ --recursive

Now let’s take a look at the deployed artifacts.

Data lake

The S3 bucket holds sample data for two entities: companies and their respective owners. The bucket is registered with Lake Formation, as shown in Figure 6. This enables Lake Formation to create and manage data catalogs and manage permissions on the data.

Figure 6 – Lake Formation console showing data lake location

Figure 6 – Lake Formation console showing data lake location

A database is created to hold the schema of data present in Amazon S3. An AWS Glue crawler is used to update any change in schema in the S3 bucket. This crawler is granted permission to CREATE, ALTER, and DROP tables in the database using Lake Formation.

Apply data lake access controls

Two IAM roles are created, dl-us-east-1-developer and dl-us-east-1-business-analyst, each assigned to a different Cognito user group. Each role is assigned different authorizations through Lake Formation. The Developer role gains access to every column in the data lake, while the Business Analyst role is only granted access to the non-personally identifiable information (PII) columns.

Lake Formation console data lake permissions assigned to group roles

Figure 7 –Lake Formation console data lake permissions assigned to group roles

GraphQL schema

The GraphQL API is viewable from the AWS AppSync console. The Companies type includes several attributes describing the owners of the companies.

Schema for GraphQL API

Figure 8 – Schema for GraphQL API

The data source for the GraphQL API is a Lambda function, which handles the requests.

– AWS AppSync data source mapped to Lambda function

Figure 9 – AWS AppSync data source mapped to Lambda function

Handling the GraphQL API requests

The GraphQL API request handler Lambda function retrieves the Cognito user pool ID from the environment variables. Using the boto3 library, you create a Cognito client and use the get_group method to obtain the IAM role associated to the Cognito user group.

You use a helper function in the Lambda function to obtain the role.

def get_cognito_group_role(group_name):
    response = cognito_idp_client.get_group(
            GroupName=group_name,
            UserPoolId=cognito_user_pool_id
        )
    print(response)
    role_arn = response.get('Group').get('RoleArn')
    return role_arn

Using the AWS Security Token Service (AWS STS) through a boto3 client, you can assume the IAM role and obtain the temporary credentials you need to run the Athena query.

def get_temp_creds(role_arn):
    response = sts_client.assume_role(
        RoleArn=role_arn,
        RoleSessionName='stsAssumeRoleAthenaQuery',
    )
    return response['Credentials']['AccessKeyId'],
response['Credentials']['SecretAccessKey'],  response['Credentials']['SessionToken']

We pass the temporary credentials as parameters when creating our Boto3 Amazon Athena client.

athena_client = boto3.client('athena', aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=session_token)

The client and query are passed into our Athena query helper function which executes the query and returns a query id. With the query id, we are able to read the results from S3 and bundle it as a Python dictionary to be returned in the response.

def get_query_result(s3_client, output_location):
    bucket, object_key_path = get_bucket_and_path(output_location)
    response = s3_client.get_object(Bucket=bucket, Key=object_key_path)
    status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
    result = []
    if status == 200:
        print(f"Successful S3 get_object response. Status - {status}")
        df = pandas.read_csv(response.get("Body"))
        df = df.fillna('')
        result = df.to_dict('records')
        print(result)
    else:
        print(f"Unsuccessful S3 get_object response. Status - {status}")
    return result

Enabling client-side access to the data lake

On the client side, AWS Amplify is configured with an Amazon Cognito user pool for authentication. We’ll navigate to the Amazon Cognito console to view the user pool and groups that were created.

Figure 10 –Amazon Cognito User pools

Figure 10 –Amazon Cognito User pools

For our sample application we have two groups in our user pool:

  • dl-dev-businessAnalystUserGroup – Business analysts with limited permissions.
  • dl-dev-developerUserGroup – Developers with full permissions.

If you explore these groups, you’ll see an IAM role associated to each. This is the IAM role that is assigned to the user when they authenticate. Athena assumes this role when querying the data lake.

If you view the permissions for this IAM role, you’ll notice that it doesn’t include access controls below the table level. You need the additional layer of governance provided by Lake Formation to add fine-grained access control.

After the user is verified and authenticated by Cognito, Amplify uses access tokens to invoke the AWS AppSync GraphQL API and fetch the data. Based on the user’s group, a Lambda function assumes the corresponding Cognito user group role. Using the assumed role, an Athena query is run and the result returned to the user.

Create test users

Create two users, one for dev and one for business analyst, and add them to user groups.

  1. Navigate to Cognito and select the user pool, dl-dev-cognitoUserPool, that’s created.
  2. Choose Create user and provide the details to create a new business analyst user. The username can be biz-analyst. Leave the email address blank, and enter a password.
  3. Select the Users tab and select the user you just created.
  4. Add this user to the business analyst group by choosing the Add user to group button.
  5. Follow the same steps to create another user with the username developer and add the user to the developers group.

Test the solution

To test your solution, launch the React application on your local machine.

  1. In the cloned project directory, navigate to the react-app directory.
  2. Install the project dependencies.
npm install
  1. Install the Amplify CLI:
npm install -g @aws-amplify/cli
  1. Create a new file called .env by running the following commands. Then use a text editor to update the environment variable values in the file.
echo export REACT_APP_APPSYNC_URL=Your AppSync endpoint URL > .env
echo export REACT_APP_CLIENT_ID=Your Cognito app client ID >> .env
echo export REACT_APP_USER_POOL_ID=Your Cognito user pool ID >> .env

Use the Outputs tab of your CloudFormation console stack to get the required values from the keys as follows:

REACT_APP_APPSYNC_URL appsyncApiEndpoint
REACT_APP_CLIENT_ID cognitoUserPoolClientId
REACT_APP_USER_POOL_ID cognitoUserPoolId
  1. Add the preceding variables to your environment.
source .env
  1. Generate the code needed to interact with the API using Amplify CodeGen. In the Outputs tab of your Cloudformation console, find your AWS Appsync API ID next to the appsyncApiId key.
amplify add codegen --apiId <appsyncApiId>

Accept all the default options for the above command by pressing Enter at each prompt.

  1. Start the application.
npm start

You can confirm that the application is running by visiting http://localhost:3000 and signing in as the developer user you created earlier.

Now that you have the application running, let’s take a look at how each role is served from the companies endpoint.

First, sign is as the developer role, which has access to all the fields, and make the API request to the companies endpoint. Note which fields you have access to.

The results for developer role

Figure 11 –The results for developer role

Now, sign in as the business analyst user and make the request to the same endpoint and compare the included fields.

The results for Business Analyst role

Figure 12 –The results for Business Analyst role

The First Name and Last Name columns of the companies list is excluded in the business analyst view even though you made the request to the same endpoint. This demonstrates the power of using one unified GraphQL endpoint together with multiple Cognito user group IAM roles mapped to Lake Formation permissions to manage role-based access to your data.

Cleaning up

After you’re done testing the solution, clean up the following resources to avoid incurring future charges:

  1. Empty the S3 buckets created by the CloudFormation template.
  2. Delete the CloudFormation stack to remove the S3 buckets and other resources.

Conclusion

In this post, we showed you how to securely serve data in a data lake to authenticated users of a React application based on their role-based access privileges. To accomplish this, you used GraphQL APIs in AWS AppSync, fine-grained access controls from Lake Formation, and Cognito for authenticating users by group and mapping them to IAM roles. You also used Athena to query the data.

For related reading on this topic, see Visualizing big data with AWS AppSync, Amazon Athena, and AWS Amplify and Design a data mesh architecture using AWS Lake Formation and AWS Glue.

Will you implement this approach for serving data from your data lake? Let us know in the comments!


About the Authors

Rana Dutt is a Principal Solutions Architect at Amazon Web Services. He has a background in architecting scalable software platforms for financial services, healthcare, and telecom companies, and is passionate about helping customers build on AWS.

Ranjith Rayaprolu is a Senior Solutions Architect at AWS working with customers in the Pacific Northwest. He helps customers design and operate Well-Architected solutions in AWS that address their business problems and accelerate the adoption of AWS services. He focuses on AWS security and networking technologies to develop solutions in the cloud across different industry verticals. Ranjith lives in the Seattle area and loves outdoor activities.

Justin Leto is a Sr. Solutions Architect at Amazon Web Services with specialization in databases, big data analytics, and machine learning. His passion is helping customers achieve better cloud adoption. In his spare time, he enjoys offshore sailing and playing jazz piano. He lives in New York City with his wife and baby daughter.

The collective thoughts of the interwebz