<?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>Jeff Mandel &#8211; Undocumented Matlab</title>
	<atom:link href="https://undocumentedmatlab.com/articles/tag/jeff-mandel/feed" rel="self" type="application/rss+xml" />
	<link>https://undocumentedmatlab.com</link>
	<description>Professional Matlab consulting, development and training</description>
	<lastBuildDate>Fri, 18 Mar 2016 10:39:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>Secure SSL connection between Matlab and PostgreSQL</title>
		<link>https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=secure-ssl-connection-between-matlab-and-postgresql</link>
					<comments>https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql#respond</comments>
		
		<dc:creator><![CDATA[Yair Altman]]></dc:creator>
		<pubDate>Fri, 18 Mar 2016 10:39:49 +0000</pubDate>
				<category><![CDATA[Guest bloggers]]></category>
		<category><![CDATA[High risk of breaking in future versions]]></category>
		<category><![CDATA[Undocumented feature]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Jeff Mandel]]></category>
		<category><![CDATA[Pure Matlab]]></category>
		<guid isPermaLink="false">http://undocumentedmatlab.com/?p=6318</guid>

					<description><![CDATA[<p>It is tricky, but quite possible, to use SSL to connect Matlab to a PostgreSQL database. </p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql">Secure SSL connection between Matlab and PostgreSQL</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab" rel="bookmark" title="Using SQLite in Matlab">Using SQLite in Matlab </a> <small>SQLite databases can be accessed in a variety of different ways in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver" rel="bookmark" title="Fixing Matlab&#039;s actxserver">Fixing Matlab&#039;s actxserver </a> <small>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
</ol>
</div>
]]></description>
										<content:encoded><![CDATA[<p><i>I&#8217;d like to introduce guest blogger <a href="http://www.med.upenn.edu/apps/faculty/index.php/g275/p40141" rel="nofollow" target="_blank">Jeff Mandel</a> of the Perelman School of Medicine at the University of Pennsylvania. Today Jeff will discuss a how-to guide for setting up an SSL connection between Matlab and a PostgreSQL database. While this specific topic may be of interest to only a few readers, it involves hard-to-trace problems that are not well documented anywhere. The techniques discussed below may also be applicable, with necessary modifications, to other SSL targets and may thus be of use to a wider group of Matlab users.</i><br />
<span class="alignright"><a href="http://postgresql.org" target="_blank"><img decoding="async" src="https://undocumentedmatlab.com/images/PostgreSQL.gif" alt="PostgreSQL database" title="PostgreSQL database" width="200" height="200" /></a></span><br />
I&#8217;m developing software for pharmacokinetic control, and needed secure access to a central database from users at remote sites. The client software is written in Matlab, and while I have targeted MacOS, this could be adapted to Windows fairly easily. Hopefully, this will save someone the week it took me to figure all this out.<br />
My environment:</p>
<ul>
<li>PostgreSQL 9.4 installed on the server (Windows 7 PC, but Linux would be equally good)</li>
<li>DynDNS CNAME pointing at the server (diseserver.mydomain.org)</li>
<li>CACert.org registration for domain mydomain.org</li>
<li>Matlab 2015b running on El Capitan</li>
</ul>
<p>Here are the neccesary steps:<br />
<span id="more-6318"></span></p>
<ol>
<li>First, we need a certificate for the server. We can generate this with <a href="http://www.openssl.org" rel="nofollow" target="_blank">OpenSSL</a>:
<pre lang="bash">$openssl req -out diseserver.csr -new -newkey rsa:2048 -nodes -keyout diseserver.key</pre>
<p>Specify any information you want on the key, but ensure <code>CN=diseserver.mydomain.org</code>.</li>
<li>Paste the resulting <i>diseserver.csr</i> file into a new key request at <a href="http://cacert.org" rel="nofollow" target="_blank">CACert.org</a>. Save the resulting certificate as <i>diseserver.crt</i> on your machine.</li>
<li>While still at CACert.org, grab the Class 1 root certificate and save it as <i>root.crt</i>.</li>
<li>Put the files <i>diseserver.key</i>, <i>diseserver.crt</i>, and <i>root.crt</i> in the PostgreSQL data directory.</li>
<li>Edit your <i>postgresql.conf</i> file:
<pre lang="bash">
ssl = on
ssl_cert_file = 'diseserver.crt'  # (change requires restart)
ssl_key_file  = 'diseserver.key'  # (change requires restart)
ssl_ca_file   = 'root.crt'        # (change requires restart)
</pre>
</li>
<li>Restart the PostgreSQL server. The server will now permit SSL connections, a necessary pre-condition for certificate authentication.</li>
<li>We now add 2 lines to <i>pg_hba.conf</i>:
<pre lang="text">
hostnossl  all    all   0.0.0.0/0   reject
hostssl	 mytable  all   0.0.0.0/0   cert map=ssl clientcert=1
</pre>
<p>The first line causes all non-SSL connections to be rejected. The second allows certificate logins for mytable using the map ssl that is defined in <i>pg_ident.conf</i>:</p>
<pre lang="matlab">ssl  /^(.*).mydomain\.org$ \1</pre>
<p>this line extracts the username prefix from <code>CN=username.mydomain.org</code>.</li>
<li>Now we need to generate client certificates. PostgreSQL expects these to be in <i>~/.postgresql</i> (Windows <i>%appdata%\postgresql\</i>):
<pre lang="bash">
$mkdir ~/.postgresql
$cd ~/.postgresql
$openssl req -out postgresql.csr -new -newkey rsa:2048 -nodes -keyout postgresql.key
</pre>
<p>for this key, make <code>CN=username.mydomain.org</code>.</li>
<li>Again, paste the resulting <i>postgresql.csr</i> file into CACert.org, saving the certificate as <i>postgresql.crt</i>.</li>
<li>Test this:
<pre lang="bash">$psql "sslmode=verify-full host=diseserver.mydomain.org dbname=effect user=username"</pre>
<p>The server should respond:</p>
<pre lang="text">
psql (9.4.6, server 9.4.1)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
</pre>
</li>
<li>Next we need to convert our key into pkcs8 format so that Java can read it:
<pre lang="bash">$openssl pkcs8 -topk8 -inform PEM -outform DER -in postgresql.key -out postgresql.pk8 -nocrypt</pre>
</li>
<li>Next, ensure that we have the correct version of the JDBC driver (Java-to-database connector). From the Mac command line:
<pre lang="bash">
$java -version
java version "1.8.0_05"
</pre>
<p>and in Matlab:</p>
<pre lang="matlab">
>> version -java
ans =
Java 1.7.0_75-b13 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
</pre>
<p>This shows that although we have Java 8 installed on El Capitan (at the OS level), Matlab uses a private Java 7 version. So we need the correct version of the jdbc on our <a href="/articles/static-java-classpath-hacks" target="_blank">static java classpath that is used by Matlab</a>:</p>
<pre lang="text">~/Matlab/postgresql-9.4.1208.jre7.jar</pre>
</li>
<li>The next part is very poorly documented in both the MathWorks and the PostgreSQL documentation, but I found it in Russel Gray&#8217;s <a href="https://basildoncoder.com/blog/postgresql-jdbc-client-certificates.html" rel="nofollow" target="_blank"><i>Basildon Coder</i></a> blog: We need to use the jdbc postgresql driver to check the client certificate. To do this, we need a custom SSLSocketFactory &#8211; LibPQFactory. This will grab our certificate and key from <i>~/.postgresql</i> and present them to the server. The url is (note the trailing &#038;):
<pre lang="text">jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&</pre>
</li>
<li>Next we need the username. Rather than hard-coding this in the source code, we get the system username:
<pre lang="matlab">>> username = java.lang.System.getProperty('user.name');</pre>
</li>
<li>Bundle this all up in a Matlab function, stripping the trailing CR from the username:
<pre lang="matlab">
function dbtest
   driver = 'org.postgresql.Driver';
   [~,username] = system('whoami');
   url = 'jdbc:postgresql://diseserver.mydomain.org/mytable?ssl=true&sslfactory=org.postgresql.ssl.jdbc4.LibPQFactory&sslmode=verify-full&';
   myconn = database('mytable', username, '', driver, url);
   if ~isempty(myconn.Message)
      fprintf(2,'%s\n', myconn.Message);
   else
      fprintf(1, 'Connected!\n');
   end
end
</pre>
</li>
</ol>
<p>Now we can connect from the Matlab command line or a Matlab program.<br />
What if we&#8217;re deployed? We also need to add the contents of our <i>.postgresql</i> directory, plus the jdbc jar file to our deployed app:</p>
<pre lang="matlab">>> mcc -m dbtest.m -a ~/.postgresql -a ~/Matlab/postgresql-9.4.1208.jre7.jar</pre>
<p>Let&#8217;s test the compiled program from the OS command line:</p>
<pre lang="bash">
$./run_dbtest.sh /Applications/Matlab/Matlab_Runtime/v90
Connected!
</pre>
<p>Note that the key and certificates are part of the encrypted bundle produced by Matlab&#8217;s <i><b>mcc</b></i> compiler.<br />
I hope this helps someone!<br />
<i><u>Yair&#8217;s note</u>: the Matlab code above uses Matlab&#8217;s Database Toolbox (specifically, the <b>database</b> function) to connect to the database. In future posts I plan to show how we can connect Matlab directly to a database via JDBC. This topic is covered in detail in chapter 2 of my <a href="/books/matlab-java" rel="nofollow" target="_blank">Matlab-Java programming secrets book</a>.<br />
p.s. &#8211; this blog celebrates a 7-year anniversary tomorrow: I published my very first post here on March 19, 2009, showing <a href="/articles/changing-matlab-command-window-colors" target="_blank">how to change Matlab&#8217;s command-window colors</a> (a post that later led to the now-famous <a href="/articles/cprintf" target="_blank"><b>cprintf</b> utility</a>). It&#8217;s been a long and very interesting ride indeed, but I have no plans to retire anytime soon 🙂</i></p>
<p>The post <a rel="nofollow" href="https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql">Secure SSL connection between Matlab and PostgreSQL</a> appeared first on <a rel="nofollow" href="https://undocumentedmatlab.com">Undocumented Matlab</a>.</p>
<div class='yarpp-related-rss'>
<h3>Related posts:</h3><ol>
<li><a href="https://undocumentedmatlab.com/articles/speeding-up-matlab-jdbc-sql-queries" rel="bookmark" title="Speeding up Matlab-JDBC SQL queries">Speeding up Matlab-JDBC SQL queries </a> <small>Fetching SQL ResultSet data from JDBC into Matlab can be made significantly faster. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/using-sqlite-in-matlab" rel="bookmark" title="Using SQLite in Matlab">Using SQLite in Matlab </a> <small>SQLite databases can be accessed in a variety of different ways in Matlab. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/fixing-matlabs-actxserver" rel="bookmark" title="Fixing Matlab&#039;s actxserver">Fixing Matlab&#039;s actxserver </a> <small>Matlab's COM (ActiveX) server behavior can be fixed in a couple of useful manners. ...</small></li>
<li><a href="https://undocumentedmatlab.com/articles/matlab-compilation-quirks-take-2" rel="bookmark" title="Matlab compilation quirks &#8211; take 2">Matlab compilation quirks &#8211; take 2 </a> <small>A few hard-to-trace quirks with Matlab compiler outputs are explained. ...</small></li>
</ol>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://undocumentedmatlab.com/articles/secure-ssl-connection-between-matlab-and-postgresql/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
