<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tech Scribblings &#187; python</title>
	<atom:link href="http://tech.pedersen-live.com/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://tech.pedersen-live.com</link>
	<description></description>
	<lastBuildDate>Mon, 20 Dec 2010 17:11:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Trusting All Certificates In Jython</title>
		<link>http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/</link>
		<comments>http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/#comments</comments>
		<pubDate>Thu, 07 Oct 2010 20:30:47 +0000</pubDate>
		<dc:creator>Brandon</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[certificates]]></category>
		<category><![CDATA[jython]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[ssl]]></category>

		<guid isPermaLink="false">http://tech.pedersen-live.com/?p=69</guid>
		<description><![CDATA[I had a little application I was writing to check some information on a VMware vSphere server. I was sending SSL HTTP requests to the server to get data. Everything was working fine under python. I had one function that needs to use Jython (which is fine because I am running everything under Jython most [...]]]></description>
			<content:encoded><![CDATA[<p>I had a little application I was writing to check some information on a VMware vSphere server. I was sending SSL HTTP requests to the server to get data. Everything was working fine under python. I had one function that needs to use Jython (which is fine because I am running everything under Jython most of the time anyway, Python is just faster to start up for testing). However, when I ran it in Jython I was getting socket.sslerror SSL handshake exceptions. This is known behavior in Jython because by default Java will automatically check the validity of certificates while Python just disregards the SSL certificates.</p>
<p>There are a couple of ways to get around this and they are documented here <a href="http://wiki.python.org/jython/NewSocketModule#SSLSupport">http://wiki.python.org/jython/NewSocketModule#SSLSupport</a>. However, I didn&#8217;t like any of those approaches.</p>
<p>The first option requires messing with your certificate store in the JVM which means all Java processes doing anything will have your certificate added. This may or may not be what you want, but if you go to another machine or use a different JVM you will lose the ability to connect to your SSL host again.</p>
<p>Option 2, creating your own Security Provider looked a little more appealing because I don&#8217;t have to worry about importing each certificate and could enable this at runtime. However, it has the drawback of having to be compiled outside of Jython, and has to be put on the class path. Again, this makes it a little less portable (but not too bad). It also has the affect of trusting all certificates for every single SSL connection made, which is good because it matches up to what Python does but what if you want to only trust invalid certificates in certain parts of your code?</p>
<p>I started digging and came up with a way that would let me trust all certificates, be written completely in Jython, and have the ability to dynamically switch between trusting all certificates or not.</p>

<div class="wp_syntax"><div class="code"><pre class="python"><span class="co1"># Check if running in Jython</span>
<span class="kw1">if</span> <span class="st0">'java'</span> <span class="kw1">in</span> <span class="kw3">sys</span>.<span class="kw3">platform</span>:
    <span class="kw1">from</span> javax.<span class="me1">net</span>.<span class="me1">ssl</span> <span class="kw1">import</span> TrustManager, X509TrustManager
    <span class="kw1">from</span> jarray <span class="kw1">import</span> <span class="kw3">array</span>
    <span class="kw1">from</span> javax.<span class="me1">net</span>.<span class="me1">ssl</span> <span class="kw1">import</span> SSLContext
    <span class="kw1">class</span> TrustAllX509TrustManager<span class="br0">&#40;</span>X509TrustManager<span class="br0">&#41;</span>:
        <span class="st0">''</span><span class="st0">'Define a custom TrustManager which will blindly accept all certificates'</span><span class="st0">''</span>
&nbsp;
            <span class="kw1">def</span> checkClientTrusted<span class="br0">&#40;</span><span class="kw2">self</span>, chain, auth<span class="br0">&#41;</span>:
                <span class="kw1">pass</span>
&nbsp;
            <span class="kw1">def</span> checkServerTrusted<span class="br0">&#40;</span><span class="kw2">self</span>, chain, auth<span class="br0">&#41;</span>:
                <span class="kw1">pass</span>
&nbsp;
            <span class="kw1">def</span> getAcceptedIssuers<span class="br0">&#40;</span><span class="kw2">self</span><span class="br0">&#41;</span>:
                <span class="kw1">return</span> <span class="kw2">None</span>
    <span class="co1"># Create a static reference to an SSLContext which will use</span>
    <span class="co1"># our custom TrustManager</span>
    trust_managers = <span class="kw3">array</span><span class="br0">&#40;</span><span class="br0">&#91;</span>TrustAllX509TrustManager<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#93;</span>, TrustManager<span class="br0">&#41;</span>
    TRUST_ALL_CONTEXT = SSLContext.<span class="me1">getInstance</span><span class="br0">&#40;</span><span class="st0">&quot;SSL&quot;</span><span class="br0">&#41;</span>
    TRUST_ALL_CONTEXT.<span class="me1">init</span><span class="br0">&#40;</span><span class="kw2">None</span>, trust_managers, <span class="kw2">None</span><span class="br0">&#41;</span>
    <span class="co1"># Keep a static reference to the JVM's default SSLContext for restoring</span>
    <span class="co1"># at a later time</span>
    DEFAULT_CONTEXT = SSLContext.<span class="me1">getDefault</span><span class="br0">&#40;</span><span class="br0">&#41;</span>
&nbsp;
<span class="kw1">def</span> trust_all_certificates<span class="br0">&#40;</span>f<span class="br0">&#41;</span>:
    <span class="st0">''</span><span class="st0">'Decorator function that will make it so the context of the decorated method
    will run with our TrustManager that accepts all certificates'</span><span class="st0">''</span>
    <span class="kw1">def</span> wrapped<span class="br0">&#40;</span><span class="sy0">*</span>args, <span class="sy0">**</span>kwargs<span class="br0">&#41;</span>:
        <span class="co1"># Only do this if running under Jython</span>
        <span class="kw1">if</span> <span class="st0">'java'</span> <span class="kw1">in</span> <span class="kw3">sys</span>.<span class="kw3">platform</span>:
            <span class="kw1">from</span> javax.<span class="me1">net</span>.<span class="me1">ssl</span> <span class="kw1">import</span> SSLContext
            SSLContext.<span class="me1">setDefault</span><span class="br0">&#40;</span>TRUST_ALL_CONTEXT<span class="br0">&#41;</span>
            <span class="kw1">try</span>:
                res = f<span class="br0">&#40;</span><span class="sy0">*</span>args, <span class="sy0">**</span>kwargs<span class="br0">&#41;</span>
                <span class="kw1">return</span> res
            <span class="kw1">finally</span>:
                SSLContext.<span class="me1">setDefault</span><span class="br0">&#40;</span>DEFAULT_CONTEXT<span class="br0">&#41;</span>
        <span class="kw1">else</span>:
            <span class="kw1">return</span> f<span class="br0">&#40;</span><span class="sy0">*</span>args, <span class="sy0">**</span>kwargs<span class="br0">&#41;</span>
    <span class="kw1">return</span> wrapped</pre></div></div>

<p>Thats it. Now I can do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="python">@trust_all_certificates
<span class="kw1">def</span> connect_to_untrusted_host<span class="br0">&#40;</span>host<span class="br0">&#41;</span>:
        conn = <span class="kw3">httplib</span>.<span class="me1">HTTPSConnection</span><span class="br0">&#40;</span>host<span class="br0">&#41;</span>
        conn.<span class="me1">request</span><span class="br0">&#40;</span><span class="st0">'GET'</span>, <span class="st0">'/index.html'</span><span class="br0">&#41;</span>
        response = conn.<span class="me1">getresponse</span><span class="br0">&#40;</span><span class="br0">&#41;</span></pre></div></div>

<p>And the connection will succeed. If I have another method that is not decorated then it will automatically verify the certificates validity.</p>
<p>Note that this decorator is not thread safe. Setting the SSLContext default is a global operation, so if another thread is running it could reset the SSLContext to the default before another method tries to make an SSL connection.</p>
<p>You can also use this without the decorator function. Just use the code prior to the decorator and set the SSLContext default wherever you need to.</p>
<p>If you happen to also need to verify the hostname of a certificate, which is the case if you use an HttpsURLConnection, then you will also need to create a HostnameVerifier. You can do this as follows:</p>
<p> </p>

<div class="wp_syntax"><div class="code"><pre class="python"><span class="kw1">from</span> javax.<span class="me1">net</span>.<span class="me1">ssl</span> <span class="kw1">import</span> HostnameVerifier, HttpsURLConnection
<span class="kw1">class</span> AllHostsVerifier<span class="br0">&#40;</span>HostnameVerifier<span class="br0">&#41;</span>:
    <span class="kw1">def</span> verify<span class="br0">&#40;</span><span class="kw2">self</span>, urlHostname, session<span class="br0">&#41;</span>:
        <span class="kw1">return</span> <span class="kw2">True</span>
HttpsURLConnection.<span class="me1">setDefaultHostnameVerifier</span><span class="br0">&#40;</span>AllHostsVerifier<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div>

<p> </p>
<p>Hope that helps. It&#8217;s nice to have a pure Jython implementation of this and have it be transportable.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Killing a thread in Python</title>
		<link>http://tech.pedersen-live.com/2009/01/killing-a-thread-in-python/</link>
		<comments>http://tech.pedersen-live.com/2009/01/killing-a-thread-in-python/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 16:45:43 +0000</pubDate>
		<dc:creator>Brandon</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://tech.pedersen-live.com/?p=17</guid>
		<description><![CDATA[I have been searching for quite a while for information on how to kill a thread in Python and I finally found a great solution. I was just about to implement my own way of doing it but it is not as clean as this way (although killing threads is not clean in the first [...]]]></description>
			<content:encoded><![CDATA[<p>I have been searching for quite a while for information on how to kill a thread in Python and I finally found a great solution. I was just about to implement my own way of doing it but it is not as clean as this way (although killing threads is not clean in the first place).</p>
<p>My thought was to use threading.settrace() and set my own trace function for every thread that is started. That way every thread will have to pass through the trace function in oder to continue executing and it doesn&#8217;t matter where in the code it is at or going. In my trace function I was going to add an Event that it would wait on if I want to pause execution of the thread, or check something to make it through an execption to exit out of the thread.</p>
<p>I was in the process of searching for a way to find out if a thread died because of an Exception when I ran across a post here: <a href="http://www.dlevel.com/blogs/alex/20" target="_blank">http://www.dlevel.com/blogs/alex/20</a></p>
<p>What they have done is added a terminate() method to the Thread class in the threading library. This will throw a SystemExit exception and quitely terminate the thread. Just take the code and paste it into a new module and use that Thread class as opposed to the threading.Thread class.</p>
<p>I agree with what he says about using this. Obviously it is not very safe to do this but in some cases you really need a way to terminate a thread and if you are careful it can work out ok.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.pedersen-live.com/2009/01/killing-a-thread-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Interesting Python Static Attributes</title>
		<link>http://tech.pedersen-live.com/2008/12/interesting-python-static-attributes/</link>
		<comments>http://tech.pedersen-live.com/2008/12/interesting-python-static-attributes/#comments</comments>
		<pubDate>Wed, 31 Dec 2008 01:19:42 +0000</pubDate>
		<dc:creator>Brandon</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://tech.pedersen-live.com/?p=14</guid>
		<description><![CDATA[So I was playing around with some code in Python today and was  curious about static members of a class (I guess that is what you would call it). I wanted to know if I set an attribute at the class level and change it, would all the instances see that change or if each [...]]]></description>
			<content:encoded><![CDATA[<p>So I was playing around with some code in Python today and was  curious about static members of a class (I guess that is what you would call it). I wanted to know if I set an attribute at the class level and change it, would all the instances see that change or if each instance is separate.</p>
<p>Here is some code I played with:</p>
<p><code><br />
&gt;&gt;&gt; class T:<br />
...     build_location = None<br />
...     def get_location(self):<br />
...               return self.build_location<br />
...<br />
&gt;&gt;&gt; t = T()<br />
&gt;&gt;&gt; print t.get_location()<br />
None<br />
&gt;&gt;&gt; T.build_location = "hello"<br />
&gt;&gt;&gt; print t.get_location()<br />
hello<br />
&gt;&gt;&gt; t.build_location = "there"<br />
&gt;&gt;&gt; print t.get_location()<br />
there<br />
&gt;&gt;&gt; print T.build_location<br />
hello<br />
&gt;&gt;&gt; T.build_location = "hello"<br />
&gt;&gt;&gt; print t.get_location()<br />
there<br />
&gt;&gt;&gt;</code></p>
<p>So, what I did was set an attribute on the class level that everyone can see without an instance of the class. When I create an instance it can see that attribute just like I can from just doing T.build_location. When I change the static variable then the instance sees that change as well (which is what I was hoping for).</p>
<p>Now, the interesting part is that if I use an instance of the class to change the variable, that variable becomes local to that instance as you can see above when I printed the class&#8217;s T.build_location. Now I tried to set the class level attribute back to &#8220;hello&#8221; and that works but now it does not change what the instance sees!</p>
<p>This is not any earth shattering news but I thought it was interesting when I saw it.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.pedersen-live.com/2008/12/interesting-python-static-attributes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

