<?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 Gaurav Talele on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Talele on Medium]]></description>
        <link>https://medium.com/@gauravtalele?source=rss-d241a91074ad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OJQOTuMjY_ax41Lrg0UPlA.png</url>
            <title>Stories by Gaurav Talele on Medium</title>
            <link>https://medium.com/@gauravtalele?source=rss-d241a91074ad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:34:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravtalele/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[Hibernate Inheritance Strategies]]></title>
            <link>https://gauravtalele.medium.com/hibernate-inheritance-strategies-35c51dd33e96?source=rss-d241a91074ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c51dd33e96</guid>
            <category><![CDATA[hibernate-jpa]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[Gaurav Talele]]></dc:creator>
            <pubDate>Sat, 29 May 2021 13:52:18 GMT</pubDate>
            <atom:updated>2021-05-29T13:52:18.294Z</atom:updated>
            <content:encoded><![CDATA[<p>There are three inheritance mapping strategies in hibernate:</p><ol><li><strong>Single Table Per Class:</strong> Only <strong>one table is created </strong>for all the classes involved in hierarchy. Here we maintain an extra <strong>discriminator field</strong> in table to differentiate between the tables.</li><li><strong>Table Per Subclass:</strong> <strong>One table for each class is created</strong>. The above hierarchy gets three tables. Here, foreign key is maintained between the tables.</li><li><strong>Table Per Concrete Class:</strong> <strong>One table for each concrete class (subclass) is created but not of super class</strong>. The above hierarchy gets two tables. As a special case, the super class can be an abstract or interface. Here, foreign key is not maintained.</li></ol><p>The relational model supported by Hibernate is “has-a” relationship. How Hibernate writes tables for the Java classes involved in inheritance? Yes, That&#39;s what we are reveling in this article.</p><h3>Single Table Per Class:</h3><p>In Single table per subclass, the <strong>union of all the properties</strong> from the inheritance hierarchy is mapped to one table. As all the data goes in one table, a discriminator is used to differentiate between different type of data.</p><pre><strong>User (Base class)</strong></pre><pre>// DiscriminatorColumn - Tells about the type of data<br>// DiscriminatorValue - Is the data is representing User type, the // value is &quot;USER&quot;</pre><pre>@Entity<br>@Inheritance(strategy=InheritanceType.SINGLE_TABLE)<br>@DiscriminatorColumn(name=&quot;DISCRIMINATOR&quot;, discriminatorType=DiscriminatorType.STRING)<br>@DiscriminatorValue(&quot;USER&quot;)<br>@Table(name=&quot;BASIC_USER&quot;)</pre><pre>public class User {<br>    protected long id;<br>    protected String name;<br>    ...<br>}<br>-------------------------------------------------------------<strong>Customer Class (Derived from User)</strong></pre><pre>//There is no id column</pre><pre>@Entity<br>@DiscriminatorValue(&quot;CUST&quot;)<br>public class Customer extends User{<br>    protected double creditLimit; <br>    ...<br>}<br>--------------------------------------------------------------<br><strong>Employee Class (Derived From User)</strong></pre><pre>//There is no id column</pre><pre>@Entity<br>@DiscriminatorValue(&quot;EMP&quot;)<br>public class Employee extends User{<br>    protected String rank<br>    ...<br>}</pre><p>Advantages of <strong>Single Table per class hierarchy</strong>:</p><ul><li>Simplest to implement.</li><li>Only one table to deal with.</li><li>Performance wise better than all strategies because no joins or sub-selects need to be performed.</li></ul><p>Disadvantages:</p><ul><li>Most of the column of table are nullable so the NOT NULL constraint cannot be applied.</li><li>Tables are not normalized.</li></ul><h3>Table Per Sub Class:</h3><p>In this case all the classes are mapped to its own table. It’s highly normalized but performance is not good.</p><pre><strong>User class<br>----------</strong></pre><pre>@Entity<br>@Inheritance(strategy=InheritanceType.JOINED)<br>@Table(name=&quot;BASIC_USER&quot;)<br>public class User implements Serializable{<br>    protected long id;<br>    protected String name;<br>    ...<br>}<br>-------------------------------------------------------------</pre><pre><strong>Employee class</strong></pre><pre>@Entity<br>@PrimaryKeyJoinColumn(name=&quot;EMPLOYEE_ID&quot;)<br>public class Employee extends User{    <br>    protected String rank;<br>    ...<br>}</pre><p>The derived class mapped table contain the foreign key which maps it to the base class. The table structure is as follows.</p><p>Basic_User =&gt; ID, NAME</p><p>Employee =&gt; EMPLOYEE_ID (Acts both as primary key and foreign key.), RANK</p><p>Advantage:</p><ul><li>Tables are normalized.</li><li>Able to define NOT NULL constraint.</li></ul><p>Disadvantage:</p><ul><li>Does not perform as well as SINGLE_TABLE strategy</li></ul><h3><strong>Table Per Concrete Class:</strong></h3><p>In this case let’s say our User class is abstract and Customer and Employee are concrete classes. So the table structure that comes out is basically one table for Customer and one table for Employee. The data for User is duplicated in both the tables.</p><pre><strong>User Class</strong></pre><pre>@Entity<br>@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)<br>public abstract class User{<br>    protected long id;<br>    protected String name;<br>    ...<br>}</pre><pre>@Id<br>@GeneratedValue(strategy = GenerationType.AUTO)<br>public long getId() { </pre><pre>}<br>-----------------------------------------------------------<br><strong>Customer class</strong></pre><pre>@Entity<br>public class Customer extends User{<br>    protected double creditLimit;<br>    ...<br>}</pre><p>Advantage:</p><ul><li>Possible to define NOT NULL constraints on the table.</li></ul><p>Disadvantage:</p><ul><li>Tables are not normalized.</li><li>To support polymorphism either container has to do multiple trips to database or use SQL UNION kind of feature.</li></ul><p>Now it is very obvious question that, <strong>Which Strategy to Choose ???</strong></p><p>Usually the choice is between Single Table and Table per subclass strategy. Table per concrete class is optional in JPA and may hinder your portability later on. They also represent the two ends of the spectrum. Some rule of thumbs are:</p><ol><li>If there are many properties common in the base class and very less uncommon properties in derived class. Go for Single table strategy. However make sure your database architect is comfortable with nullable constraint not put on the properties of derived class. If there are too many uncommon properties, you might want to go for table per subclass strategy.</li><li>Another criteria is the amount of polymorphic queries you do. If most of the time you fetch Customer and Employees separately you can go for Table per subclass as this will involve join only on two tables a time. However if you have requirements where you fetch User polymorphically most of the time, Single table strategy will give better performance.</li></ol><p>Another Question Might arise how to <strong>Inherit From a non entity base class ???</strong></p><p>Let’s say we want to put Audit information in many tables. We can make Audit as a base class and make our entities class to inherit from Audit class.</p><pre><strong>Audit class</strong></pre><pre><a href="http://twitter.com/MappedSuperclass">@MappedSuperclass</a><br>public class Audit {    <br>    protected Date updateDate;<br>    protected Date createDate;</pre><pre>    @Temporal(TemporalType.TIMESTAMP)<br>    public Date getCreateDate() {<br>        return createDate;<br>    }<br>    <br>    ...<br>}</pre><pre><strong>User class<br></strong>// If we want to overried the column name than <br>// AttributeOverride is required</pre><pre><a href="http://twitter.com/Entity">@Entity</a><br><a href="http://twitter.com/Table">@Table</a>(name=&quot;BASIC_USER&quot;)<br><a href="http://twitter.com/AttributeOverride">@AttributeOverride</a>(name=&quot;createDate&quot;,column=<a href="http://twitter.com/Column">@Column</a>(name=&quot;CREATE_DATE&quot;))<br>public class User extends Audit{<br>  ...<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c51dd33e96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nginx Top 5 Security Considerations + Problems and their Solutions]]></title>
            <link>https://gauravtalele.medium.com/nginx-top-5-security-considerations-problems-and-their-solutions-d00213388c92?source=rss-d241a91074ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/d00213388c92</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[nginx-proxy]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[web-server-security]]></category>
            <dc:creator><![CDATA[Gaurav Talele]]></dc:creator>
            <pubDate>Tue, 25 May 2021 14:48:46 GMT</pubDate>
            <atom:updated>2021-05-25T14:48:46.483Z</atom:updated>
            <content:encoded><![CDATA[<p>Well, Nginx A Linux based fastest web server across the globe. Yes, you heard right. Today we will see the most important security considerations that can make your nginx server more secure and safer.</p><p>Nginx is a web server that can also be used as a reverse proxy, load balancer, mail proxy and HTTP cache.</p><h4><strong>Step 1. Disable Any Unwanted nginx Modules</strong></h4><p>When you install nginx, it automatically includes many modules. Currently, you cannot choose modules at runtime. To disable certain modules, you need to recompile nginx. We recommend that you disable any modules that are not required as this will minimize the risk of potential attacks by limiting allowed operations</p><h4><strong>Step 2. Disable nginx server_tokens</strong></h4><p>By default, the <em>server_tokens</em> directive in nginx displays the nginx version number. It is directly visible in all automatically generated error pages but also present in all HTTP responses in the <em>Server</em> header.</p><p>This could lead to information disclosure — an unauthorized user could gain knowledge about the version of nginx that you use. You should disable the <em>server_tokens</em> directive in the nginx configuration file by setting</p><pre>server_tokens off;</pre><h4><strong>Step 3. Disable Any Unwanted HTTP methods</strong></h4><p>disable any HTTP methods, which are not going to be utilized and which are not required to be implemented on the web server. If you add the following condition in the location block of the nginx virtual host configuration file, the server will only allow GET, HEAD, and POST methods and will filter out methods such as DELETE and TRACE.</p><pre><strong>location</strong> / { <br>   <strong>limit_except</strong> GET HEAD POST { <strong>deny</strong> all; } <br>}</pre><h4><strong>Step 4. Set Up and Configure nginx Access and Error Logs</strong></h4><p>The nginx access and error logs are enabled by default and are located in <em>logs/error.log</em> and <em>logs/access.log</em> respectively. If you want to change the location, you can use the <em>error_log</em> directive in the nginx configuration file. You can also use this directive to specify the logs that will be recorded according to their severity level. For example, a <em>crit</em> severity level will cause nginx to log critical issues and all issues that have a higher severity level than <em>crit</em>. To set the severity level to <em>crit</em>, set the <em>error_log</em> directive as follows:</p><pre><strong>error_log</strong> logs/error.log crit;</pre><p>You can find a complete list of <em>error_log</em> severity levels in <a href="http://nginx.org/en/docs/ngx_core_module.html#error_log">official nginx documentation</a>.</p><h4>Step 5. Configure Nginx to Include Security Headers</h4><p>we can harden nginx server by configuring security headers in server block.</p><p><strong>X-Frame-Options: </strong>we can<strong> </strong>use the <em>X-Frame-Options</em> HTTP response header to indicate if a browser should be allowed to render a page in a <em>&lt;frame&gt;</em> or an <em>&lt;iframe&gt;</em>. This could prevent <a href="https://owasp.org/www-community/attacks/Clickjacking">clickjacking </a>attacks.</p><pre><strong>add_header</strong> X-Frame-Options &quot;SAMEORIGIN&quot;;</pre><p><strong>Strict-Transport-Security: </strong>HTTP Strict Transport Security (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">HSTS</a>) is a method used by websites to declare that they should only be accessed using a secure connection (HTTPS). If a website declares an HSTS policy, the browser must refuse all HTTP connections and prevent users from accepting insecure SSL certificates.</p><pre><strong>add_header</strong> Strict-Transport-Security &quot;max-age=31536000; includeSubdomains; preload&quot;;</pre><p><strong>Content Security Policy and XSS-Protection: </strong>Content Security Policy (<a href="https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html">CSP</a>) protects your web server against certain types of attacks, including Cross-site Scripting attacks (<a href="https://owasp.org/www-community/attacks/xss/">XSS</a>) and data injection attacks.</p><pre><strong>add_header</strong> Content-Security-Policy &quot;default-src &#39;self&#39; http: https: data: blob: &#39;unsafe-inline&#39;&quot; always;</pre><pre><strong>add_header</strong> X-XSS-Protection &quot;1; mode=block&quot;;</pre><p>Some of the problems and their solutions.</p><p><strong>X-Content-Type-Options: </strong>The X-Content-Type-Options header is used to prevent some types of <strong>MIME-type sniffing techniques</strong>.</p><p>By applying the <strong>‘nosniff’</strong> variable, you can ensure the browser will render the data as original, and not as any other.</p><p>For example, the web server specifies that the content is text/plain. By using this protection, the browser will render the content only as that MIME type, preventing any sniffing attempts.</p><pre><strong>add_header </strong>X-<strong>Content</strong>-Type-Options &quot;nosniff&quot; always;</pre><p><strong>X-Frame-Options: </strong>it was pretty common to build websites using iframes, a quick way to include headers, footers, and even remote content from other websites.</p><p>Today it’s not as common a practice, but some web applications still use it. Unfortunately, a lot of malicious actors use iframes to perform clickjacking attacks and steal sensitive data from users.</p><pre><strong>add_header</strong> X-Frame-Options &quot;DENY&quot; always;</pre><p><strong>Problem 1)</strong> Lets say we need to <strong>correlate NGINX logs with application logs</strong> to have an end-to-end understanding of a request.</p><pre><strong>add_header</strong> X-Request-ID $request_id;</pre><p>and to pass it to app server</p><pre>location / {<br>    proxy_pass http://app_server;<br>    proxy_set_header X-Request-ID $request_id;<br>    access_log /var/log/nginx/access_trace.log trace;<br>}</pre><p><strong>Problem 2) </strong>Performance (Joke Though…)</p><p>we can cache the static content in client side.</p><pre>location ~* \.(css|js)$ {  <br>    expires 1y;   <br>    add_header Cache-Control &quot;public&quot;; <br>}</pre><p><strong>Problem 3) </strong>Need the client source IP address to be correct in the logs of the backend servers.</p><p>X-Forwarded-For Header can be implemented whether or not the --with-http_realip_module was specified at compilation, and modifies the format for the access_log directive to include the X-Forwarded-For Header contents.</p><pre>log_format  main  <br>    &#39;$http_x_forwarded_for - $remote_user [$time_local] &quot;$request&quot; &#39;<br>                        &#39;$status $body_bytes_sent &quot;$http_referer&quot; &#39;<br>                       &#39;&quot;$http_user_agent&quot;&#39;;<br><br>access_log  /var/log/nginx/access.log  main;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d00213388c92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Container Security Considerations From Basics]]></title>
            <link>https://gauravtalele.medium.com/docker-container-security-considerations-from-basics-f489b5f78789?source=rss-d241a91074ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/f489b5f78789</guid>
            <category><![CDATA[docker-security]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Gaurav Talele]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 07:24:51 GMT</pubDate>
            <atom:updated>2021-02-07T07:33:11.221Z</atom:updated>
            <content:encoded><![CDATA[<p>Their are various aspects when we plan to deploy our containerised application into a real production environment. so to go ahead with that we need to ensure weather the underlying environment is following a compliance to security policy. So lets start from the scratch…</p><blockquote>What Exactly Happen When you hit container run:</blockquote><p>it creates a set of namespaces and control groups for the container. <strong>Namespaces provide the first and most straightforward form of isolation</strong>: processes running within a container cannot see, and even less affect, processes running in another container, or in the host system. same as LXC ( now what the heck is LXC…:( ). Well, LXC is an operating-system-level virtualisation method for running multiple isolated Linux systems on a control host using a single Linux kernel. <strong>Control Groups </strong>implement resource accounting and limiting. They provide many useful metrics, but they also help ensure that each container gets its fair share of memory, CPU, disk I/O.</p><p>OK Great. now we will consider what can be done to reduce the surface area and maximise the container security</p><ol><li><strong>Just Use Docker </strong>with running an app in a default-settings Docker Linux container which greatly reduces your risk profile vs. just running that app on a full Linux VM OS. No Absolutely Not, Second option is not even considerable. <strong>So in order to secure and reduce the surface area we can enable SELinux (an alternative to AppArmor), dockerd can also be enabled to use a default SELinux profile as well. SELinux </strong>is a security architecture for Linux systems that allows administrators to have more control over who can access the system. (reference: How AppArmour is enabled <a href="https://docs.docker.com/engine/security/apparmor/">https://docs.docker.com/engine/security/apparmor/</a>)</li><li><strong>Docker Host Config Scan: </strong>By scanning the docker host we can understand how the docker host is installed on machine. also their is a open source tool named Docker Bench Security who can does this job for us. (Reference: <a href="https://github.com/docker/docker-bench-security">https://github.com/docker/docker-bench-security</a>)</li><li><strong>Don’t run apps in containers as root: </strong>Use USER &lt;appname&gt; to prevent your app from running as the root user in the container. Often there is already a user created in official images, but just not enabled until you add the USER line in your own downstream Dockerfile. The recommendation here is to create a user with a known uid in the Dockerfile and run the application process as that user. The start of a Dockerfile should follow this pattern.</li></ol><pre>FROM node:12-slim as base<br>RUN groupadd -g 999 node &amp;&amp; \<br>              useradd -r -u 999 -g node node<br>USER node</pre><pre>RUN mkdir /app &amp;&amp; chown -R node:node /app</pre><pre>...&lt;rest of Dockerfile&gt;...</pre><p>4. <strong>Enable “user namespaces”: </strong>so even the root user in a container isn’t really root on the host. (so even if a hacker broke out of the container they are just limited user on host OS.) This won’t work in all use cases, so consider having different sets of servers where the high-security set has user namespaces enabled and runs all your apps that still work in that setup. Then run the rest on the default Docker config on a different set of servers.</p><p>About remapping and subordinate user and group IDs: The remapping itself is handled by two files: /etc/subuid and /etc/subgid. Each file works the same, but one is concerned with the user ID range, and the other with the group ID range. [ testuser:231072:65536 ] This means that testuser is assigned a subordinate user ID range of 231072 and the next 65536 integers in sequence. UID 231072 is mapped within the namespace (within the container, in this case) as UID 0 (root). UID 231073 is mapped as UID 1,</p><p><strong>To Enable userns-remap on the daemon: </strong>Edit /etc/docker/daemon.json add { “userns-remap”: “testuser” }, Restart Docker, verify by &gt;id dockremap</p><p>Verify that the entry has been added to /etc/subuid and /etc/subgid:</p><pre>$ grep dockremap /etc/subuid<br><br>dockremap:231072:65536<br><br>$ grep dockremap /etc/subgid<br><br>dockremap:231072:65536 # This Is Test User Entry 231072</pre><pre>$ sudo ls -ld /var/lib/docker/231072.231072/</pre><p>To disable user namespaces for a specific container, add the --userns=host flag to the docker container create, docker container run, or docker container exec command.</p><p><strong>5. App and OS dependency scanning: </strong>You want to scan for vulnerabilities in both your app dependencies (npm, pip, composer, etc.) and OS dependency’s (apt, apk, yum). There are three main stages where you can do this: git commits, image build, and after image build:</p><p>git For app dependency-only CVE (<a href="https://cve.mitre.org/data/downloads/index.html">https://cve.mitre.org/data/downloads/index.html</a>) scanning in your git repos, use something like <a href="https://snyk.io/"><strong>Snyk</strong></a><strong> </strong>(or just GitHub built-in) to scan your git repos for known vulnerabilities. This is great for <a href="https://www.twistlock.com/resources/shift-left-security/">shift-left security</a>.</p><p>CI Scan during image build. Aqua Security <a href="https://github.com/aquasecurity/microscanner"><strong>Microscanner</strong></a> does OS CVE (Common Vulnerabilities and Exposures number) scanning inside a container build, which I think is very handy, but doesn&#39;t look for app dependencies and doesn&#39;t have the full Alpine support if you need it. Compliments the git-repo scanning above</p><p>CI Scan images after build or on servers. Docker Hub used to do this for a fee, now you&#39;ll need Docker EE or 3rd party. I think the best open-source scanner right now might be Aqua Security&#39;s <a href="https://github.com/aquasecurity/trivy#os-packages">Trivy</a> which claims to have the most complete scanner, especially for Alpine-based images. It scans images from outside Docker. This could replace the above two methods. (Reference 1: <a href="https://www.youtube.com/watch?v=cCJhN9nl1NY&amp;feature=youtu.be">https://www.youtube.com/watch?v=cCJhN9nl1NY&amp;feature=youtu.be</a>, Reference 2: <a href="https://github.com/aquasecurity/microscanner">https://github.com/aquasecurity/microscanner</a>)</p><p><strong>6. Don’t Expose the Docker TCP Socket to the Internet: U</strong>se docker’s built-in SSH connection method to remotely control the Docker Engine without exposing anything other than SSH. This is perfect for remote docker admin and CI/CD solutions. Here’s a <a href="https://youtu.be/5EuDY6ayNs8?t=382">demo of using it with the </a><a href="https://youtu.be/5EuDY6ayNs8?t=382">DOCKER_HOST=ssh://user@host environment variable</a>, and <a href="https://youtu.be/fJTaUvcCJts?t=1621">here&#39;s a demo of using it with the new </a><a href="https://youtu.be/fJTaUvcCJts?t=1621">docker context</a> in 19.05 (docker context ls)</p><p>Note that most tools that need the Docker socket (Portainer, Traefik) have a way to do it without exposing the TCP port to remote connections. Once you have higher-level admin tools like web admins, you now need to protect them, as they become the target. To protect them, use VPN-only or private network access, high random port, or add a stronger web proxy auth in front of them.</p><p><strong>7. Runtime Bad Behavior Monitoring: </strong><a href="https://sysdig.com/opensource/falco/">Sysdig Falco</a> has the great idea of watching your containers for unusual behavior, like an exec command, or bind-mounting sensitive host files in /etc, or something trying to mess with certain files <em>in</em> a container... it will watch the system and log these actions (based on a default set of rules that you can add to). You can run this small binary on every host, and have it log to a central location.</p><p><strong>8. </strong><a href="https://docs.docker.com/engine/security/trust/"><strong>Content Trust</strong></a><strong>:</strong> which has to do with signing your code, and then the images all the way through the CI/CD pipeline and finally making certain your servers won’t deploy new containers on images you didn’t cryptographic-ally trust. <a href="https://docs.docker.com/engine/security/trust/content_trust/">Docker does this</a>, Docker Enterprise makes it easier, also other platforms may do this.</p><p><strong>9. Use Slimmed-Down Base Images: </strong>which will set off less CVE’s when scanning images, and prevent attack vectors that could potentially use the vulnerable software that wasn’t included in the larger, more “full-featured” base images. There are several downsides to doing this and there are several choices in choosing your base.</p><ul><li>Smaller base images mean less utilities are included, and that usually means that the smaller the base is, the more skilled you need to be at managing/using containers. What do you do when your container needs troubleshooting, but it doesn’t have curl or ping? Or even a shell? There are ways to deal with this limitation, but it’s more than just docker exec.</li><li>A scratch (empty) or busybox image is the smallest. I see very few able to get away with those.</li><li>Alpine is a popular choice, and most official images have a version using alpine, but I’ve seen specific issues in rare cases by choosing Alpine over the default Debian, and I only know of one CVE scanner that correctly handles it: <a href="https://github.com/aquasecurity/trivy">trivy</a>, and if you’re forced to use a different scanner, then I recommend comparing results to trivy to ensure it does what the scanner maker claims.</li><li>Slim is an option that some official images have, and I prefer it. It’s just a bit larger than Alpine, but is Debian-based so that doesn’t have the limitations of Alpine.</li></ul><p><strong>10. “Distroless” Docker Images: </strong>“Distroless” images contain only your application and its runtime dependencies. They do not contain package managers, shells (cant docker exec -it) or any other programs you would expect to find in a standard Linux distribution.</p><p>(Reference: <a href="https://github.com/GoogleContainerTools/distroless">https://github.com/GoogleContainerTools/distroless</a>)</p><p><strong>11. Docker root-less: </strong>his is an option for running the dockerd daemon as a normal user on the host. It’s new in 2019 and if you already do all the above, it may be more work then it’s worth to use this, but it can also be handy when you don’t have local admin, or you’re interested in<strong> CI automation without local admin</strong>. See Docker’s blog post.<strong> Note the biggest limitation is lack of virtual networking (which still requires root).</strong> Watch this <a href="https://www.youtube.com/watch?v=Qq78zfXUq18"><strong>DockerCon</strong></a> session on it, and install it with a script as a normal Linux user https://get.docker.com/rootless</p><h4>References:</h4><ul><li><a href="https://www.cisecurity.org/benchmark/docker/">CIS Docker Benchmarks - CIS</a></li><li><a href="https://sysdig.com/blog/20-docker-security-tools/">29 Docker security tools compared. | Sysdig</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f489b5f78789" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Node JS Rest API]]></title>
            <link>https://gauravtalele.medium.com/secure-node-js-rest-api-1780ec6c8656?source=rss-d241a91074ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/1780ec6c8656</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Gaurav Talele]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 12:52:03 GMT</pubDate>
            <atom:updated>2020-03-20T12:52:03.531Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Folks, This is friday. Today we will discuss how we can secure our rest api against various attacks. You might already know that these attacks are very harmful and you need to make your application (or API) secure, as much as you can. But how exactly…?</p><p><strong>Their are DOS Attacks, XSS, SQL/NoSQL Injection Attacks.</strong></p><p>You might already know that these attacks are very harmful and you need to make your application (or API) secure, as much as you can. But how exactly?</p><h3>Denial-Of-Service (DOS) Attacks</h3><p>DOS Attack will crash / shut down a network, or machine, making it inaccessible. Which means users won’t be able to access your application, for example. Attacker accomplishes this by constantly sending requests, creating traffic and sending plenty of all kind of a informations. <br>With DOS attacks, attackers can either make your service <strong>slower</strong> or<strong> crash it </strong>entirely.</p><h3>Cross-Site Scripting (XSS) Attacks</h3><p>XSS Attacks are a type of injections. Attackers inject malicious scripts into the forms of a browser side script. Usually they occur on input forms when those forms are not validated or encoded. With XSS attacks, attacker can gain access to cookies, session tokens or / and other sensitive data. As well, these scripts can rewrite HTML content of a page.</p><h3>Brute Force Attacks</h3><p>Brute force attack is a method used to obtain sensitive data such as user password or personal identification number (PIN). In these attacks, attackers most likely rely on automated software to generate a large numbers guesses to the value of desired data.</p><h3>SQL/NoSQL Injection Attacks</h3><p>SQL/NoSQL Injection (SQLi) Attacks is a type of an injection attack. SQL/NoSQL Injection makes it possible for attacker to execute malicious SQL/NoSQL statements. Attackers can achieve SQL/NoSQL Injection attack simply by inserting SQL/NoSQL commands (queries) to a specific fields on your application that is connected to a database (POST request for logging in for example).With SQL/NoSQL Injection Attacks, attackers can bypass authentication, authorization, retrieve the content of the entire SQL/NoSQL database, add, modify, delete data in database.</p><h3>The Question is how to prevent these attacks…?</h3><h4>Preventing DOS Attacks:</h4><ol><li>First thing to consider when dealing with DOS attacks prevention is to limit the actual payload that user can submit to your app / api / service. You can <strong>limit the body payload using body-parser.</strong> If you are using ExpressJS as your backend framework, then you are golden. ExpressJS comes with built-in body-parser that you can use.</li></ol><pre>const express = require(&#39;express&#39;);<br>const app = express();app.use(express.json({ limit: &#39;10kb&#39; })); // Body limit is 10</pre><p>2.Another useful express feature is <strong>express-rate-limit dependency. </strong>This dependency lets you set rate limit for users. So basically, you can set maximum amount of requests for each user, after user uses all of his requests, you can lock him out for certain amount of time.</p><p><em>— npm install express-rate-limit</em></p><pre>const limit = rateLimit({<br>    max: 100,// max requests<br>    windowMs: 60 * 60 * 1000, // 1 Hour<br>    message: &#39;Too many requests&#39; // message to send<br>});<br>app.use(&#39;/routeName&#39;, limit); // Setting limiter on specific route</pre><h3>Preventing XSS Attacks:</h3><ol><li>First of all, you can sanitize user data, on input. This is very easy to implement, and we can use another useful dependency called <strong>xss-clean.<br></strong>This dependency will prevent users from inserting HTML &amp; Scripts on input.</li></ol><p><em>— npm install xss-clean</em></p><pre>app.use(xss());</pre><p>2. Give your project special HTTP headers using<strong> helmet</strong> dependency. Helmet is a collection of middleware functions. By default, not all of the middleware functions are included, but you can enable rest of them manually. You can check <a href="https://github.com/helmetjs/helmet/#user-content-how-it-works">this</a> link to see other middleware functions.</p><p><em>— npm install helmet</em></p><pre>app.use(helmet());</pre><h3>Preventing Brute Force Attacks</h3><ol><li>One of the most efficient way to help you to deal with brute force attacks, is to set limit to login attempts, or anything related to authentication that requires users to insert their passwords, special codes or PINs.</li><li>Next up, and again, if you are using ExpressJS, you could implement <strong>express-rate-limit dependency. </strong>Which we did indeed implemented in DOS attacks prevention. But this dependency works both for Brute Force attacks and DOS attacks.</li><li>To slower down and make life a little bit harder for attackers when guessing sensitive data (passwords, PINs), you could implement <strong>bcrypt dependency. </strong>Bcrypt will encrypt sensitive data such as passwords and it will make them harder to guess. Bcrypt is a little bit complex dependency, but if you want to learn more (and you should) checkout this <a href="https://www.npmjs.com/package/bcrypt">link</a>.</li><li>Another thing that will make brute force attacks less likely is implementing <strong>2-Step verification process</strong>, or <strong>two-factor authentication</strong>. It does take couple of lines of codes to implement this, so here is the <a href="https://davidwalsh.name/2fa">link</a> that will help you out with it!</li></ol><h3>Preventing SQL/NoSQL Injection Attacks</h3><ol><li>Either if you are working with SQL or NoSQL database, you should sanitize your data. <br>If you are working with SQL database, you should consider using <strong>node-mysql dependency. </strong>Learn more about node-mysql <a href="https://github.com/mysqljs/mysql#escaping-query-values">here</a>.<br>If you are working with NoSQL database (MongoDB) and ExpressJS, consider using <strong>express-mongo-sanitize dependency.</strong></li></ol><p><em>— npm install express-mongo-sanitize</em></p><pre>app.use(mongoSanitize());</pre><p>2. If working with MongoDB, use Object Data Modeling tool (ODM) <strong>Mongoose</strong>. Mongoose lets you define schemas and schema types for each one of your documents, making it secure from the beginning. Mongoose is pretty complex on it’s own, but if you want to dive deep into it, i’ll suggest you to check this <a href="https://code.tutsplus.com/articles/an-introduction-to-mongoose-for-mongodb-and-nodejs--cms-29527">link</a> or get a crash course on it and learn it on the go.</p><h3>Your main app file could look like this after you implemented these dependencies:</h3><pre>// Importing Dependencies<br>const express = require(&#39;express&#39;);<br>const rateLimit = require(&#39;express-rate-limit&#39;);<br>const helmet = require(&#39;helmet&#39;);<br>const mongoSanitize = require(&#39;express-mongo-sanitize&#39;);<br>const xss = require(&#39;xss-clean&#39;);<br>const app = express();// Helmet</pre><pre>app.use(helmet());// Rate Limiting</pre><pre>const limit = rateLimit({<br>    max: 100,// max requests<br>    windowMs: 60 * 60 * 1000, // 1 Hour of &#39;ban&#39; / lockout <br>    message: &#39;Too many requests&#39; // message to send<br>});<br></pre><pre>app.use(&#39;/routeName&#39;, limit); </pre><pre>app.use(express.json({ limit: &#39;10kb&#39; })); <br><br>app.use(mongoSanitize());</pre><pre>app.use(xss()</pre><h3>Conclusion:</h3><p><em>These are just couple of methods, practices that you can use in your own project to make your application or API secure. You can explore each one of these more in depth following references i included or simply researching more about them on your own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1780ec6c8656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Swarm Cluster Setup With Vagrant]]></title>
            <link>https://gauravtalele.medium.com/docker-swarm-cluster-setup-with-vagrant-bca5ddb7a672?source=rss-d241a91074ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/bca5ddb7a672</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vagrant]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[swarm]]></category>
            <dc:creator><![CDATA[Gaurav Talele]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 10:30:51 GMT</pubDate>
            <atom:updated>2019-12-03T10:30:51.134Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>GOAL</em></strong><em>: in this article we will start two node Docker Swarm Cluster and go over commands to manage multiple nodes. We will put a detailed glance on topics 1) starting the Swarm 2) viewing Swarm status 3) joining the Swarm 4) obtaining join-tokens 5) Run Containers with replication 6) Response to fail-over</em></p><h3>System Requirements</h3><p><strong>Considering we will do this LAB on Windows System.</strong> On this System we will Install Chocolatey + Vagrant + Install Virtualbox.</p><p>Open PowerShell as a Administrator:</p><pre>Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString(&#39;<a href="https://chocolatey.org/install.ps1&#39;">https://chocolatey.org/install.ps1&#39;</a>))</pre><p>Restart The Powershell with administrator privileges.</p><pre>choco install virtualbox vagrant --yes<br>mkdir DockerSwarmCluster &amp;&amp; cd DockerSwarmCluster</pre><p>Open Command Prompt and navigate to <em>DockerSwarmCluster </em>directory.</p><p>create a new file named <em>Vagrantfile. and paste following code.</em></p><pre>$install_docker_script = &lt;&lt;SCRIPT<br>echo Installing Docker...<br>curl -sSL <a href="https://get.docker.com/">https://get.docker.com/</a> | sh<br>sudo usermod -aG docker ubuntu<br>SCRIPT</pre><pre>$manager_script = &lt;&lt;SCRIPT<br>echo Swarm Init...<br>sudo docker swarm init --listen-addr 10.100.199.200:2377 --advertise-addr 10.100.199.200:2377<br>sudo docker swarm join-token --quiet worker &gt; /vagrant/worker_token<br>SCRIPT</pre><pre>$worker_script = &lt;&lt;SCRIPT<br>echo Swarm Join...<br>sudo docker swarm join --token $(cat /vagrant/worker_token) 10.100.199.200:2377<br>SCRIPT</pre><pre>Vagrant.configure(&#39;2&#39;) do |config|</pre><pre>vm_box = &#39;ubuntu/xenial64&#39;</pre><pre>config.vm.define :manager, primary: true  do |manager|<br>    manager.vm.box = vm_box<br>    manager.vm.box_check_update = true<br>    manager.vm.network :private_network, ip: &quot;10.100.199.200&quot;<br>    manager.vm.network :forwarded_port, guest: 8080, host: 8080<br>    manager.vm.network :forwarded_port, guest: 5000, host: 5000<br>    manager.vm.hostname = &quot;manager&quot;<br>    manager.vm.synced_folder &quot;.&quot;, &quot;/vagrant&quot;<br>    manager.vm.provision &quot;shell&quot;, inline: $install_docker_script, privileged: true<br>    manager.vm.provision &quot;shell&quot;, inline: $manager_script, privileged: true<br>    manager.vm.provider &quot;virtualbox&quot; do |vb|<br>      vb.name = &quot;manager&quot;<br>      vb.memory = &quot;1024&quot;<br>    end<br>  end</pre><pre>(1..2).each do |i|<br>    config.vm.define &quot;worker0#{i}&quot; do |worker|<br>      worker.vm.box = vm_box<br>      worker.vm.box_check_update = true<br>      worker.vm.network :private_network, ip: &quot;10.100.199.20#{i}&quot;<br>      worker.vm.hostname = &quot;worker0#{i}&quot;<br>      worker.vm.synced_folder &quot;.&quot;, &quot;/vagrant&quot;<br>      worker.vm.provision &quot;shell&quot;, inline: $install_docker_script, privileged: true<br>      worker.vm.provision &quot;shell&quot;, inline: $worker_script, privileged: true<br>      worker.vm.provider &quot;virtualbox&quot; do |vb|<br>        vb.name = &quot;worker0#{i}&quot;<br>        vb.memory = &quot;1024&quot;<br>      end<br>    end<br>  end</pre><pre>end</pre><h3>About The Vagrantfile:</h3><p>This makes two different virtualboxes, one named: manager, another named: worker01 and worker02.</p><p>With the way the Vagrantfile configuration, connects each virtualbox to a private network with IP Addresses 10.100.199.200 (manager), 10.100.199.201 (worker01) and 10.100.199.202 (worker02).</p><p>All actions taken on manager, worker01,worker02 are equivalent to working on separate computers.</p><pre>vagrant up</pre><p>Now this will fetch the ubuntu/xenial64 box from vagrant cloud and make the necessary configuration including installation of docker engine and docker compose.</p><p>Once the process exited.</p><pre>Command Prompt 1 &gt; vagrant ssh manager<br>Command Prompt 2 &gt; vagrant ssh worker01<br>Command Prompt 3 &gt; vagrant ssh worker02</pre><h3>Create a service At Manager Node</h3><pre>docker service create --name my_web <br>                     --replicas 7<br>                     --publish published=8080,target=80 <br>                     nginx</pre><p>now, See all the docker containers from the nodes.</p><pre>vagrant@manager  &gt; docker container ls<br>vagrant@worker01 &gt; docker container ls<br>vagrant@worker02 &gt; docker container ls</pre><h3>Why Should we use Vagrant To Setup Docker Swarm</h3><p><a href="https://www.vagrantup.com/">Vagrant</a> is a tool for building and managing virtual machine environments in a single workflow. With an easy-to-use workflow and focus on automation, Vagrant lowers development environment setup time, increases production parity, and makes the “works on my machine” excuse a relic of the past. Vagrant is convenient to share virtual environment setup and configurations.</p><p>Vagrant allows us very easily to share setups between team members allowing very easy spin up of a work environment.</p><h3>Conclusion</h3><p>Vagrant provides an easy way to define and share a different application or environment setup in a single text file called Vagrantfile. Vagrant uses virtualization engines like VirtualBox, VMWare or Hyper-V and builds on top of them</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bca5ddb7a672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with AWS CLI + Configure Cli User role for Programmatic Access + Cli Profiles]]></title>
            <link>https://gauravtalele.medium.com/getting-started-with-aws-cli-configure-cli-user-role-for-programmatic-access-cli-profiles-58cb344427b4?source=rss-d241a91074ad------2</link>
            <guid isPermaLink="false">https://medium.com/p/58cb344427b4</guid>
            <category><![CDATA[setup]]></category>
            <category><![CDATA[aws-cli]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[iaac]]></category>
            <dc:creator><![CDATA[Gaurav Talele]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 06:48:46 GMT</pubDate>
            <atom:updated>2019-11-18T06:48:46.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*uu4i9_itUCO5YnMdXuvOPA.png" /></figure><blockquote><strong><em>GOAL:</em></strong> The aws-cli is a neat and handy command line tool from which management of AWS-services is way more faster. Therefore, this blog focuses on the usage of aws-cli. Within in this post, I’ll explain to you how to setup the aws-cli and create a Cli user for programmatic access.</blockquote><h3><strong>Why Should we use AWS CLI / Benefits:</strong></h3><p>1) You can develop shell scripts to manage resources<br>2) You have direct access to the AWS services’ public APIs.<br>3) You can use all of the functionality provided by the AWS Management Console.<br>4) Provides low level commands for complete control and high level commands which simplify using a complex service.</p><h3><strong>AWS Free Tier Programme:</strong></h3><p>New customers of AWS have the possibility of testing some services for 12 months. Which consists of 750 hours per month of AWS EC2, 5 GB of S3 Storage and many more. You can find more in this <a href="https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&amp;all-free-tier.sort-order=asc"><strong><em>link</em></strong></a>.</p><h3>Create an AWS-account</h3><p>Before we can begin setting up aws-cli, you need to have an AWS-account. If you already have an account you can skip the next three steps.</p><ol><li>Go to the <a href="https://aws.amazon.com/"><strong><em>AWS start page</em></strong></a> and click on the <strong>Register </strong>button on the top right</li><li>Select “I am a new customer” and enter a valid email-address</li><li>On the following screens, just enter your personal data as requested. You also might get asked for your credit card details, so keep them at hand during the registration process.You will need a credit card for registration process.</li></ol><h3>Create a sub-account</h3><ol><li>Login to the AWS Management Console with your root-account, which you just created before. Then go to the AWS-service<strong> IAM</strong> from the service group <strong>“Administration &amp; Security”</strong></li><li>Select<strong> “Users”</strong> in the menu on the left side</li><li>Click on <strong>“Create New Users”</strong></li><li>Enter a User Name and ensure that <strong>“Generate an access key for each user” </strong>is enabled</li><li>Download the created credentials. <strong>This is the only time you’ll be able to download the credentials.</strong> Store the credentials at a save place. If you loose that credentials, you can’t retrieve the password anymore. Only a reset is possible afterwards.</li></ol><h3>For Ubuntu / Debian-based OS</h3><p>The aws-cli is installed via python-pip. Therefore, firstly we need to install pip, which is a plugin package-manager for the python runtime environment.</p><pre>sudo apt-get install -y python-pip</pre><pre>sudo apt-get install -y python</pre><h3>For Windows</h3><p>Download and install the MSI-installation file</p><ul><li><a href="https://s3.amazonaws.com/aws-cli/AWSCLI64.msi">AWS CLI MSI (64-bit)</a></li><li><a href="https://s3.amazonaws.com/aws-cli/AWSCLI32.msi">AWS CLI MSI (32-bit)</a></li></ul><p>After installing cli packages you will configure aws-cli for its usage with the AWS-services. Therefore, you need the credentials from the previously created sub-account. Open the downloaded credentials.csv and use the <strong>Access Key Id</strong> and <strong>Secret Access Key</strong> for the following configuration.</p><p>Concerning the default region, use the one, which suits you best. The list for the regions is available at <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html"><strong><em>link</em></strong></a>.</p><p><strong><em>NOTE:</em></strong><em> Keep in mind that not every regions is offering all AWS-services. The region with the most offered services is probablly </em><strong><em>us-east-1</em></strong><em>. A complete list of available services per region can be found </em><a href="http://docs.aws.amazon.com/general/latest/gr/rande.html"><em>here</em></a><em>. Furthermore, the prices and privacy agreements can differ from region to region.</em></p><pre>&gt; aws configure<br>AWS Access Key ID []: &lt;Access Key Id&gt;<br>AWS Secret Access Key []: &lt;Secret Access Key&gt;<br>Default region name []: &lt;eu-central-1&gt;<br>Default output format []: text </pre><p>By default, the CLI installs to C:\Program Files\Amazon\AWSCLI (64-bit version) or C:\Program Files (x86)\Amazon\AWSCLI (32-bit version). To confirm the installation, use the aws — version command at a command prompt (open the Start menu and search for cmd to start a command prompt).</p><p><strong>Test the AWS CLI Installation:</strong></p><p>Hope, you have installed AWS CLI on your computer. You may think that what next? To do.</p><pre>aws --version<br>aws iam list-users --output table</pre><h3>Named Profiles</h3><p>You can configure additional profiles by using aws configure with the --profile option, or by adding entries to the config and credentials files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*Iui1Oi2IkMUMXwAdV0SI8g.jpeg" /><figcaption><strong>~/.aws/credentials</strong> (Linux &amp; Mac) or <strong>%USERPROFILE%\.aws\credentials</strong> (Windows)</figcaption></figure><pre><strong>aws ec2 describe-instances --profile user1</strong></pre><p>To use a named profile for multiple commands, you can avoid specifying the profile in every command by setting the AWS_PROFILE environment variable at the command line.</p><pre><strong>export AWS_PROFILE=user1 # for Linux or Mac<br>setx AWS_PROFILE=user1 # for Windows User </strong></pre><p>For windows systems close and restart the command shell to see the effects of the change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58cb344427b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>