<?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 Rahul Ram on Medium]]></title>
        <description><![CDATA[Stories by Rahul Ram on Medium]]></description>
        <link>https://medium.com/@rahulram?source=rss-6e09f54d5e3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*GY4ldVo-xDVAXI0PjnkIqw.png</url>
            <title>Stories by Rahul Ram on Medium</title>
            <link>https://medium.com/@rahulram?source=rss-6e09f54d5e3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:22:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulram/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[Provide Limited Shell Access to users in Linux]]></title>
            <link>https://medium.com/@rahulram/provide-limited-shell-access-to-users-in-linux-ae86eabbe699?source=rss-6e09f54d5e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae86eabbe699</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Rahul Ram]]></dc:creator>
            <pubDate>Tue, 25 Jul 2017 05:25:48 GMT</pubDate>
            <atom:updated>2017-07-25T05:25:48.653Z</atom:updated>
            <content:encoded><![CDATA[<p>I was wondering, on whats the best way to provide limited shell access to certain users. I get to talk to many people in the security domain and one thing many people have consensus on is,</p><blockquote>Its always better to whitelist on what a user can do, as apposed to blacklist things the user cannot do. They ll, always find a way to break it!</blockquote><p>The following were my requirements</p><ol><li>Execute few bash commands like date etc in non-sudo mode.</li><li>I dint want to use any third party shells or add extra code to the platform. Basically, make as minimal changes as possible with least overhead.</li><li>I should be easily able to extend the privileges (in this case mostly what commands the users can execute)</li></ol><p>My first thought was to chroot, which is like creating a jail like environment for the user. But afaik, there is not easy way grant sudo access for certain commands in chroot as you ll have to copy all the sudo and its dependent files to chrooted environment. It very soon gets messy. Besides, over a period of time, it ll be very difficult to manage as and when I add a few more commands to extend the users privilege.</p><p>So finally, I decided to use restricted bash shell (rbash). All you need to do is to add set -r in your .bash_profile and limit the PATH to users HOMEand HOME/bin</p><p>When you login either via console or via ssh, .bash_profile is executed by the shell before your initial command prompt. After logging in, if you create another bash instance by typing /bin/bash, then .bashrc is executed. So its better to set restricted mode changes in .bash_profile as apposed to .bashrc</p><p>In rbash, users cannot do the following things.</p><ul><li>Changing directories with the cd builtin.</li><li>Setting or unsetting the values of the SHELL, PATH, ENV, or BASH_ENV variables.</li><li>Specifying command names containing slashes.</li><li>Specifying a filename containing a slash as an argument to the . builtin command.</li><li>Specifying a filename containing a slash as an argument to the -p option to the hash builtin command.</li><li>Importing function definitions from the shell environment at startup.</li><li>Parsing the value of SHELLOPTS from the shell environment at startup.</li><li>Redirecting output using the ‘&gt;’, ‘&gt;|’, ‘&lt;&gt;’, ‘&gt;&amp;’, ‘&amp;&gt;’, and ‘&gt;&gt;’ redirection operators.</li><li>Using the exec builtin to replace the shell with another command.</li><li>Adding or deleting builtin commands with the -f and -d options to the enable builtin.</li><li>Using the enable builtin command to enable disabled shell builtins.</li><li>Specifying the -p option to the command builtin.</li></ul><p>This pretty much restricts users from doing anything meaningful. We might as well not give access in the first place. But wait, there is more… we need to whitelist some the bash commands for the user. Remember, after setting restricted shell you cannot execute any command with / in it. So, the user cannot really access /bin/ls etc. In order to allow users to do that, we need to create symbolic links to actual path. That way, they can access those commands from their home directory. So all the whitelisted cmds can be linked by symbolic link.</p><p>sudo ln -s /bin/ls /home/limited_user/bin/ls</p><p>Now that we can created a bunch of symbolic links, the users can execute those commands without the need to add / in it.</p><p>After all this, I was thinking I have pretty much secured a limited access shell to user….. spoiler alert! Nooooooo <br>Users can modify the .bash_profile themselves and get out of restricted mode. So you ll have to modify the permissions of .bash_profile itself, so that only root can change it.</p><p>Now the user cannot change .bash_profile and is only using a restricted shell with certain whitelisted commands. There is nooooo way he/she can break it. Right ? ….. Nooooooooo! Not, if you grant vi access. Apparently, in vi you can execute shell commands. :!UNIX_COMMAND can do wonders :) So ensure, you dont whitelist vi , instead maybe grant access to nano which is another simple file editor, not as powerful as vi though.</p><p>After doing all this, so far I havent been able to break the restricted shell given to user. I ‘ll be more than happy to know, if you know any other way break this setup. I ll add more, if I find something.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae86eabbe699" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Pet Peeves]]></title>
            <link>https://medium.com/@rahulram/python-pet-peeves-2d9505bfe5a9?source=rss-6e09f54d5e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d9505bfe5a9</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Ram]]></dc:creator>
            <pubDate>Tue, 18 Apr 2017 04:58:22 GMT</pubDate>
            <atom:updated>2017-04-18T04:58:22.498Z</atom:updated>
            <content:encoded><![CDATA[<p>I have decided to blog about various python code snippets, I see online and elsewhere.</p><h4>1. try/except blocks.</h4><pre>try:<br> major = version.rsplit(“.”)[0]<br>except IndexError:<br> major = “0”</pre><pre># The minor version <br> try:<br>   minor = version.rsplit(“.”)[1]<br> except IndexError:<br>   minor = “0”</pre><pre>#The release version <br> try:<br>   release = version.rsplit(“.”)[2]<br> except IndexError:<br>   release = “0”</pre><pre>#The patch version <br> try:<br>   patch = version.rsplit(“.”)[3]<br> except IndexError:<br>   patch = “0”</pre><p>Basically a total abuse of try/except blocks. It ll miserably fail for strings “a.b.c.” without raising index errors. I am not a huge fan of try/except blocks unless you really really really need it. Of course, you cannot cover all the cases and surrounding yourself with the bastion of try/except makes me feel comfortable. But more often, forcing your mind to not use one, helps me come with better code.</p><p>One of the ways, I was thinking was to get a list of size 4 which should default to “0” if no value exist. No matter what size is version string. I should be able to extract only 4 values based on the split and get the associated version numbers. I finally came up with the following,</p><pre>version_list = map(lambda x,y: x if x and y!= None else “0”, version.split(“.”)[:4],xrange(4))</pre><p>I am basically apply the lambda function on 2 lists. The xrange function ensures that, I process atleast 4 indices. so if version = 5.6. (mind the extra . in the end :) I ll still have version_list = [&quot;5”,&quot;6&quot;,&quot;0&quot;,&quot;0&quot;]</p><p>This way, I totally prevent using the try/except block and code is much leaner. Ofcourse, there are other alternatives. I ll keep adding as and when I get time to add more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d9505bfe5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I decided to explicitly version APIs]]></title>
            <link>https://medium.com/@rahulram/why-i-decided-to-explicitly-version-apis-fbb764173a3a?source=rss-6e09f54d5e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb764173a3a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Rahul Ram]]></dc:creator>
            <pubDate>Mon, 11 Jan 2016 08:08:26 GMT</pubDate>
            <atom:updated>2016-01-11T08:10:06.864Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been working on streaming application for a while now. And one of the major issues that bothers me is <em>change</em>. Every now and then, there are minor changes to response data for the requested API or the associated model with the API calls have to be updated. It becomes a nightmare, if the code is not flexible enough to handle these with minimal changes. To make things worst, one needs to support different request for the same resource.</p><p>One of the effective ways to handle changes is to version your APIs. It enables me to handle different users with various requirements and at the same time, politely hints the users to update to a newer version of API, before it gets deprecated. There are ample amount of resources online and relentless debates on whats the right way of doing it. It finally comes down to the following methods</p><h4>Method 1</h4><p>Make the version part of your API Request Parameter</p><pre>endpoint = &#39;https://something.com/blah&#39;<br>request_parameters = &#39;Action=NeedData&amp;Version=1.0&#39;</pre><p>Its very comforting to know that, most of the AWS APIs have a similar format, where version is a part of request parameters. Arguably AWS has championed the API way.</p><h4>Method 2</h4><p>Mentioning versions in accepted headers.</p><pre>Accept: application/vnd.heroku+json; version=3&quot;</pre><p>Heroku APIs are in a similar format. In this case, version is a metadata type which needs to be always mentioned while content negotiation. Many of the REST purists (yeah thats a thing! :) I have talked to, kinda agree on this method. Since your end point is strictly not changing in anyway (you GET / POST request parameters will still be the same). Its just the format in which you need the data is negotiated in the Accept type.</p><h4>Method 3</h4><p>Explicitly mentioning version numbers in the API calls.</p><pre>http://something.com/api<strong>/v1.0</strong>/data/</pre><p>In this case, we are specifying the version are a part of URI resource. Its seems very explicit to the end users.</p><p>I just couldn&#39;t decide on which way to proceed, since all these methods seems legit in their own ways. From a REST perspective, if you read the original <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">dissertation</a> from the author Roy Fielding, embedding the version in the API will disrupt the concept of REST interface to begin with. Since, the endpoints need to be static and users could easily permalink these API calls.</p><p>Being an avid python programmer, whenever I face such a dilemma, I prefer to follow <strong>Zen of Python, which states</strong></p><pre>Beautiful is better than ugly.<br><strong>Explicit is better than implicit</strong>.<br>Simple is better than complex.<br>Complex is better than complicated.<br><strong>Flat is better than nested</strong>.<br>Sparse is better than dense.<br><strong>Readability counts</strong>.<br>Special cases aren&#39;t special enough to break the rules.<br><strong>Although practicality beats purity.<br>Errors should never pass silently</strong>.<br>Unless explicitly silenced.<br>In the face of ambiguity, refuse the temptation to guess.<br>There should be one and preferably only one obvious way to do it.<br>Although that way may not be obvious at first unless you&#39;re Dutch.<br>Now is better than never.<br>Although never is often better than *right* now.<br>If the implementation is hard to explain, it&#39;s a bad idea.<br>If the implementation is easy to explain, it may be a good idea.<br>Namespaces are one honking great idea -- let&#39;s do more of those!</pre><p>I realized, in my scenario</p><ol><li>My application is not written from scratch and has some amount of legacy code, which I don&#39;t have time to mess with.</li><li>The APIs I am concerned with, are more of an interface for pushing different kinds of data into a stream. So more and different types of POST request than GET. Also, most (not all) of the end users will consume the API using different client programs.</li><li>I cannot support backwards compatibility forever, so APIs will have to be deprecated at some point in time. Thus, I need to be very explicit about which version of API will soon be deprecated, without having to make user read the documentation. Because, we all know, that`s not happening until all hell breaks lose.</li></ol><p>Keeping the above things in mind, Method 1 in my case dint make much of a sense since, request parameter according to me should be about the resource end points. Sending version numbers with it, dint seem that elegant. I would any day choose Method 2 over Method 1. It makes more sense to specify the type of response the use is expecting from Accept header. Anyways, the user needs to specify the format of the data in response. So why not version as well ?</p><p>But when it comes to readability and practicality, it is very explicit and easier as a dev for me to mention version numbers as a part of URI itself. And here`s why ?</p><ol><li>It becomes super easy for me to keep track of how many users and how frequently a given version of API is being used. (I just analyze the logs for HTTP request). I know, you could also achieve the same in other methods, but that may need some work depending on which framework you are using.</li><li>From a dev perspective, its lot easier for me to map URI routes to methods. Instead of writing one complex function to to check different parameters. I get to modularize code into different functions. Some may argue that, what if you have too many mappings ? Well, since I don&#39;t plan to have backward compatibility forever, heck I don&#39;t want to support even more than 3 versions. Its not going to be a bigger deal.</li><li>Method 3 makes the URI request more <strong><em>explicit</em></strong> (user knows which version of API is being called) , more <strong><em>readable</em></strong> (the version is a part of URI request, unlike Method 1 ,2 where the URI calls are still valid without versions)</li></ol><h4>So how do I deprecate the older version APIs ?</h4><p>Depending on the timeline. The first step would be to send warnings in the header as a response to users, that the API will soon be deprecated. According to <a href="https://tools.ietf.org/html/rfc7234#section-5.5">IETF</a>, we could send</p><pre>Warning: 2xx the api &lt;version&gt; will be deprecated by mm-dd-yyyy </pre><p>This would ideally give sufficient time for the users to switch to newer version of APIs.</p><p>Once we have crossed the deadline, we could use status code 410 as a response. Thanks to HTTP Status code <a href="https://tools.ietf.org/html/rfc2616#section-10.4.11">410</a> which stands for “Gone” . According to IETF 410 status code means,</p><blockquote>The requested resource is no longer available at the server and no<br>forwarding address is known. This condition is expected to be<br>considered permanent.</blockquote><h4>So whats the take away ?</h4><p>I have walked through different methods to version APIs. Although, method 3 seemed like a better fit for me. I am not rooting against the other methods. Each web application is unique and you ll probably have to check which method best fits your case. There is no silver bullet!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb764173a3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Orphaned Process stuck between Django and Supervisor]]></title>
            <link>https://medium.com/@rahulram/an-orphaned-process-stuck-between-django-and-supervisor-58c98ea4be7d?source=rss-6e09f54d5e3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/58c98ea4be7d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[supervisor]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Rahul Ram]]></dc:creator>
            <pubDate>Fri, 04 Dec 2015 02:33:16 GMT</pubDate>
            <atom:updated>2015-12-13T03:46:25.597Z</atom:updated>
            <content:encoded><![CDATA[<p>A very interesting thing happened today. One of my co worker happened to update a setting in Django and restarted the server from supervisorctl. The next thing I know is the process seems to be running by the web server is not loading all the contents of the page. Basically something is terribly wrong with Django at the moment.</p><p>On checking the error logs something strange was going on .</p><pre>[03/Dec/2015 17:19:23] “GET / HTTP/1.1” 200 5204<br>[03/Dec/2015 17:22:22] “GET / HTTP/1.1” 200 5201<br>Traceback (most recent call last):<br> File “/usr/lib/python2.7/wsgiref/handlers.py”, line 86, in run<br> self.finish_response()<br> File “/usr/lib/python2.7/wsgiref/handlers.py”, line 128, in finish_response<br> self.write(data)<br> File “/usr/lib/python2.7/wsgiref/handlers.py”, line 217, in write<br> self._write(data)<br> File “/usr/lib/python2.7/socket.py”, line 324, in write<br> self.flush()<br> File “/usr/lib/python2.7/socket.py”, line 303, in flush<br> self._sock.sendall(view[write_offset:write_offset+buffer_size])<br>error: [Errno 104] Connection reset by peer<br>[03/Dec/2015 17:22:22] “GET / HTTP/1.1” 500 59<br>- Broken pipe from (‘137.226.113.7’, 39937)<br>Error: That port is already in use.<br>Error: That port is already in use.</pre><p>There are two issues with it</p><ol><li>Seems like another process (orphaned) process is already running and connected to the port.</li><li>What the hell is that IP address trying to do ?</li></ol><p>It seems like Django already tried to reload the changes mentioned in the setting, which makes sense in the dev env. But not in prod :) (well ideally code should not be changed directly in prod.. but I ll talk about that later) .</p><p><strong>So how do we make supervisor and Django play nice ?</strong></p><p>Firstly, in the supervisor conf, we need to make sure, if supervisor for any reason needs to restart the process , it needs to kill the entire process group and not just individual process. By default ‘<em>stopasagroup</em>’ is set to false. So, you have to specifically enable it.</p><pre>[program:api_server]<br>stopasgroup=true</pre><p>Secondly, I strongly suggest in prod environments have Django run the process with ‘<em>noreload’ </em>option. This would ensure, Django doesnt reload itself without your knowledge. I updated the supervisor config file and restarted the process. It worked like a charm. Hopefully, that should solve the problem.</p><p>Now the second issue I saw in the log file was troubling me.</p><pre>- Broken pipe from (‘137.226.113.7’, 39937)</pre><p>What is the IP address? And what exactly is the process in that server trying to do. Turns out the network researchers from RWTH Aachen University are trying to connect to common public ports for research purposes. I am not a big fan of unknown IPs trying to mess with the web servers. But it seems benign (or may be I am naive..) either ways, I ll need to update the firewall configs.</p><p>This has definitely rekindled my interest on anomaly detections. I wonder how can I specify alerts for such anomalies. A firewall setting will totally block this activity. But I intend to detect such anomalies. Hmm … Something to think about . . . :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58c98ea4be7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>