<?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 Jonathan Tew on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Tew on Medium]]></description>
        <link>https://medium.com/@jonathantew?source=rss-d42d4fc52905------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*niDtCz8dRZb1EjfB</url>
            <title>Stories by Jonathan Tew on Medium</title>
            <link>https://medium.com/@jonathantew?source=rss-d42d4fc52905------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:43:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jonathantew/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[API Gateway Websocket Directly To SQS FIFO queue]]></title>
            <link>https://medium.com/@jonathantew/api-gateway-websocket-directly-to-sqs-fifo-queue-e8c4ee97a51d?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c4ee97a51d</guid>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 15:50:39 GMT</pubDate>
            <atom:updated>2023-03-24T15:50:39.371Z</atom:updated>
            <content:encoded><![CDATA[<p>As with all the articles I publish, they are born out of the frustration that I endured to figure out the solution.</p><p>We are starting to build an application that communicates over websocket. Your first inclination when programming this pattern is to have the API Gateway send the websocket message directly to your AWS Lambda function. That works, but if you have volatile spikes of traffic then you could easily exhaust your Lambda concurrency pool. The solution to this problem is to use an SQS FIFO queue to make sure that the messages from the websocket maintain their order, but can be processed asynchronously by an AWS Lambda function at a predictable concurrency and rate. So the problem we need to solve is connecting API Gateway Websocket directly to SQS without using an intermediate lambda function. A flow diagram of this looks like:</p><pre>Browser &lt;---websocket connection---&gt; API Gateway --&gt; SQS FIFO --&gt; AWS Lambda</pre><p>Inside of the API Gateway Websocket configuration click on the $default route and then click on Integration Request as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suNT1HuErbMXP9G_E3iL5g.png" /></figure><p>Next we’ll cover all the configuration of the SQS integration that you can do from the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7k7Ffm4G6ACvBse83TxLhA.png" /></figure><p>Next we need to use a Request Template to transform the data into the format needed by SQS. Setup a template key named “\$default” as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5L5UbYjZFCbvN19LXGzGA.png" /></figure><p>For the template use the following Velocity:</p><pre>Action=SendMessage&amp;MessageGroupId=$util.urlEncode($context.connectionId)&amp;MessageDeduplicationId=$util.urlEncode($context.requestId)&amp;MessageAttribute.1.Name=connectionId&amp;MessageAttribute.1.Value.StringValue=$util.urlEncode($context.connectionId)&amp;MessageAttribute.1.Value.DataType=String&amp;MessageAttribute.2.Name=requestId&amp;MessageAttribute.2.Value.StringValue=$util.urlEncode($context.requestId)&amp;MessageAttribute.2.Value.DataType=String&amp;MessageAttribute.3.Name=sourceIp&amp;MessageAttribute.3.Value.StringValue=$util.urlEncode($context.identity.sourceIp)&amp;MessageAttribute.3.Value.DataType=String&amp;MessageBody=$util.urlEncode($input.json(&#39;$&#39;))</pre><p>The template is doing the following:</p><ul><li>Setting the SQS action to SendMessage</li><li>Using the connectionId as the MessageGroupId so that all messages for the same connection are processed in order within the FIFO queue.</li><li>The websocket requestId is used as the MessageDeduplicationId</li><li>The connectionId, requestId, and sourceIp are passed as message attributes on the SQS message.</li><li>The body of the websocket message is encoded as the MessageBody of the SQS message.</li></ul><p>Once you save that you have done ALL the configuration that is possible within the UI. Will this integration work? NO! When you send a message and look at your Cloudwatch logs for API gateway you are going to see the following error come back from SQS:</p><pre>UnknownOperationException error</pre><p>Doing a Google search of that particular SQS error message will lead you to the following <a href="https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-rest-api-sqs-errors/">article</a> which correctly articulates what the problem is:</p><pre>An UnknownOperationException error occurs when a user fails to configure the Content-Type as &quot;application/x-www-form-urlencoded&quot; in the integration request HTTP header. The UnknownOperationException error also occurs when you don&#39;t add the SendMessage action to the integration request mapping template.</pre><p>At this point I’m scratching my head on why in the world the API Gateway integration would not take care of sending the proper header. At this point I opened up a case with AWS support. While waiting for the response I continue to ride the struggle bus to try and figure this out. I’m searching and I come across the following article: <a href="https://serverlessland.com/patterns/apigw-websocket-sqs-lambda">https://serverlessland.com/patterns/apigw-websocket-sqs-lambda</a></p><p>This article shows how to set this up using a Cloudformation template and I can see in his template the way he’s configure it to send the proper Content-Type header:</p><pre>      RequestParameters:<br>        integration.request.header.Content-Type: &quot;&#39;application/x-www-form-urlencoded&#39;&quot;</pre><p>I’m not using Cloudformation so there has got to be a way to do this on the command line.</p><p>First we’ll run a command to find out all the integrations on our API. You’ll need the API ID in order to run this command:</p><pre>aws apigatewayv2 get-integrations --api-id &lt;API ID&gt;</pre><p>You’re looking for the integration ID associated with the SQS $default route. It will look something like this:</p><pre>&quot;IntegrationId&quot;: &quot;abc123&quot;</pre><p>Once you have that ID, you need to create a JSON file named integration-definition.json that contains the following contents:</p><pre>{<br>            &quot;ConnectionType&quot;: &quot;INTERNET&quot;,<br>            &quot;CredentialsArn&quot;: &quot;arn:aws:iam::1234567890:role/apigateway-sqs-abc-role&quot;,<br>            &quot;IntegrationMethod&quot;: &quot;POST&quot;,<br>            &quot;IntegrationType&quot;: &quot;AWS&quot;,<br>            &quot;IntegrationUri&quot;: &quot;arn:aws:apigateway:us-east-1:sqs:path/1234567890/my-app-websocket-message.fifo&quot;,<br>            &quot;PassthroughBehavior&quot;: &quot;NEVER&quot;,<br>            &quot;PayloadFormatVersion&quot;: &quot;1.0&quot;,<br>            &quot;RequestParameters&quot;: {<br>                &quot;integration.request.header.Content-Type&quot;: &quot;&#39;application/x-www-form-urlencoded&#39;&quot;<br>            },<br>            &quot;RequestTemplates&quot;: {<br>                &quot;\\$default&quot;: &quot;Action=SendMessage&amp;MessageGroupId=$util.urlEncode($context.connectionId)&amp;MessageDeduplicationId=$util.urlEncode($context.requestId)&amp;MessageAttribute.1.Name=connectionId&amp;MessageAttribute.1.Value.StringValue=$util.urlEncode($context.connectionId)&amp;MessageAttribute.1.Value.DataType=String&amp;MessageAttribute.2.Name=requestId&amp;MessageAttribute.2.Value.StringValue=$util.urlEncode($context.requestId)&amp;MessageAttribute.2.Value.DataType=String&amp;MessageAttribute.3.Name=sourceIp&amp;MessageAttribute.3.Value.StringValue=$util.urlEncode($context.identity.sourceIp)&amp;MessageAttribute.3.Value.DataType=String&amp;MessageBody=$util.urlEncode($input.json(&#39;$&#39;))&quot;<br>            },<br>            &quot;TemplateSelectionExpression&quot;: &quot;\\$default&quot;,<br>            &quot;TimeoutInMillis&quot;: 29000<br>}</pre><p>Make sure that in your JSON you adjust the CredentialsArn and IntegrationUri to match your IAM role ARN and SQS ARN.</p><p>Now you need to run the following AWS CLI to update the integration configuration. Make sure to specify your API ID and Integration ID:</p><pre>aws apigatewayv2 update-integration --api-id &lt;API ID&gt; --integration-id &lt;INTEGRATION ID&gt; --integration-type AWS --integration-method POST --integration-uri &quot;arn:aws:apigateway:us-east-1:sqs:path/1234567890/my-app-websocket-message.fifo&quot; --passthrough-behavior NEVER --payload-format-version 1.0 --cli-input-json file://integration-definition.json</pre><p>At this point you need to deploy your API so that the configuration change is completed. You can do the deployment through the web interface. Wait about a minute and then send your websocket message. You should see it arrive in your SQS FIFO queue.</p><p>AWS, seriously you need to document this for your SQS integration or just detect and inject the needed content header automatically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8c4ee97a51d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS HTTP API directly to SQS with User Agent and IP Address]]></title>
            <link>https://medium.com/@jonathantew/aws-http-api-directly-to-sqs-with-user-agent-and-ip-address-39ca3dda56fe?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ca3dda56fe</guid>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Tue, 17 May 2022 12:06:30 GMT</pubDate>
            <atom:updated>2022-05-20T06:26:12.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Like many companies, ingestion of millions to billions of “beacons” from web browsers is very common when doing analytics tracking. Originally the best serverless solution we could come up with was:</p><p><strong>API Gateway REST -&gt; SQS</strong></p><p>API Gateway for REST has been around a long time and there is a pretty clean blueprint for pushing messages directly into SQS. A complex mapping template like the sample below formats the information to pass off to SQS.</p><pre>Action=SendMessage&amp;MessageBody=$util.urlEncode($input.json(&#39;$&#39;))&amp;MessageAttribute1.Name=IP&amp;MessageAttribute1.Value.StringValue=$util.urlEncode($context.identity.sourceIp)&amp;MessageAttribute1.Value.DataType=String&amp;MessageAttribute2.Name=UA&amp;MessageAttribute2.Value.StringValue=$util.urlEncode($context.identity.userAgent)&amp;MessageAttribute2.Value.DataType=String&amp;MessageAttribute3.Name=TS&amp;MessageAttribute3.Value.StringValue=$context.requestTimeEpoch&amp;MessageAttribute3.Value.DataType=String</pre><p>The problem is that this costs $3.50 per million beacons processed. The ideal solution would be able to do this with the AWS HTTP version of API Gateway which only costs $1.00 per million instead of the REST version. The <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html">documentation</a> on message attributes for the SQS integration is lacking concrete examples.</p><p>That is the purpose of this simple article. Here is the recipe to do the same thing with HTTP API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReIJtDv_AmSjHBeg2FAKYA.png" /></figure><p><strong>Message Body</strong></p><pre>$request.body</pre><p><strong>Message Attributes</strong></p><pre>{&quot;UA&quot;: {&quot;DataType&quot;: &quot;String&quot;, &quot;StringValue&quot;: &quot;${request.header.user-agent}&quot;}, &quot;IP&quot;: {&quot;DataType&quot;: &quot;String&quot;, &quot;StringValue&quot;: &quot;${context.identity.sourceIp}&quot;}, &quot;TS&quot;: {&quot;DataType&quot;: &quot;String&quot;, &quot;StringValue&quot;: &quot;${context.requestTimeEpoch}&quot;}}</pre><p>You can add additional message attributes other than UA, IP or TS to your message. Just follow the standard JSON pattern. All the variables are <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging-variables.html">documented here</a>. Just make sure you use the syntax <strong>${variable}</strong> inside of the quotes.</p><p>Enjoy the 71.4% cost savings on ingestion of web beacons!</p><p><strong>P.S.</strong></p><p>The epoch on the HTTP Gateway context is the number of seconds since the epoch. If you’re end code is looking for milliseconds then multiply the value by 1,000 during your SQS processing logic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ca3dda56fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically Cleanup AWS Cloudwatch LogStreams]]></title>
            <link>https://medium.com/@jonathantew/automatically-cleanup-aws-cloudwatch-logstreams-94d7f6c89820?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d7f6c89820</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[cloudwatch-logs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 16:05:52 GMT</pubDate>
            <atom:updated>2022-07-21T11:39:44.935Z</atom:updated>
            <content:encoded><![CDATA[<p>Cloudwatch will retain empty Log Streams after the data retention time period. To fix this we’re going to use a simple NodeJS based lambda function</p><pre>var AWS = require(&quot;aws-sdk&quot;);</pre><pre>var cloudwatchlogs = new AWS.CloudWatchLogs();</pre><pre>exports.handler = async (event) =&gt; {</pre><pre>// Paginated loop to describe each log group<br>    let describeLogGroupsRequest = {<br>    };<br>    for (;;) {<br>      let describeLogGroupsResponse = await cloudwatchlogs.describeLogGroups(describeLogGroupsRequest).promise();</pre><pre>for (let i = 0; i &lt; describeLogGroupsResponse.logGroups.length; i++) {<br>         await processLogGroup(describeLogGroupsResponse.logGroups[i]);<br>      }  <br>      <br>      describeLogGroupsRequest.nextToken = describeLogGroupsResponse.nextToken;<br>      if (!describeLogGroupsResponse.nextToken) break;<br>    }</pre><pre>    return {};<br>};</pre><pre>async function processLogGroup(logGroup) {<br>    console.log(&quot;processLogGroup&quot;, logGroup.logGroupName);</pre><pre>    // Ignore things with infinite retention<br>    if (!logGroup.retentionInDays) {<br>        console.log(&quot;Log group &quot;, logGroup.logGroupName, &quot; is configured for infinite retention.&quot;);<br>        return;<br>    }<br>    <br>    console.log(&quot;Log group configured to retain &quot;, logGroup.retentionInDays, &quot; days&quot;);<br>    <br>    var describeLogStreamsRequest = {<br>        logGroupName: logGroup.logGroupName,<br>        orderBy: &#39;LastEventTime&#39;<br>    };<br>        <br>    for (;;) {<br>        var describeLogStreamsResponse = await cloudwatchlogs.describeLogStreams(describeLogStreamsRequest).promise();<br>        <br>        for (var i = 0; i &lt; describeLogStreamsResponse.logStreams.length; i++) {<br>            var logStream = describeLogStreamsResponse.logStreams[i];<br>            <br>            // Sanity check this to prevent accidental delete<br>            if (!logStream.lastIngestionTime) continue;<br>            <br>            // How old is this log stream based upon ingestion<br>            var diffMillis = new Date().getTime() - logStream.lastIngestionTime;<br>            var diffDays = diffMillis / (1000 * 86400);<br>            <br>            console.log(&quot;Contents of stream&quot;, logStream.logStreamName, &quot; is &quot;, diffDays, &quot;days&quot;);<br>            if (diffDays &gt; logGroup.retentionInDays) {<br>                console.log(&quot;Log stream&quot;, logStream.logStreamName, &quot; is eligible for delete.&quot;);<br>                <br>                var deleteLogStreamRequest = {<br>                   &quot;logGroupName&quot;: logGroup.logGroupName,<br>                   &quot;logStreamName&quot;: logStream.logStreamName<br>                };<br>                <br>                try {<br>                    await cloudwatchlogs.deleteLogStream(deleteLogStreamRequest).promise();<br>                    console.log(&quot;Deleted log stream&quot;, logStream.logStreamName);<br>                    await sleep(200);<br>                } catch (e) {<br>                    if (e.message === &quot;Rate exceeded&quot;) {<br>                        console.log(&quot;We&#39;ve hit a rate limit error so we are stopping for this log group.&quot;);<br>                        return;<br>                    } else {<br>                        console.log(&quot;Error deleting log stream&quot;, e.message);<br>                        return;<br>                    }<br>                }<br>            } else {<br>                console.log(&quot;Done with log group&quot;, logGroup.logGroupName);<br>                return;<br>            }<br>        }</pre><pre>describeLogStreamsRequest.nextToken = describeLogStreamsResponse.nextToken;<br>      if (!describeLogStreamsResponse.nextToken) break;<br>      <br>      // Pause 1 second every loop to avoid throttling on the list method.<br>      await sleep(1000);<br>    }<br>    <br>}</pre><pre>const sleep = (milliseconds) =&gt; {<br>  return new Promise(resolve =&gt; setTimeout(resolve, milliseconds))<br>}</pre><p>Besides the default role that is created, you’ll also want to give the Lambda the following permissions in IAM.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;logs:DescribeLogGroups&quot;,<br>                &quot;logs:DescribeLogStreams&quot;,<br>                &quot;logs:DeleteLogStream&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>Configure the lambda for a 15 minute execution timeout and 128 MB of RAM.</p><p>Finally we want to schedule this Lambda function to invoke one every 15 minutes using Cloudwatch Events. Once that’s done the Lamba function should keep Cloudwatch Log Streams in check.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d7f6c89820" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving SQS responsive without sacrificing long polling]]></title>
            <link>https://medium.com/@jonathantew/improving-sqs-responsive-without-sacrificing-long-polling-edf8ebd1883b?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf8ebd1883b</guid>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 17:14:57 GMT</pubDate>
            <atom:updated>2020-01-07T17:14:57.983Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re like me than to optimize SQS costs you typically would long poll for 20 seconds asking for up to 10 messages. That’s great until you have a bunch of queues within a pipeline and you end up with reduced responsiveness. To solve this behavior I wrote a simple class that wraps around the SQS client to intelligently poll. It has two modes:</p><ul><li>Ask for 1 message, but wait up to 20 seconds.</li><li>Ask for 10 messages, but wait up to 1 second.</li></ul><p>The code starts out by long polling for a single message. As soon as one message arrives it flips back to polling for 10 messages, but only waiting for a second. As soon as a receive request returns zero messages the code flips back to long polling. This logic substantially reduced end-to-end responsiveness in some of our queue heavy applications without drastically increasing SQS operation pricing.</p><pre>package com.sample.aws.sqs.util;</pre><pre>import com.amazonaws.services.sqs.AmazonSQS;<br>import com.amazonaws.services.sqs.model.ReceiveMessageRequest;<br>import com.amazonaws.services.sqs.model.ReceiveMessageResult;</pre><pre>public class SQSClientIntelligentLongPoller {<br>  private AmazonSQS sqsClient;</pre><pre>private int messageCount = 1;</pre><pre>public SQSClientIntelligentLongPoller(AmazonSQS sqsClient) {<br>    this.sqsClient = sqsClient;<br>  }</pre><pre>public ReceiveMessageResult receiveMessage(ReceiveMessageRequest receiveMessageRequest) {<br>    // Adjust the request to what the poller things is a good idea<br>    receiveMessageRequest.setMaxNumberOfMessages(messageCount);<br>    // If we&#39;re waiting for a single message to arrive then there is no reason not to long poll as long as possible.<br>    if (messageCount == 1) {<br>      receiveMessageRequest.setWaitTimeSeconds(20);<br>    } else {<br>      // If we&#39;re waiting on more than one record at this point then only wait a second.  We want to quickly ramp up the<br>      // record count we&#39;re asking for or reach an empty queue and go back to long polling for one record.<br>      receiveMessageRequest.setWaitTimeSeconds(1);<br>    }</pre><pre>// Perform the receive message op<br>    ReceiveMessageResult receiveMessageResponse = sqsClient.receiveMessage(receiveMessageRequest);</pre><pre>// Adjust based upon how many messages we received back<br>    if (receiveMessageResponse.getMessages().size() == 0) {<br>      if (messageCount &gt; 1) {<br>        messageCount = 1;<br>      }<br>    } else if (messageCount &lt; 10) {<br>      messageCount = 10;<br>    }</pre><pre>return receiveMessageResponse;<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf8ebd1883b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Things I Don’t Miss About On-premise Data Centers]]></title>
            <link>https://medium.com/@jonathantew/10-things-i-dont-miss-about-on-premise-data-centers-7b0db2341111?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b0db2341111</guid>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Sun, 07 Jul 2019 12:55:00 GMT</pubDate>
            <atom:updated>2019-07-07T12:55:00.927Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Physical proximity to the actual data center for hardware repair, troubleshooting, etc.</li><li>High availability switching configurations, switch firmware, cabling, etc.</li><li>VMWare is the best we could do, but machine failures, etc. are enough to scare you to death when you don’t have hundreds of servers. Decent size percentages of your workload can fail at once.</li><li>Upgrading firewalls that were absolutely mission critical. Even when you follow the blessed upgrade paths there is risk and failures. Firewalls also have to sit between each subnet to do their job. Having security groups as a firewall around each device and referencing other devices by security group is awesome.</li><li>Storage Area Networks (SANs) during upgrades. With great vendors their is risk. With some of the upstarts that have been gobbled up a few times, their devices become downright scary to run their warrantied lifetimes. Lack of SANs in the cloud forces you to deploy databases differently, but you’re better off in the long run as you’ve reduced single points of failure further.</li><li>Cross connecting multiple data centers. The magic of multi-AZ deployments is awesome. Doing this yourself costs an absolute fortune. The data centers are just starting to roll out products to make virtual circuits between multiple of their data centers possible via portals.</li><li>Figuring out a way to do unified logging. Cloudwatch just makes this so darn easy and cheap. Being able to integrate it into Lambdas is awesome.</li><li>Planning and purchasing hardware. Enterprise hardware is very expensive, you have to over provision, and a number of times you get it wrong and end up with an expensive paper weight in the data center.</li><li>Power modifications. Now OSHA won’t let the data center electricians do anything hot at all so if a modification has to take place, half your circuits could be shut down for a period of time. Always scary.</li><li>Training other staff on skills to manage the data center. Just too much to learn for a lot of people. Small companies can’t train staff on all the different layers of the stack. It’s so much easier to have developers control the data center via APIs and manage the full stack.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b0db2341111" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blocking Traffic from TOR Exit Nodes on Servers Behind an AWS Network Load Balancer]]></title>
            <link>https://medium.com/@jonathantew/blocking-traffic-from-tor-exit-nodes-on-servers-behind-an-aws-network-load-balancer-e97022fde295?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97022fde295</guid>
            <category><![CDATA[network-load-balancer]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[iptables]]></category>
            <category><![CDATA[tor]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Fri, 03 May 2019 17:11:26 GMT</pubDate>
            <atom:updated>2020-02-10T10:43:00.220Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re running AWS GuardDuty then it will flag as a medium any traffic from a TOR exit node that interacts with your instance. We blocked TOR exit nodes on our ELB using a WAF IP Set that we periodically update with a Lambda function.</p><p>If you’re using an NLB to front other servers though, that blocking must be done on the instances. Sure we’d all love a checkbox on the AWS NLB configuration that says “block TOR exit node traffic”, but right now that is something we have to do ourselves. Here is the script that we’re running every 15 minutes via a crontab on our instances.</p><pre>#!/bin/bash</pre><pre># Based upon <a href="http://mikhailian.mova.org/node/194">http://mikhailian.mova.org/node/194</a></pre><pre># Create a new set for individual IP addresses.  <br># If the set already exists then ignore the error<br>/sbin/ipset -N tor iphash || true<br># The list could already exist so we&#39;ll flush it<br>/sbin/ipset flush tor<br># Define public ips here.  <br># Put one entry for each public IP of the NLB<br>publicIps=( &quot;123.123.123.123&quot; &quot;234.234.234.234&quot; )<br># get a list of Tor exit nodes that can access your ip, <br># skip the comments and read line by line<br>for publicIp in &quot;${publicIps[@]}&quot;<br>do<br>  echo &quot;Fetching TOR exit node list for IP: $publicIp&quot;<br>  wget -q <a href="https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=$publicIp">https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=$publicIp</a> -O -|sed &#39;/^#/d&#39; |while read IP<br>  do<br>    # add each IP address to the new set, silencing the warnings <br>    # for IPs that have already been added<br>    /sbin/ipset -q -A tor $IP<br>  done<br>done<br># filter our new set in iptables.  Make sure to delete the <br># existing rule so we don&#39;t pile these up each time it runs<br>/sbin/iptables -D INPUT -m set --match-set tor src -j DROP || true<br>/sbin/iptables -A INPUT -m set --match-set tor src -j DROP</pre><p>Depending upon the flavor of linux you’re running, you may have to install an additional package to get the “ipset” command. On Ubuntu that command is:</p><pre>apt-get install ipset</pre><h4>Further Enhancement</h4><p>Recently we also created a Lambda function to listen for GuardDuty findings of malicious IPs scanning some of our public IPs. We take those findings and build up a text file on S3. We modified the script to include a block like this:</p><pre># Grab our own IP reputation list and add that as well<br>wget -q <a href="https://bucket-with-reputation-file.s3.amazonaws.com/guardduty-ips.txt">https://bucket-with-reputation-file.s3.amazonaws.com/guardduty-ips.txt</a> -O -|sed &#39;/^#/d&#39; |while read IP<br>do<br>  # add each IP address to the new set, silencing the warnings for IPs that have already been added<br>  /sbin/ipset -q -A tor $IP<br>done</pre><p>In addition to the set of guardduty ips collected automatically above, we also started blocking entire networks that host the TOR exit nodes. We look up those networks in ARIN/RIPE, etc. and then place them on a WAF IP Set. The same lambda updates another text file of networks. We now run an ipset for individual ips and an ipset for networks that we block.</p><p>We also removed the flush of the ipset each time the script runs. We found that during the script execution there was a brief window where the tor traffic could hit the server and create another event in GuardDuty. By removing the flush we prevent this problem, but we also know that it makes a false positive more problematic. So far we have not had any false positives to deal with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97022fde295" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On-demand Access to Production Application Logs in AWS for Developers]]></title>
            <link>https://medium.com/@jonathantew/on-demand-access-to-production-application-logs-in-aws-for-developers-f17a109a759f?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/f17a109a759f</guid>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kinesis]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Sun, 17 Mar 2019 11:57:58 GMT</pubDate>
            <atom:updated>2019-05-18T11:01:01.455Z</atom:updated>
            <content:encoded><![CDATA[<p>As you journey to the public cloud with your application the deployment structure is going to get more complicated. Fixed instances at predictable IP addresses are replaced with auto scaled instances in multiple AZ’s for high availability. In an on-premise environment the developer might login to the instance and tail/grep the log data to see what is going on. That task gets harder in the cloud which the dynamic nature of the ASG instances. This story is how we solved our version of the problem.</p><p>Our application produces a lot of log information using a popular logging framework that supports configurable filters to determine where the log data goes. I guess we could have simply written a filter that shipped 100% of the log data off to Cloudwatch Logs and provided access that way, but there are a lot of unknowns and cost associated with that. We were looking for the minimal amount of change possible to the application. The ideal solution would be a command line utility that developers could run which would cause a cloud version of “tail &amp; grep” of the logs in a secure fashion.</p><p>The solution we came up with was a log engine filter which would listen to an SQS queue for control messages. When the control messages came in the application would publish them out to all nodes in the cluster using our existing Redis pub/sub framework. The filter running on each node of the application is listing to the Redis publication and takes action. When a request is received the filter begins taking log messages that match the regex patterns and bundling them up. After a certain amount of time has elapsed (5 seconds) or the size of messages reaches a threshold (512KB), we compress, encrypt and then send the log messages to a Kinesis stream. The command line utility that the developer is using is reading the Kinesis stream and looking for messages associated with it’s session. It then decrypts, uncompresses, and displays the log events on the developers console. Messages not associated with the session are discarded by the application.</p><h3>The functionality that we achieved:</h3><ul><li>On-demand access to logs</li><li>Ability to filter through multiple regex expressions just like you would do with multiple grep statements on the command line</li><li>Servlerless solution with low overhead &amp; fixed cost</li><li>Zero application impact when no requests and minimal impact when an active on-demand request is taking place</li><li>Restrict access through IAM users/policies which control access to the SQS control queue and the Kinesis data channel.</li><li>AES encryption to make sure one client is not reading log event bundles from the Kinesis stream that are not destined for it.</li><li>Ability to specify a client IP address to monitor log entries associated with that customer IP across the entire cluster.</li><li>Ability to specify an individual node that we’re interested in performing on-demand analysis (if that node is known)</li><li>Ability to search historical data located from the beginning of the log file on disk (opened in read only mode and grepped through) before monitoring in real-time.</li></ul><h3>Why did we choose Kinesis &amp; SQS for our integration?</h3><p>Both of these services combined give us a highly secure way to transmit log data without having to connect up to a VPN, SSH into a server, use Systems Manager, or ship all of the log data out into another environment.</p><p>SQS was chosen for the control channel. The control channel is where simple JSON payloads to start / heartbeat / stop on-demand requests are communicated. SQS gives us inexpensive long polling functionality. We could have done the control channel with another Kinesis stream that all nodes were reading from instead of using the SQS/Redis solution, but it would have required another stream with it’s associated hourly cost. We also like the ability to have a separate SQS queue per environment that we’re allowing access to and securing that with IAM.</p><p>Kinesis was chosen for the data transport because it supports multiple clients processing the stream of data at their own location. We can also scale up the # of shards in Kinesis if the throughput requirements of the on-demand requests necessitate it. Generally speaking developers are looking for very specific data that is low volume so a single shard is typically more than enough. That gives us a cost of approximately $11.16/mo. Even though this stream is shared, the encryption key generated by the client and used to encrypt the data on the server ensures that only the client that made the request can read that log data.</p><h3>Security</h3><ul><li>EC2 role’s use policies that give specific permission to read the SQS queue and write to the Kinesis stream.</li><li>IAM user profiles give specific permission to write to the SQS queue for the particular environment and read from the Kinesis stream.</li><li>AES GCM encryption is used to secure the event data going through the shared Kinesis stream.</li></ul><h3>Deployment</h3><ul><li>Single JAR Java application</li><li>Configuration file with JSON to specify the different environments</li><li>IAM profile configuration on the developers workstation.</li></ul><h3>Safeguards</h3><p>What if a developer does a REALLY stupid pattern like .* on the production application cluster? Yeah that is going to be a LOT of data! Let’s look at some things that will happen both on the client and the server. First from the clients perspective:</p><ul><li>Your console can only display text at a certain rate of speed so the client application is going to end up falling behind the most recent point in the Kinesis queue and take time to catch up.</li><li>As soon as CTRL-C/SIGINT is detected the polling loop is stopped and the stop control message is sent to SQS.</li></ul><p>Now on to the more important topic of how the servers protect themselves.</p><ul><li>Log events are batched up and then placed into a queue. The queue is processed by an asynchronous thread that performs the Kinesis operations. If the queue fills up then the data is simply discarded.</li><li>The asynchronous thread sending data to Kinesis will deal with throughput exceeded scenarios and back off until it can successfully send.</li><li>If an on-demand request is not heartbeat every 5 minutes then it’s shut off. This prevents requests from continuing to process if the client has unexpectedly died without performing a clean stop.</li></ul><h3>Roadmap</h3><p>As with all projects, we’ve come up with a few ideas that we haven’t implemented yet.</p><ul><li>Track on-demand requests within a database table so that if a new instance comes online or a build is loaded with CodeDeploy, we can continue performing the on-demand logging when the application starts.</li><li>Historical log searching in S3. Since we archive logs off into S3, it would be ideal if the client could specify a date range on the search. A lambda function would be concurrently invoked to perform the searching of each log file (pull down from S3, uncompress, grep, and send output to temporary files on S3). After the lambda functions finish, the client could download the temporary files from S3, display the output and then cleanup the temp files. Using lambda like this would give us high concurrency without wasting a bunch of bandwidth pulling the data down from S3 all the way to the client.</li><li>Change the application log format to JSON so that logs archived into S3 would be searchable by S3 Select instead of text alone using Lambda functions.</li></ul><h3>Conclusion</h3><p>The cloud forces you to think differently about how you handle production operations, but giving up access to your application logs is not necessary. There are very low cost ways to give developers secure access to log data so they can have faster time to resolution when problems arise.</p><h3>Real World Usage So Far</h3><p>This log access strategy has been great. Since building this tool, not once have we logged into an individual instance to tail the log file. It’s definitely the right cloud native strategy for real-time log access.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17a109a759f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating ModSecurity with AWS WAF]]></title>
            <link>https://medium.com/@jonathantew/integrating-modsecurity-with-aws-waf-f26b5af4c1a8?source=rss-d42d4fc52905------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26b5af4c1a8</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[modsecurity]]></category>
            <category><![CDATA[asl]]></category>
            <category><![CDATA[waf]]></category>
            <category><![CDATA[atomic-secured-linux]]></category>
            <dc:creator><![CDATA[Jonathan Tew]]></dc:creator>
            <pubDate>Mon, 24 Dec 2018 12:37:46 GMT</pubDate>
            <atom:updated>2019-03-17T10:41:10.407Z</atom:updated>
            <content:encoded><![CDATA[<p>The journey to the cloud for companies is not as easy and simple as the marketing videos of cloud providers make it out to be. This article details some of the backstory in a phase of our journey.</p><p>We started by setting up ELB load balancers w/ certificates managed by ACM to handle customer facing HTTPS traffic. This traffic ultimately proxies to existing web servers running our WAF and then on to our application servers.</p><p>We started by white-listing all of the NAT gateway IP addresses that would hit our existing WAF from our VPC so that if our existing WAF blocked traffic, it would not SHUN the IP which would be our NAT gateways. At this point we’ll still 403 a malicious request, but we had no way of firewalling off the IP to stop their traffic entirely.</p><p>We tested some managed rules by several vendors on AWS WAF, but honestly we just didn’t feel like we understood the product, how to configure it actually block stuff, etc. It would have taken a much larger investment of time learning their WAF to completely replace our existing WAF.</p><p>We still have the problem though of wanting to block malicious traffic for a period of time once an attack is detected just like we could with our on-premise infrastructure. We need to stop that traffic before it ever enters the VPC. Time to write some glue code…</p><p>So let’s dive into how we’re accomplishing this further with ModSecurity and AWS WAF. ModSecurity is one of the most popular WAF (web application firewalls) available. ModSecurity has existed for Apache for a long time and the newer libmodsecurity 3.x is bringing that functionality to Nginx. The rule sets available for ModSecurity range from free to paid and professionally maintained:</p><ul><li><a href="https://modsecurity.org/crs/">OWASP Core Rule Set</a></li><li><a href="https://www.atomicorp.com/amember/cart/index/index?c=6">Atomicorp Secure Linux</a></li><li><a href="https://www.trustwave.com/Products/Application-Security/ModSecurity-Rules-and-Support/">Trustwave Rule Set</a></li></ul><p>Our organization has been long time users of Atomicorp Secure Linux (ASL) so we are very familiar with their rule sets, tuning them, and interacting with their support. Great organization to work with.</p><p>So let’s get into the core of how we have things plumbed today. ASL manages the Apache and ModSecurity components of the web server. When a malicious request happens an entry is output to /var/log/httpd/audit_log and then a file is written under /var/asl/audit/data/… The processing flow looks like this.</p><ol><li>Our web server watchdog program tails the audit_log, reads the individual event records, does some regex parsing and then ships the event data off via HTTPS to an AWS API Gateway</li><li>API Gateway pushes the data into SQS “shun” queue.</li><li>We have our “SHUN” Lambda function wired up to the SQS queue so it immediately gets invoked. It reads the payload (extracting ELB headers, etc.), interacts with an RDS database to determine what should be done for the given rule and the IP’s history and then if desired we update an AWS WAF IP Set tied to a blacklist rule. Putting an IP on the ip set for the blacklist rule is the equivalent of ASL running an iptables command to shun the IP at the linux firewall level. The lambda function also stores a copy of the modsecurity event payload in S3 for further review in a consolidated manner.</li><li>Like standard ASL you typically want to unblock the IP after a period of time. So we send another SQS queue for “unshun”, but this queue is configured to have a 10 minute delivery delay.</li><li>Our “UNSHUN” lambda is invoked by the SQS queue and then decides if the IP address should be unblocked. If so it is removed from the AWS WAF IP set. This lambda function also does some audit work to make sure the AWS WAF IP Set reflects the IPs we want blocked based upon our tracking database. Sometimes removing an IP from the IP set will fail if you have a batch of them and you have to retry them one by one. Took a little trial and error to make the audit routine robust.</li></ol><p>So what we’ve achieved using:</p><ul><li>1 API Gateway</li><li>1 S3 bucket</li><li>2 SQS queues</li><li>2 Lambda functions</li><li>1 RDS cluster (3 tables)</li><li>AWS WAF</li><li>ASL ModSecurity WAF</li></ul><p>is a cloud based WAF with industry leading rules which responds within milliseconds to a malicious requests and SHUNs the traffic using AWS WAF across all our ELBs.</p><p>Our hope is that ASL will update their product offering to provide a direct integration with AWS WAF to provide this functionality. In our ideal world ASL would:</p><ul><li>Not run a local database, but instead all the instances would be able to use an RDS Aurora MySQL database for all of the event tracking, rule configuration, IP reputation, etc. across multiple web servers in a single pain of glass deployment.</li><li>Manage the AWS WAF IP Set for blacklisting via a simple configuration option (and of course the IAM Role assigned to the instance permitting it)</li><li>Expose event stream information to SNS so it can be routed to various other AWS services for integration and analysis.</li></ul><p>We’ve also done some experimenting to build the lightest web server possible and achieve similar blocking functionality. We have tested the following:</p><ol><li>Compile modsecurity from source enabling JSON support on CentOS. Not as bad as you would think it would be once you figure out the dependencies.</li><li>Configure modsecurity and mlogc to perform an HTTPS PUT directly to an API Gateway (since it’s JSON we can go straight into the API Gateway without any code to modify)</li></ol><p>This scenario works fine with both the OWASP core rule set or ASL rule set, but we’ll have to write a rule set upgrading engine to automate that since we don’t have a full blown ASL installation in that particular scenario.</p><p>One other highly effective thing we did was block traffic where the host header was a numeric IP address and the URL ended in .php. These are nothing more than malicious scanners going IP by IP across the internet looking for vulnerable PHP installations. They will literally hit your server with hundreds of requests. So we now issue a block on the very fire request and prevent them from abusing our infrastructure.</p><p>The other scenario we’ve found helpful is for our application to block requests with a 403 response code(this will cause a modsecurity event to be generated) and also include an HTTP response header with an additional reason code. Our shun lambda function is seeing these events and performing blocks as if an actual modsecurity rule was tripped. This allows us to tie application level security code to the AWS WAF by leveraging the existing plumbing.</p><p>In our tracking database we’re also banning IPs entirely after they trip a certain number of blocks. These are persistent bad acting IPs so we ban them for much longer periods of time.</p><p>How much does this plumbing scenario cost to operate? The most expensive part would be the RDS Aurora database cluster, but most AWS customers have at least one of those they can piggy back on. The rest of the API Gateway, SQS and Lambda processing is probably &lt; $1/mo. The amount of code written is probably less than 1000 lines end-to-end. Costs for traffic through the WAF will vary based upon the number of requests that you’re processing. Bottom line is it’s an inexpensive solution.</p><p>How high could you scale this solution? An AWS WAF ACL can have 10 rules and if those rules were all blacklist rules then you could block up to 100,000 (10 x 10,000) IPs at once.</p><p>We shared this idea with the folks over at ASL and they were excited about it. I’m very hopeful that we’ll see native support for this in ASL or OSSEC in the near future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26b5af4c1a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>