<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Brain dump on software]]></title><description><![CDATA[Blogging all the weird stuff I've been through in software and what's not]]></description><link>http://blog.moatazthenervous.com/</link><generator>Ghost 0.6</generator><lastBuildDate>Mon, 23 Mar 2026 13:08:44 GMT</lastBuildDate><atom:link href="http://blog.moatazthenervous.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Create a key chain for Apple's VPN]]></title><description><![CDATA[<p>While trying to get a VPN connection pro grammatically up and running using swift (check my <a href="http://blog.moatazthenervous.com/create-a-vpn-connection-with-apple-swift/">VPN blog post</a>), I hit a couple of obstacles. One big obstacle was how to pass VPN password and shared key to <code>NEVPNProtocol</code> class. Passing plain strings didn't work. </p>

<p>It then turned out that</p>]]></description><link>http://blog.moatazthenervous.com/create-a-key-chain-for-apples-vpn/</link><guid isPermaLink="false">a43a470a-0658-4fa5-8a9b-bc18419d4fb1</guid><category><![CDATA[vpn]]></category><category><![CDATA[swift]]></category><category><![CDATA[keychain]]></category><dc:creator><![CDATA[Moataz Elmasry]]></dc:creator><pubDate>Wed, 15 Feb 2017 22:39:37 GMT</pubDate><content:encoded><![CDATA[<p>While trying to get a VPN connection pro grammatically up and running using swift (check my <a href="http://blog.moatazthenervous.com/create-a-vpn-connection-with-apple-swift/">VPN blog post</a>), I hit a couple of obstacles. One big obstacle was how to pass VPN password and shared key to <code>NEVPNProtocol</code> class. Passing plain strings didn't work. </p>

<p>It then turned out that I need to pass a reference to a key chain entry that I saved before. The problem was that Apple's key chains seem quite difficult to handle manually. Luckily there are a couple of swift and Objective-C libraries out there that handle Key Chains, the most famous one is <a href="https://github.com/kishikawakatsumi/KeychainAccess">KeychainAccess</a>. I thought all my problems were solved, but alas that was just the begining. I saved the password and passed a data reference to the <code>NEVPNIPSec</code> class but I couldn't establish the VPN connection. The error was that authentication failed. </p>

<p>Anyways after some search and retires, I could finally solve the problem using an Objective-C snippet I found online (sorry I lost the original URL). And here's the swift equivalent snippet.</p>

<pre><code>import Foundation

import UIKit  
import Security

// Identifiers
let serviceIdentifier = "MySerivice"  
let userAccount = "authenticatedUser"  
let accessGroup = "MySerivice"

// Arguments for the keychain queries
var kSecAttrAccessGroupSwift = NSString(format: kSecClass)

let kSecClassValue = kSecClass as CFString  
let kSecAttrAccountValue = kSecAttrAccount as CFString  
let kSecValueDataValue = kSecValueData as CFString  
let kSecClassGenericPasswordValue = kSecClassGenericPassword as CFString  
let kSecAttrServiceValue = kSecAttrService as CFString  
let kSecMatchLimitValue = kSecMatchLimit as CFString  
let kSecReturnDataValue = kSecReturnData as CFString  
let kSecMatchLimitOneValue = kSecMatchLimitOne as CFString  
let kSecAttrGenericValue = kSecAttrGeneric as CFString  
let kSecAttrAccessibleValue = kSecAttrAccessible as CFString

class KeychainService: NSObject {  
    func save(key:String, value:String) {
        let keyData: Data = key.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)!
        let valueData: Data = value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)!

        let keychainQuery = NSMutableDictionary();
        keychainQuery[kSecClassValue as! NSCopying] = kSecClassGenericPasswordValue
        keychainQuery[kSecAttrGenericValue as! NSCopying] = keyData
        keychainQuery[kSecAttrAccountValue as! NSCopying] = keyData
        keychainQuery[kSecAttrServiceValue as! NSCopying] = "VPN"
        keychainQuery[kSecAttrAccessibleValue as! NSCopying] = kSecAttrAccessibleAlwaysThisDeviceOnly
        keychainQuery[kSecValueData as! NSCopying] = valueData;
        // Delete any existing items
        SecItemDelete(keychainQuery as CFDictionary)
        SecItemAdd(keychainQuery as CFDictionary, nil)
    }

    func load(key: String)-&gt;Data {

        let keyData: Data = key.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)!
        let keychainQuery = NSMutableDictionary();
        keychainQuery[kSecClassValue as! NSCopying] = kSecClassGenericPasswordValue
        keychainQuery[kSecAttrGenericValue as! NSCopying] = keyData
        keychainQuery[kSecAttrAccountValue as! NSCopying] = keyData
        keychainQuery[kSecAttrServiceValue as! NSCopying] = "VPN"
        keychainQuery[kSecAttrAccessibleValue as! NSCopying] = kSecAttrAccessibleAlwaysThisDeviceOnly
        keychainQuery[kSecMatchLimit] = kSecMatchLimitOne
        keychainQuery[kSecReturnPersistentRef] = kCFBooleanTrue

        var result: AnyObject?
        let status = withUnsafeMutablePointer(to: &amp;result) { SecItemCopyMatching(keychainQuery, UnsafeMutablePointer($0)) }


        if status == errSecSuccess {
            if let data = result as! NSData? {
                if let value = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) {
                }
                return data as Data;
            }
        }
        return "".data(using: .utf8)!;
    }
}
</code></pre>

<p>Using this class, I was able to save password strings into the keychain and again pass them to <code>NEVPNProtocol</code> class as data references. </p>

<p>This code is quite similar to the KeychainAccess library, but it sets some more keys/attributes, that are currently not possible to set explicitly from outside, for example <code>kSecAttrServiceValue</code>.</p>]]></content:encoded></item><item><title><![CDATA[Create an IPSec VPN connection with swift]]></title><description><![CDATA[<p>We needed to pro grammatically start an <strong>IPSec VPN</strong> connection from an App we are working on. Luckily Apple is providing a nice set API for doing that without external library.</p>

<p>To create a VPN connection in iOS <strong>you do not need to obtain a network extension entitlement from apple</strong></p>]]></description><link>http://blog.moatazthenervous.com/create-a-vpn-connection-with-apple-swift/</link><guid isPermaLink="false">8381dbfa-3a53-4beb-990b-ec60f41a2f6f</guid><category><![CDATA[vpn]]></category><category><![CDATA[swift]]></category><category><![CDATA[IPSec]]></category><dc:creator><![CDATA[Moataz Elmasry]]></dc:creator><pubDate>Wed, 15 Feb 2017 22:13:11 GMT</pubDate><content:encoded><![CDATA[<p>We needed to pro grammatically start an <strong>IPSec VPN</strong> connection from an App we are working on. Luckily Apple is providing a nice set API for doing that without external library.</p>

<p>To create a VPN connection in iOS <strong>you do not need to obtain a network extension entitlement from apple</strong>.</p>

<h1 id="createavpn">Create a VPN</h1>

<pre><code class="language-swift">import NetworkExtension

class VPN {

let vpnManager = NEVPNManager.shared();

private var vpnLoadHandler: (Error?) -&gt; Void { return  
        { (error:Error?) in
            if ((error) != nil) {
                print("Could not load VPN Configurations")
                return;
            }
            let p = NEVPNProtocolIPSec()
            p.username = "SOME_USERNAME"
            p.serverAddress = "example.com"
            p.authenticationMethod = NEVPNIKEAuthenticationMethod.sharedSecret

            let kcs = KeychainService();
            kcs.save(key: "SHARED", value: "MY_SHARED_KEY")
            kcs.save(key: "VPN_PASSWORD", value: "MY_PASSWORD"
            p.sharedSecretReference = kcs.load(key: "SHARED")
            p.passwordReference = kcs.load(key: "VPN_PASSWORD)
            p.useExtendedAuthentication = true
            p.disconnectOnSleep = false
            self.vpnManager.protocolConfiguration = p
            self.vpnManager.localizedDescription = "Contensi"
            self.vpnManager.isEnabled = true
            self.vpnManager.saveToPreferences(completionHandler: self.vpnSaveHandler)
    } }

private var vpnSaveHandler: (Error?) -&gt; Void { return  
    { (error:Error?) in
        if (error != nil) {
            print("Could not save VPN Configurations")
            return
        } else {
            do {
                try self.vpnManager.connection.startVPNTunnel()
            } catch let error {
                print("Error starting VPN Connection \(error.localizedDescription)");
                }
            }
        }
        self.vpnlock = false
    }}

public func connectVPN() {  
        //For no known reason the process of saving/loading the VPN configurations fails.On the 2nd time it works
        do {
            try self.vpnManager.loadFromPreferences(completionHandler: self.vpnLoadHandler)
        } catch let error {
            print("Could not start VPN Connection: \(error.localizedDescription)" )
        }
    }

public func disconnectVPN() -&gt;Void {  
        vpnManager.connection.stopVPNTunnel()
}
}
</code></pre>

<p>The code does the following: <br>
* 
Load the preferences <br>
* 
Change the preferences to the desired values (username, password, URL etc..) <br>
* 
Save the preferences <br>
* 
Start the connection</p>

<p>I know that it is weird to load the preferences, and then save it, although we didn't have anything to load. But this is unfortunately how Apple decided that it should be done. If you apply your changes directly and saved to preferences <strong>before</strong> loading preferences, the save operation will fail. *sighs*</p>

<p>The password and the shared key have to be saved in a specific key chain. You can read more about <strong>saving/loading keychain entries for VPN</strong> in <a href="http://blog.moatazthenervous.com/create-a-key-chain-for-apples-vpn/">this other blog post</a>. </p>

<p>Also note that the <code>loadFromPreferences</code> and the <code>saveToPreferences</code> callbacks are <strong>asynchronous</strong></p>

<p>One more thing I learnt while figuring out this API is that the call <code>vpnManager.connection.startVPNTunnel()</code> succeeds it does not mean the VPN connection has been established successfully, but it means that the process of establishing a VPN tunnel has been started successfully. Apparently Apple has been writing those APIs for lawyers. </p>

<p>Finally if you want to be notified when the VPN connection has been established successfully, or otherwise has been disconnected, you need to use the <code>NotificationCenter</code> class. I'll describe this in a separate post.</p>]]></content:encoded></item><item><title><![CDATA[How to debug SoftEtherVPN]]></title><description><![CDATA[<h2 id="1compileanddebugsoftether">1. Compile and Debug SoftEther</h2>

<p>In order to debug SoftEtherVPN I had to spend a considerable amount of time to get it running.</p>

<p>These set of libraries apply to <strong>Ubuntu 16.04</strong> </p>

<pre><code>sudo apt-get install -y cmake libncurses-dev libc-bin libc-dev-bin libc6 libc6-dbg libc6-dev libc6-pic  multiarch-support nscd libnss3-dev libreadline-dev libssl-dev
</code></pre>

<p>After</p>]]></description><link>http://blog.moatazthenervous.com/how-to-debug-softethervpn/</link><guid isPermaLink="false">f7ee8e28-2b0d-4cec-b01d-aace5e1a74b6</guid><category><![CDATA[vpn]]></category><category><![CDATA[SoftEtherVPN]]></category><category><![CDATA[C]]></category><category><![CDATA[eclipse]]></category><category><![CDATA[debugging]]></category><dc:creator><![CDATA[Moataz Elmasry]]></dc:creator><pubDate>Thu, 01 Sep 2016 13:37:25 GMT</pubDate><content:encoded><![CDATA[<h2 id="1compileanddebugsoftether">1. Compile and Debug SoftEther</h2>

<p>In order to debug SoftEtherVPN I had to spend a considerable amount of time to get it running.</p>

<p>These set of libraries apply to <strong>Ubuntu 16.04</strong> </p>

<pre><code>sudo apt-get install -y cmake libncurses-dev libc-bin libc-dev-bin libc6 libc6-dbg libc6-dev libc6-pic  multiarch-support nscd libnss3-dev libreadline-dev libssl-dev
</code></pre>

<p>After that check out and compile the project</p>

<pre><code>git clone https://github.com/SoftEtherVPN/SoftEtherVPN
cd SoftEtherVPN
./configure
make clean
make DEBUG=YES
</code></pre>

<p>Then run the the vpn server as a root</p>

<pre><code>./bin/vpnserver/vpnserver execsvc
</code></pre>

<ul>
<li>Now open eclipse CDT and import the project</li>
<li>Go Run -> Debug Configurations -> and create a new "C/C++ Attach to application" -> Then hit "Debug"</li>
<li>a Menu with the processes running on your system will open, choose the vpnserver</li>
<li>Note: There should be two vpnserver processes running. Choose the one with "one" core next to its name</li>
</ul>

<p>That's it. Now you should be able to debug SoftEther</p>

<h2 id="onlycompilesoftether">Only Compile SoftEther</h2>

<p>Also done for Ubuntu, you need to install the following libraries:</p>

<pre><code>sudo apt-get install -y build-essential libreadline-dev libssl-dev 
</code></pre>]]></content:encoded></item><item><title><![CDATA[Install freeradius on Ubuntu 14.04 from source]]></title><description><![CDATA[<p>So I needed to install the latest version of freeradius on my Ubuntu 14.04.</p>

<p>The newest version at the time of writing this post is v3.1. Ubuntu has up to version 2.1 of freeradius.</p>

<p>First you need to install some libs needed to compile freeradius code</p>

<pre><code class="language-bash">sudo</code></pre>]]></description><link>http://blog.moatazthenervous.com/install-freeradius-on-ubuntu-14-04/</link><guid isPermaLink="false">9a356e98-e41f-4848-8172-88ad26b39d8c</guid><category><![CDATA[freeradius]]></category><category><![CDATA[ubuntu]]></category><dc:creator><![CDATA[Moataz Elmasry]]></dc:creator><pubDate>Sun, 09 Aug 2015 20:43:09 GMT</pubDate><content:encoded><![CDATA[<p>So I needed to install the latest version of freeradius on my Ubuntu 14.04.</p>

<p>The newest version at the time of writing this post is v3.1. Ubuntu has up to version 2.1 of freeradius.</p>

<p>First you need to install some libs needed to compile freeradius code</p>

<pre><code class="language-bash">sudo apt-get install build-essential libmysqlclient-dev libperl-dev libssl-dev  
git clone https://github.com/FreeRADIUS/freeradius-server.git  
cd freeradius server  
./configure
make  
make install  
</code></pre>]]></content:encoded></item><item><title><![CDATA[Configure freeradius with mysql]]></title><description><![CDATA[<h2 id="etcfreeradiusradiusdconf">/etc/freeradius/radiusd.conf</h2>

<p>edit the file <mark>/etc/freeradius/radiusd.conf</mark></p>

<ol>
<li>Find the next two lines and uncomment them. After uncommenting them, they should look like the following:</li>
</ol>

<pre><code class="language-sh">$INCLUDE sql.conf 
$INCLUDE sql/mysql/counter.conf 
</code></pre>

<ol>
<li>Find the snippet <u>instantiate {...} around line 710 and add the following</u> inside it:  </li>
</ol>

<pre><code>noresetcounter</code></pre>]]></description><link>http://blog.moatazthenervous.com/configure-freeradius-with-mysql/</link><guid isPermaLink="false">15b0b9ef-ea31-4a4e-8e7c-a19a26f8c353</guid><category><![CDATA[mysql]]></category><category><![CDATA[freeradius]]></category><dc:creator><![CDATA[Moataz Elmasry]]></dc:creator><pubDate>Sun, 21 Jun 2015 19:15:56 GMT</pubDate><content:encoded><![CDATA[<h2 id="etcfreeradiusradiusdconf">/etc/freeradius/radiusd.conf</h2>

<p>edit the file <mark>/etc/freeradius/radiusd.conf</mark></p>

<ol>
<li>Find the next two lines and uncomment them. After uncommenting them, they should look like the following:</li>
</ol>

<pre><code class="language-sh">$INCLUDE sql.conf 
$INCLUDE sql/mysql/counter.conf 
</code></pre>

<ol>
<li>Find the snippet <u>instantiate {...} around line 710 and add the following</u> inside it:  </li>
</ol>

<pre><code>noresetcounter  
</code></pre>

<h2 id="etcfreeradiussitesavailabledefault">/etc/freeradius/sites-available/default</h2>

<p>Edit the file <mark>/etc/freeradius/sites-available/default</mark>. We will do several changes here</p>

<ol>
<li><p>The first snippet is the <u>authorize {...}</u> snipper. Find the line <strong>files</strong> in this snippet and comment it out (around line 170).</p></li>
<li><p>Find the <strong>sql</strong> line inside the <u>session {...}</u> snippet (around line 454) and enable it.</p></li>
<li><p>Find the <strong>sql</strong> line inside the <u>accounting {...}</u> snippet (around line 406) and enable it.</p></li>
<li><p>Find the <strong>sql</strong> line inside the <u>authorize {...}</u> snippet (around line 177) and enable it.</p></li>
<li><p>After enabling the 'sql' line in the authorize {...} snippet add the next lines after 'sql' as follows:  </p></li>
</ol>

<pre><code>sql  
chillispot_max_bytes  
noresetcounter  
</code></pre>]]></content:encoded></item><item><title><![CDATA[Installing freeradius on Ubuntu 14.04]]></title><description><![CDATA[<h1 id="installandconfigurefreeradius">Install and configure freeradius</h1>

<h2 id="installviaaptget">Install via apt-get</h2>

<pre><code class="language-sh">sudo apt-get install freeradius freeradius-mysql apache2 php5 libapache2-mod-php5 mysql-server mysql-client php5-mysql  
</code></pre>

<p>While installing freeradius, you will be asked for a password. Type in a strong password and keep it for later. We will need it.</p>

<h2 id="configureyourfirstuser">Configure your first user</h2>

<p><em>*Before doing any changes</em></p>]]></description><link>http://blog.moatazthenervous.com/installing-radius-on-ubuntu-14-04/</link><guid isPermaLink="false">5c351cfa-7ef5-419f-87ae-0db71a2a8523</guid><dc:creator><![CDATA[Moataz Elmasry]]></dc:creator><pubDate>Sun, 21 Jun 2015 16:49:27 GMT</pubDate><content:encoded><![CDATA[<h1 id="installandconfigurefreeradius">Install and configure freeradius</h1>

<h2 id="installviaaptget">Install via apt-get</h2>

<pre><code class="language-sh">sudo apt-get install freeradius freeradius-mysql apache2 php5 libapache2-mod-php5 mysql-server mysql-client php5-mysql  
</code></pre>

<p>While installing freeradius, you will be asked for a password. Type in a strong password and keep it for later. We will need it.</p>

<h2 id="configureyourfirstuser">Configure your first user</h2>

<p><em>*Before doing any changes to the configuration files, I can only recommend using git or mercurial to keep track of your changes and revert them *</em></p>

<p>Edit the freeradius users with vim  </p>

<pre><code class="language-sh">vim /etc/freeradius/users  
</code></pre>

<p>and search for the user '<strong>John Doe</strong>' which should be commented. Remove the comment from this line as well as the next line which says:  </p>

<pre><code class="language-properties">"John Doe" Auth-Type := Local, User-Password == "hello"
Reply-Message = "Hello, %u"  
</code></pre>

<p>Save and exit. Upon restarting the service, this user will be activated and will be ready to use. Now start freeradius with verbose output: </p>

<pre><code class="language-sh">sudo freeradius -fxxX  
</code></pre>

<p>If you get an error, like service is already running or port is being used, then most probably this means that freeradius has been started automatically when you first installed it. You need to kill this process. First find this process id</p>

<pre><code class="language-sh">ps -ef | grep freeradius  
#Then kill it with
kill -9 &lt;PROCESS ID HERE&gt;  
</code></pre>

<p>Later when everything is working fine, you can start freeradius with:  </p>

<pre><code class="language-sh">sudo service freeradius start  
</code></pre>

<p>If everything goes fine and you receive no error, then you should now be able to log into your radius server. Open a new window and type:</p>

<pre><code class="language-sh">sudo radtest "John Doe" hello 127.0.0.1 0 testing123  
</code></pre>

<p>You should get an accept reply, mine was:  </p>

<pre><code class="language-sh">Sending Access-Request of id 136 to 127.0.0.1 port 1812  
User-Name = "John Doe"  
User-Password = "hello"  
NAS-IP-Address = 255.255.255.255  
NAS-Port = 0  
rad_recv: Access-Accept packet from host 127.0.0.1:1812, id=136, length=37  
Reply-Message = "Hello, John Doe"  
</code></pre>

<h2 id="remoteaccesstotheradiusserver">Remote access to the radius server</h2>

<p>The configuration method described above does not grant you automatically an access from the internet to your radius server. If you have the domain name example.com and you tried an access from outside:</p>

<pre><code class="language-sh">sudo radtest "John Doe" hello example.com 0 testing123  
</code></pre>

<p>Then you will get a <em>connection closed</em> error. To enable remote access you need to define at least one remote clinet. <br>
edit the <u><strong>/etc/freeradius/clients.conf</strong></u> file</p>

<pre><code class="language-sh">vim /etc/freeradius/clients.conf  
</code></pre>

<p>And add the following snippet:  </p>

<pre><code>client 0.0.0.0/0 {  
  secret = "mysecret"
  shortname = name
}
</code></pre>

<p>Replace the '<em>mysecret</em>' with any password you want. Note that by doing this <u>you open your radius server authentication to the internet!!!</u>. You can of course fine tune this setting to allow connections from only a short list of clients</p>

<p>Again restart the freeradius. Now from another machien, try the following:</p>

<pre><code class="language-sh">radtest "John Doe" "hello" example.com 0 "mysecret"  
</code></pre>

<p>You should now be able to connect to your radius server from any client.</p>

<p>Here's part 2 of this tutorial <br>
<a href="http://blog.moatazthenervous.com/configure-freeradius-with-mysql/">Configure freeradius with mysql</a></p>]]></content:encoded></item></channel></rss>