<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luiz Nazari on Medium]]></title>
        <description><![CDATA[Stories by Luiz Nazari on Medium]]></description>
        <link>https://medium.com/@luiznazari?source=rss-3e0fa6816a64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZFinGMjATKAiD2Hw7WPqHg.png</url>
            <title>Stories by Luiz Nazari on Medium</title>
            <link>https://medium.com/@luiznazari?source=rss-3e0fa6816a64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:15:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luiznazari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dynamic Cron in Serverless Architectures]]></title>
            <link>https://luiznazari.medium.com/dynamic-cron-in-serverless-architectures-bd4c16216aa5?source=rss-3e0fa6816a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd4c16216aa5</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Luiz Nazari]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 10:01:59 GMT</pubDate>
            <atom:updated>2024-02-02T10:01:59.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*B_4eIv1q1F0a54pdiuqLfg.jpeg" /></figure><p>Designing a cron solution in an application built on Serverless Architecture may be challenging due to the dynamic and event-driven nature of serverless platforms and it&#39;s main principle: we lack a server for scheduling our cron jobs.</p><p><a href="https://www.hostinger.com/tutorials/cron-job">Cron</a> is a time-based job scheduler that automates the execution of tasks or scripts at specified intervals using a cron expression. This expression defines the schedule, specifying minutes, hours, days, months, and weekdays when the task should run.</p><p><a href="https://www.redhat.com/en/topics/cloud-native-apps/what-is-serverless">Serverless services</a> are designed to exist only at the right moment when they need to execute, when they finishes, the instance ceases to exist, without the need of a long running server, often being more cost-effective.</p><figure><img alt="The life cycle of a serverless service consists of five main stages: an event that triggers the execution, the initialization of an instance, a cycle of execution and readiness state and the disposal of the instance. This cycle generally takes a timespan of milliseconds to seconds or even minutes in some cases." src="https://cdn-images-1.medium.com/max/761/1*TyeSZhwiFAryVyXvWGW-Gw.png" /><figcaption>The life cycle of a serverless service consists of five main stages: an event that triggers the execution, the initialization of an instance, a cycle of execution and readiness state and the disposal of the instance. This cycle generally takes a timespan of milliseconds to seconds or even minutes in some cases.</figcaption></figure><p>This ephemeral nature make <strong>impossible to host a cron job scheduler</strong> in a serverless architecture, because it requires an ever-running server, thus, leading us to a hybrid architecture.</p><p>Furthermore, a <strong>dynamic cron</strong> solution, where <strong>we don’t know the cron expressions</strong> beforehand or when the schedules are determined on-the-fly by the users, add a level of complexity to the equation, risking the scalability and adaptability capabilities, key benefits of the serverless paradigm.</p><p>In this article we will discuss approaches and present a functional and cost-effective solution to the dynamic cron problematic in a <strong>pure serverless architecture</strong> hosted on Amazon Web Service (AWS) cloud.</p><h3>Creating a pure Serverless, scalable and adaptable cron solution</h3><p>To achieve our goal we&#39;ll need:</p><ul><li>Two serverless functions (AWS Lambda);</li><li>A fixed-rate cron scheduled job (AWS Event Bridge Rule);</li><li>A handler to be run by the fixed-rate schedule, capable of hosting the dynamic cron logic (AWS StepFunction);</li><li>A database (DynamoDB).</li></ul><blockquote><strong>Important:</strong> all core services must scale on-demand, otherwise we&#39;ll compromise the <strong>scalability</strong> of the whole system.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_uFqdMdy8SyZEVRUVejxw.jpeg" /><figcaption>Dynamic cron solution in a Serverless Architecture</figcaption></figure><p>We can divide it in two parts:</p><h4>1) The creation of a schedule:</h4><ol><li>Starts with an external service that creates on-the-fly cron expressions, capable of inserting/modifying/deleting items in the schedules DynamoDB table;</li><li>Within the schedulesDynamoDB table, we use DynamoDB Stream (an AWS service that emits an event whenever an item is modified) to trigger our AWS Lambda handle-scheduled-event.</li><li>When an item is <strong>inserted</strong> or <strong>modified</strong>, the AWS Lambda handle-scheduled-event will calculate the next execution date time of the schedule (can be limited by startDateor endDate item fields) and, if it has a next execution, insert or update an item on scheduled-executions DynamoDB Table, otherwise, tries to <strong>delete</strong> an item querying by the schedule’s ID.</li></ol><h4>2) The triggering of a scheduled execution:</h4><ol><li>In AWS EventBridge, we created a Rule based on a fixed-rate schedule using the expression cron(0 * * * ? *) that will trigger <strong>every hour</strong> an AWS Step Function (this expression can be changed to other minute-level intervals).</li><li>The sf-process-scheduled-event AWS Step Function receives an input containing the precise execution timestamp from AWS EventBridge Rule, so it’ll check if there are any scheduled executions registered for this time (with an indexed query — never scan!) in scheduled-executions DynamoDB Table.</li><li>For each found executions, it’ll trigger the scheduled-trigger AWS Lambda Function asynchronously, which, in turn, will do two processes simultaneously: <strong>trigger any service</strong> of our system in the right schedule (asynchronously); and calculating the next execution timestamp (same logic as handle-schedule-event Lambda Function), rescheduling the execution if necessary.</li></ol><p>This solution inherit the <strong>limitations </strong>of the AWS Event Bridge Rule service:</p><blockquote>“EventBridge doesn’t provide second-level precision in schedule expressions. The finest resolution using a cron expression is one minute. Due to the distributed nature of EventBridge and the target services, there can be a delay of several seconds between the time the scheduled rule is triggered and the time the target service runs the target resource.” (Source: <a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html">AWS Docs</a>)</blockquote><h3>Wow. Very beautiful. But too complex!</h3><p>Why not simply use:</p><ul><li>Just AWS Event Bridge Rules?</li><li>AWS DynamoDB TTL?</li><li>AWS EC2 or equivalent server?</li><li>Other cloud vendors?</li><li>Third-party services?</li></ul><h4>Just AWS Event Bridge Rules?</h4><p>We could use multiple AWS Event Bridge Rules for each cron expression we need, thus, eliminating all the listed services and triggering the service directly.</p><p>However, this approach introduces two challenges as we don&#39;t know how many and what cron expressions will be created.</p><p><a href="https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-quota.html">AWS Event Bridge service imposes a quota of 100 or 300 rules per event bus</a>. This limitation directly impacts the number of cron expressions we can permit our users to create. Moreover, this hard limit will compete with any other Rule we need for our system to work (that&#39;d compromise the <strong>scalability</strong> of the whole system).</p><p>Although this might be a short-term solution for a smaller systems, the challenge arises in generating Rules on-the-fly. Normally, they are created by deploying an AWS CloudFormation template.</p><p>To achieve this, we could use a AWS StepFunction with EventBridge: PutRule The execution can be initiated either by another service or integrated with AWS API Gateway, exposing an URL endpoint.</p><h4>AWS DynamoDB TTL?</h4><p>AWS DynamoDB has a Time To Live (TTL) enabling the declaration of a datetime field that specifies when an item will expire and be automatically deleted. This functionality allows us to subscribe to the remove event in AWS DynamoDB Stream. We could use this functionality to register an item whose TTL is the date of the next cron execution, eliminating the complexity of our solution. But why didn&#39;t we use it?</p><p>The catch is: AWS DynamoDB TTL it&#39;s not reliable when it comes to time accuracy.</p><blockquote>&quot;TTL typically deletes expired items within a few days. Depending on the size and activity level of a table, the actual delete operation of an expired item can vary. Because TTL is meant to be a background process, the nature of the capacity used to expire and delete items via TTL is variable (but free of charge).&quot; (Source: <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html">AWS Docs</a>)</blockquote><h4>AWS EC2 or equivalent server?</h4><p>As stated earlier, adopting this approach would constitute a hybrid solution, and I would only consider it under specific conditions:</p><ol><li>there is already an available server suitable for serving as a cron scheduler;</li><li>If the server can be interfaced with an API that the application can invoke;</li><li>The server has autoscaling capabilities;</li><li>The server has regular maintenance and backup policies.</li></ol><p>Running a single cheap EC2 instance (<em>t2.micro</em>) in the region us-east-1 running 24/7 with monthly snapshots would cost approximately 8.62 USD according to the <a href="https://calculator.aws/#/">AWS pricing calculator</a> (excluding network data transfer). In contrast, an AWS StepFunction with express execution (200ms/execution) and an AWS Event Bridge Rule amount to approximately 2.21 USD, considering 1 million monthly executions.</p><h4>Other cloud vendors?</h4><p>This could be an option in a multi-cloud setup. However, this introduces additional complexity in managing multiple accounts and bills</p><p>For instance, we could use <a href="https://cloud.google.com/scheduler/docs/creating?hl=pt-br">Google Cloud Scheduler integrating with APIs</a> (authenticating via Google Cloud Service Accounts) for creating/modifying/deleting cron jobs. That would require an optimization logic to prevent the creation of duplicated jobs. This service is billed <a href="https://cloud.google.com/scheduler/pricing?hl=pt-br">0.10 USD by cron job/month</a>, and at scale, it has the potential to become expensive.</p><h4>Third-party services?</h4><p>There are free and paid online services that allow us to create cron triggers on-demand and subscription to webhook URLs.</p><p>However, caution is advised when considering free options for production, as they often lack Service Level Agreements (SLAs) as well as any other solution that can not be managed via API calls.</p><p>Paid plans from various vendors come with different limitations, such as maximum executions per day, the maximum number of schedules, or minimum execution intervals. The suitability of these services depends on specific business prerequisites, but for a generic service it may posses a risk to scalability and adaptability.</p><p>Based on my research into various vendors, including enterprise plans, it appears that these third-party solutions are generally more expensive than a custom-developed solution.</p><h3>Breaking down the custom solution</h3><p>In this section, we will discuss about key elements and optimizations of the previously described custom solution.</p><h4>Supporting other time intervals</h4><p>As illustrated in the diagram, our solution supports hourly executions, but, in fact, the architecture supports any interval with minute-level precision up to maximum of 60 executions per hour.</p><p>To support other intervals there are two points of change:</p><ol><li>The cron expression in AWS EventBridge Rule;</li><li>The validation of the service that creates the schedules. It must only allow to persist valid intervals, as others intervals will not be selected to execution.</li></ol><p>We opted to restrict executions to 24 times per day because it meets our business needs and is cost-effective, This choice results in 720 executions per month, which translates to a negligible cost for an express AWS StepFunction.</p><h4>AWS StepFunction can be replaced by an AWS Lambda Function</h4><p>We choose StepFunction over an AWS Lambda because it has no cold start, and it&#39;s logic is pretty simple as it does only an indexed query on AWS DynamoDB and calls an async service (the average billed duration is between 100 to 200ms per schedule executions check).</p><p>The use of AWS StepFunction imposes a restriction on the scheduled-executions DynamoDB Table as the nextExecution column must be of string type and adhere to the ISO 8601 format without a decimal fraction (yyyy-MM-ddTHH:mm:ssZ), to match the format of the received string in the event record sent by AWS EventBridge Rule invocations.</p><p>Any other format or type would require transformation before querying AWS DynamoDB. These operations are not supported by AWS StepFunctions capabilities, requiring an AWS Lambda Function.</p><h4>Scheduled executions AWS DynamoDB Table GSI</h4><p>The scheduled-executions DynamoDB Table must have a Global Secondary Index (GSI) to be able to do indexed queries (never scan!). We recommend that the field nextExecution is set as the RANGE key of the GSI to allow both &quot;equal&quot; or &quot;greater/less&quot; operations when querying, providing increased flexibility to retrieve executions within a specific time range.</p><h4>Schedules have a composite ID</h4><p>AWS DynamoDB allows any field to be an ID. We choose to adopt a composed ID field containing any identifier plus a checksum (md5 hash) of the cron fields (cron, timezone, startDate, endDate) resulting in something like schedule::01e5585ec106ecb1f4f35c33cc062765.</p><p>This serves as an additional security feature aimed at preventing unwanted executions. When the scheduled-trigger AWS Lambda runs a scheduled-execution, it performs a getItem operation on the scheduled AWS DynamoDB Table. If no schedule corresponds to the scheduled execution, it won&#39;t execute and promptly removes the scheduled entry.</p><p>This precautionary measure prevents the unintended execution of a modified schedule that, for any reason, wasn&#39;t removed prior to the execution time.</p><h3>Conclusion</h3><p>Designing a cron solution for a Serverless Architecture presents unique challenges due to the dynamic and event-driven nature of these platforms. To address these challenges, we introduced a functional and cost-effective solution in a pure serverless architecture on the AWS cloud. This solution leverages AWS Lambda, EventBridge, StepFunction, and DynamoDB to create a reliable dynamic cron system, ensuring scalability and adaptability while overcoming limitations inherent in other approaches.</p><p><strong>If you know all the cron expressions:</strong> go with you favorite cloud vendor native solution.</p><p><strong>If you DON’T know all the cron expressions or they may be created on-the-fly:</strong> consider a custom solution or migrate to a hybrid architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd4c16216aa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Além dos certificados SSL]]></title>
            <link>https://medium.com/base39/al%C3%A9m-dos-certificados-ssl-ec441077f527?source=rss-3e0fa6816a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec441077f527</guid>
            <category><![CDATA[domain-names]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[digital-certificates]]></category>
            <category><![CDATA[ssl]]></category>
            <dc:creator><![CDATA[Luiz Nazari]]></dc:creator>
            <pubDate>Wed, 10 May 2023 19:22:50 GMT</pubDate>
            <atom:updated>2023-05-10T19:22:50.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-KJ6idSu-YpzC51akvYkQ.png" /></figure><p>A busca por temas envolvendo a segurança digital está cada vez mais relevante, não é atoa que o mercado de Segurança da Informação vai movimentar US$ 1,3 bilhão no Brasil em 2023 (SECURITY REPORT, 2023) e compreender os assuntos em volta desta área é fundamental para profissionais de TI.</p><p>Estamos acostumados a criar ou utilizar sites e aplicativos diversos e, em todo lugar, nos deparamos com certificados de <em>Secure Socket Layer</em> (SSL): no &quot;cadeadinho&quot; dos sites que o cliente pede, no &quot;S&quot; do HTTPS das APIs que construímos ou utilizamos e, mais importante, nos erros de SSL ao integrar com alguma API de terceiros e eu sei que você já usou aquela configuração para desabilitar a verificação do SSL! 😈</p><p>Este é o primeiro de dois artigos, aumentando o teor técnico conforme vamos aprofundando nos assuntos, por primeiro, irei abordar termos gerais sobre os certificados digitais e o porquê não devemos desabilitar a verificação de SSL, seguindo por suas formas de utilização e associação com domínios. No próximo artigo, comentarei como são constituídos, formatos e extensões e, por último, como gerar sua própria Autoridade Certificadora (CA).</p><p>Na <a href="https://www.base39.com.br/">Base39</a> desenvolvemos <strong>infraestrutura para crédito</strong> e segurança é prioridade. Já abordamos sobre <a href="https://how.base39.works/privacidade-e-seguran%C3%A7a-da-inform%C3%A7%C3%A3o-fintechs-e-startups-cbdb326fff1c">Privacidade e Segurança da Informação: Fintechs e Startups</a> e <a href="https://how.base39.works/criptografia-e2e-558e5151cbdb">Criptografia E2E</a>.</p><h3>O que são e para que servem?</h3><p>De forma simples e direta os certificados digitais são compostos por:</p><ul><li><strong>O certificado</strong>: uma chave pública e bastante metadados.</li><li><strong>As datas de emissão e validade</strong>: até quando o certificado será válido.</li><li><strong>O requerente</strong>: quem solicitou o certificado (pessoas, empresas, sistemas, instituições).</li><li><strong>O emissor</strong>: a entidade que emitiu e assinou o certificado (poucas organizações autorizadas). São as<strong> Autoridades de Certificação,</strong> ou <em>Certificate Authorities</em> (CA), em inglês, elas garantem a confiabilidade ao certificado.</li><li><strong>A cadeia de certificados</strong>: ou, em inglês, <em>certificate chain</em>, é o caminho de assinaturas digitais percorrida por um sistema para verificar o certificado. É constituída por diferentes certificados, o certificado final (do requerente), zero ou mais certificados intermediários e o certificado raiz (ambos da CA).</li></ul><p>Tratando-se de requisição a sites/aplicações, os certificados digitais servem primariamente para dois propósitos:</p><ul><li><strong>Autenticidade:</strong> assegurar que determinado site é quem ele diz que é, validado pelo nome de domínio e assinaturas; e</li><li><strong>Criptografia:</strong> estabelecer uma conexão HTTP segura com SSL/TLS, criptografando todos os dados trafegados entre cliente (ex.: navegador, aplicação, etc.) e servidor (ex.: site ou aplicação).</li></ul><h4><strong>Tá, mas e daí?</strong></h4><p>Para entender estes aspectos, gosto de fazer uma analogia com os documentos emitidos por um Estado, vamos pegar como exemplo o documento de Registro Geral (RG) emitido pela Secretaria de Segurança Pública (SSP) da República Federativa do Brasil. Por que usamos e confiamos no documento de RG para provar quem somos e nos permitir a entrar em um estabelecimento ou abrir uma conta em um banco? Você confiaria da mesma forma em um RG que eu (pessoa) ou o <em>Zezinho da Esquina</em> emitisse?</p><p>Neste exemplo, o RG seria o certificado, a SSP seria o certificado intermediário e o Estado, o certificado raiz. Confiamos no documento de RG pois confiamos na República Federativa do Brasil e em seus critérios de segurança! Esta é a cadeia de confiança, iremos aceitar como válidos todos os documentos emitidos por esta autoridade. Garantindo a <strong>autenticidade</strong>.</p><p>Analisando o RG, temos uma série de detalhes e marcas para assegurar a veracidade do documento, analogamente, o certificado possui chaves, assinaturas digitais e metadados usados na validação e <strong>criptografia</strong>.</p><h4><strong>Por que não posso mais ignorar a verificação de SSL?</strong></h4><p>Seguindo o mesmo princípio de que você não confiaria em um documento RG emitido pelo <em>Zezinho da Esquina</em> para abrir uma conta em um banco (provavelmente, eu espero)<em>, </em>você confiaria em uma API bancária em HTTPS com o certificado emitido pelo <em>Zezinho? (</em>Com todo o respeito aos <em>Zezinhos</em>).</p><p>Ao estabelecer uma das requisição HTTPS (HTTP com S de segurança dos protocolos SSL/TLS), há a verificação de SSL durante o processo SSL Handshake, onde, de forma simplificada, ocorre a troca de informações e confiança mútua entre cliente e servidor, envolvendo o certificado, metadados de algoritmos criptográficos aceitos e chaves públicas para criptografia.</p><p>Ao desabilitar a verificação de SSL, estamos aceitando nos comunicar com qualquer servidor de origem e nossos sistemas estarão mais suscetíveis a brechas de segurança e ataques, por exemplo, requisitar um servidor falso, interceptação de informações por fonte terceira, categorias de ataques conhecidas como <em>Man-in-the-middle </em>(MITM).</p><p>Em ambientes locais e de desenvolvimento, é aceitável ignorar a verificação em alguns casos (como a VPN bloqueando requisições para validar a cadeia de certificados), mas para ambientes de homologação e produção, nunca deve ser uma opção!</p><h4><strong>E os certificados autoassinados?</strong></h4><p>Um certificado autoassinado é todo o certificado não vinculado a uma CA, ou seja, não possuem uma cadeia de certificação (qualquer pessoa pode gerar a partir comandos simples, como ensinado no artigo <a href="https://how.base39.works/criptografia-e2e-558e5151cbdb#77a0">Criptografia E2E</a>).</p><p>Em questão de criptografia, <strong>qualquer certificado</strong> atende o requisito. Não importa se for válido, inválido ou autoassinado, basta o certificado ser aceito pelo cliente requisitante da solicitação e desde que o mesmo não seja ignorado na conexão (ou seja, desde que o <a href="https://cryptoid.com.br/ssl-tls/explicando-os-protocolos-de-seguranca-ssl-e-tls/">SSL Handshake</a> ocorra). Entretanto, para assegurar a <strong>autenticidade</strong>, o certificado não pode ser autoassinado, toda a cadeia de certificação precisa ser válida!</p><blockquote>No próximo artigo, iremos um passo além dos certificados autoassinados, e geraremos um certificado CA para assinar outros certificados! Fique atento às <a href="https://how.base39.works/">postagens da Base39</a>.</blockquote><h3>Formas de utilização em um domínio</h3><p>Um certificado pode estar associado a um domínio, a um conjunto de domínios ou subdomínios. Um domínio é um nome único que identifica um ou um conjunto de sites ou aplicações na internet definido pelo protocolo Sistema de Nomes de Domínio (DNS).</p><p>Por exemplo, base39.com.br é o domínio do site da <a href="https://base39.com.br/">Base39</a>, exemplo.base39.com.br é um subdomínio e *.base39.com.br corresponde a todos os subdomínios da Base39.</p><h4>Nome de domínio do certificado</h4><p>Nos detalhes do certificado, o domínio é declarado no Common Name (CN ou CNAME), sendo este o “nome do certificado” e, além deste, possui os Subject Alternative Name (SAN), que é a lista dos nomes alternativos ao site/aplicação protegido pelo certificado.</p><p>Estes nomes são informados na hora de geração do certificado e, como todas informações do certificado, após geradas, são imutáveis.</p><blockquote>Caso o endereço do site/aplicação não estiver no CN e na lista de SAN, irá resultar no erro de Common Name inválido!</blockquote><h4><strong>Certificado para um domínio</strong></h4><p>Esta é a forma mais comum de certificados, consiste em um certificado que protege apenas um domínio.<strong> </strong>É a opção considerada mais segura por ser mais difícil de ser fraudada ou criar sites/aplicações secundárias.</p><p>A imagem abaixo ilustra um certificado apenas para um domínio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dmis5da14XTJyu11VX429Q.png" /><figcaption>Figura 1 — Detalhes do certificado do site da Base39.</figcaption></figure><p>Podemos observar que ambos nome comum (CN) e nomes alternativos (SAN) protegem apenas o domínio base39.com.br e a variação com o prefixo &quot;www&quot;. Este certificado não poderá ser utilizado para outros nomes de forma a manter-se válido.</p><p>Ainda na imagem, a hierarquia de certificados detalha que este certificado foi emitido e assinado pela CA <a href="https://www.abetterinternet.org/">Internet Security Research Group</a> (ISRG), a qual os sistemas em nossos computadores conhecem e confiam.</p><p>Apesar de ser mais segura, esta opção pode ter o maior custo caso uma mesma organização possua muitos sites ou aplicações, pois seria necessário um certificado para cada um ou declarar múltiplos nomes no SAN, mas a cada novo sistema, será necessário um novo certificado.</p><h4>Certificado para subdomínios</h4><p>Também chamado de “<em>wildcard certificate</em>”, é um certificado que protege todos os subdomínios de um domínio, mas não o domínio em si, pode ser identificado por conter um * no CN do certificado ou na lista SAN.</p><p>Na ilustração abaixo podemos ver em detalhes o certificado da <a href="https://api.base39.io/">API de infraestrutura para crédito da Base39</a>. Este certificado protege tanto o subdomínioapi.base39.io assim como paketa.base39.io.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZ-OdDZWMpqcHrbXJZ2kig.png" /><figcaption>Figura 2— Detalhes do certificado da API de infraestrutura para crédito da Base39.</figcaption></figure><p>O fato de um site/aplicação estar publicado em um subdomínio não obriga a utilização de um certificado aberto para subdomínios (com o *), pode ser emitido normalmente um certificado apenas para um domínio, cobrindo todo o domínio e subdomínio. É o caso do <a href="https://developers.base39.com.br/">Portal do Desenvolvedor Base39</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D70iAsOvgEav6BLHf3o76A.png" /><figcaption>Figura 3 — Detalhes do certificado do site do Portal do Desenvolvedor Base39.</figcaption></figure><h4>Certificado para mais de um subdomínio e riscos envolvidos</h4><p>Os <em>wildcard certificates</em> protegem quantos níveis de subdomínio existir no endereço do site/aplicação, entretanto a grande maioria de navegadores de internet e sistemas com processos de verificação SSL aceitam apenas um nível de subdomínio como válido.</p><p>Por exemplo, caso um certificado for emitido para o CN *.dominio.com poderá proteger os endereços xyz.dominio.com, abc.xyz.dominio.com e xpto.abc.xyz.dominio.com, o HTTPS estará habilitado para todos e a criptografia irá ocorrer, entretanto, a probabilidade de um cliente requisitando este serviço considerar o certificado <strong>inválido</strong> será grande!</p><p>É o que acontece caso tentarmos acessar a API de desenvolvimento do GitHub diretamente em nossos navegadores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhHIOtXxzqJQbr2qgFlJew.png" /><figcaption>Figura 4 — Erro de certificado ao acessar a API de desenvolvimento do GitHub no navegador.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btI5AsW7GpBzUBpGKwDcaw.png" /><figcaption>Figura 5— Detalhes do certificado do site de desenvolvimento da API do GitHub.</figcaption></figure><p>Como esta API não é desenhada para acessar via <em>browsers</em> e é dedicada a um ambiente limitado de desenvolvimento, não há problema na utilização.</p><p>Esta limitação de níveis de subdomínios é praticada para mitigar os <strong>riscos envolvidos com certificados <em>wildcard</em></strong>. Como veremos no próximo artigo, os certificados possuem um par de chaves (pública e privada) e assinados com a chave privada, caso esta chave privada vazar ou o servidor onde os sites/aplicações estão hospedados for comprometido, será um prato cheio para criminosos criarem sites falsos perfeitamente válidos com o seu certificado! Por exemplo, para ataques do tipo <a href="https://br.malwarebytes.com/phishing/"><em>phishing</em></a>. Além disso, certificados para muitos subdomínios adicionam um ponto único de falha na infraestrutura, qualquer erro de certificado acarretará em erros a todos os serviços relacionados.</p><p>A escolha entre os tipos de certificados para um domínio, com múltiplos nomes alternativos (SAN) e certificados <em>wildcard</em> envolve um estudo de caso a caso pesando entre custos e riscos de segurança.</p><h3>Considerações</h3><p>Compreender os assuntos envolvendo a segurança digital é fundamental para profissionais de TI.</p><p>Neste artigo, vimos de forma simples e direta sobre certificados digitais e que estamos sujeitos a ataques <em>Man-in-the-middle</em> (MITM) ao ignorar a verificação SSL em requisições HTTPS. Em sites e APIs, qualquer certificado provê criptografia (inclusive autoassinados!), mas a autenticidade depende, principalmente, da validação do domínio (CN), nomes alternativos (SAN) e da cadeia de CAs.</p><p>Também exploramos os diferentes tipos de certificados, para um domínio, com múltiplos nomes alternativos e certificados <em>wildcard</em>, detalhando características e riscos de cada um.</p><p>No próximo artigo, veremos como são compostos os certificados, formatos e extensões e geraremos uma CA para assinar outros certificados! Fique atento às <a href="https://how.base39.works/">postagens da Base39</a>.</p><h3>Referências:</h3><p>GLOBALSIGN. <strong>Certificate Authority Root</strong>. Disponível em: <a href="https://www.globalsign.com/pt-br/ssl-information-center/certificate-authority-root">https://www.globalsign.com/pt-br/ssl-information-center/certificate-authority-root</a>. Acesso em: 14 de Março de 2023.</p><p>KINAMO. <strong>What are root and intermediate SSL certificates?</strong>. Disponível em: <a href="https://www.kinamo.be/en/support/faq/what-are-root-and-intermediate-ssl-certificates">https://www.kinamo.be/en/support/faq/what-are-root-and-intermediate-ssl-certificates</a>. Acesso em: 05 de Abril de 2023.</p><p>SECURITY REPORT. <strong>Mercado de SI vai movimentar US$ 1,3 bilhão no Brasil neste ano</strong>. 02 de Fevereiro de 2023. Disponível em: <a href="https://www.securityreport.com.br/destaques/mercado-de-si-vai-movimentar-us-13-bilhao-no-brasil-neste-ano">https://www.securityreport.com.br/destaques/mercado-de-si-vai-movimentar-us-13-bilhao-no-brasil-neste-ano</a>. Acesso em: 13 de Março de 2023.</p><p>SERASA. <strong>O que é o certificado digital SSL e como ele pode proteger informações?</strong>. 06 de Fevereiro de 2023. Disponível em: <a href="https://serasa.certificadodigital.com.br/blog/mercado/o-que-e-o-certificado-digital-ssl-e-como-ele-pode-proteger-informacoes/">https://serasa.certificadodigital.com.br/blog/mercado/o-que-e-o-certificado-digital-ssl-e-como-ele-pode-proteger-informacoes/</a>. Acesso em: 14 de Março de 2023.</p><p>SSL.COM. <strong>The SSL/TLS Handshake: an Overview</strong>. <br>03 de Março de 2015. Disponível em: <a href="https://www.ssl.com/article/ssl-tls-handshake-overview">https://www.ssl.com/article/ssl-tls-handshake-overview</a>. Acesso em: 10 de Abril de 2023.</p><p>VENAFI. <strong>Wildcard Certificates Make Encryption Easier, But Less Secure</strong>. Disponível em: <a href="https://venafi.com/blog/wildcard-certificates-make-encryption-easier-but-less-secure/">https://venafi.com/blog/wildcard-certificates-make-encryption-easier-but-less-secure/</a>. Acesso em: 12 de Abril de 2023.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec441077f527" width="1" height="1" alt=""><hr><p><a href="https://medium.com/base39/al%C3%A9m-dos-certificados-ssl-ec441077f527">Além dos certificados SSL</a> was originally published in <a href="https://medium.com/base39">Base39</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>