<?xml version="1.0" encoding="ISO-8859-15"?>
<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>etd's Dos and Dont's &#187; Shell Script</title>
	<atom:link href="http://weblog.nomejortu.com/category/shell-script/feed" rel="self" type="application/rss+xml" />
	<link>http://weblog.nomejortu.com</link>
	<description>specialization is for insects</description>
	<lastBuildDate>Sun, 20 Jul 2008 21:45:15 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>xmitm: xml man in the middle</title>
		<link>http://weblog.nomejortu.com/shell-script/xml-man-in-the-middle-xmitm</link>
		<comments>http://weblog.nomejortu.com/shell-script/xml-man-in-the-middle-xmitm#comments</comments>
		<pubDate>Sun, 16 Dec 2007 20:47:05 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=38</guid>
		<description><![CDATA[This post is a result of ideas and tools developed during the review of  client-side applications that use the XMPP protocol to communicate with a server (opening a raw socket, not using HTTP as a transport).
The only way we could think of getting our hands on the communication was to write a small set [...]]]></description>
			<content:encoded><![CDATA[<p>This post is a result of ideas and tools developed during the review of  client-side applications that use the <a href="http://www.xmpp.org/">XMPP</a> protocol to communicate with a server (opening a raw socket, not using HTTP as a transport).</p>
<p>The only way we could think of getting our hands on the communication was to write a small set of scripts to trick the client and encapsulate the communication inside HTTP requests that we could then manipulate using standard proxy tools such as <a href="http://www.portswigger.net/suite/">burp</a>.</p>
<p>Although the information and scripts described in this post are focussed on intercepting a XML communication, the same principles apply to man in the middle any ASCII protocol such as smtp, ftp or pop.</p>
<p><strong>update</strong>: slides available <a href="/data/files/xmitm-slides_2008-02-07.pdf">here</a><br />
<span id="more-38"></span></p>
<p>The first step is to trick the client to connect to our local box instead of connecting to the remote server, this is done by adjusting the <a href="http://en.wikipedia.org/wiki/Hosts_file">hosts file</a>.</p>
<p><center><img src="/data/img/xmitm_01.jpg" height="329" width="320" alt="Standard flow of communication"/></center></p>
<p>A ruby script will sit in the middle of the communication and will be able to intercept and modify messages sent and received by the client:- </p>
<p><center><img src="/data/img/xmitm_02.jpg" height="250" width="393"  alt="xmitm sits between client and server and intercepts the communication"/></center></p>
<p>Once this is done, our <em>attack</em> will need three elements:</p>
<ul>
<li>the <strong>xmitm</strong> script.</li>
<li>an external web proxy tool.</li>
<li>a dummy web server.</li>
</ul>
<p>The script will intercept the connection and send the data to the proxy. We need the dummy server (the body of the response will be the body of the request) to close the loop with the proxy (<del>I will add some nice graphs to clarify this soon</del>).</p>
<p><center><img src="/data/img/xmitm_03.jpg" width="469" height="293" alt="The original message is passed through the proxy to let the user modify it."/></center></p>
<p>The original XML message is encapsulated in an HTTP request and passed through the proxy. The user can inspect and modify the message using a standard web proxy tool. The request is then forwared to a dummy <strong>*echo*</strong> web server that replies with the same payload that was requested. The script can extract the modified payload and forward it to the server.</p>
<p>The same process is applied to incoming messages.</p>
<p>Below is the main body of the script (you can also grab the <a href="/data/code/ruby/xmitm.rb">code</a>):-</p>
<div class="hl-surround" style="height:280px;"><div class="hl-main"><pre><span class="hl-comment"># create a server that accepts connections from the client
</span><span class="hl-identifier">server</span><span class="hl-default"> = </span><span class="hl-identifier">TCPServer</span><span class="hl-default">.</span><span class="hl-identifier">new</span><span class="hl-brackets">(</span><span class="hl-var">$local_host</span><span class="hl-code">, </span><span class="hl-var">$local_port</span><span class="hl-brackets">)

</span><span class="hl-reserved">while</span><span class="hl-brackets">(</span><span class="hl-identifier">local</span><span class="hl-code"> = </span><span class="hl-identifier">server</span><span class="hl-code">.</span><span class="hl-identifier">accept </span><span class="hl-brackets">) </span><span class="hl-reserved">do
  </span><span class="hl-comment"># everytime we accept a connection for the client, we open a connection
  # with the server to stablish the dialog.
  </span><span class="hl-identifier">remote</span><span class="hl-default"> = </span><span class="hl-identifier">TCPSocket</span><span class="hl-default">.</span><span class="hl-identifier">new</span><span class="hl-brackets">(</span><span class="hl-var">$remote_host</span><span class="hl-code">, </span><span class="hl-var">$remote_port</span><span class="hl-brackets">)
  
  </span><span class="hl-comment"># if one of the ends of the communication closes the socket, we
  # toggle this flag
  </span><span class="hl-identifier">alive</span><span class="hl-default"> = </span><span class="hl-reserved">true
    
  while </span><span class="hl-identifier">alive </span><span class="hl-reserved">do
    </span><span class="hl-comment"># see the explanation below
    </span><span class="hl-identifier">result</span><span class="hl-default"> = </span><span class="hl-identifier">select</span><span class="hl-brackets">([</span><span class="hl-identifier">local</span><span class="hl-code">, </span><span class="hl-identifier">remote</span><span class="hl-brackets">]</span><span class="hl-code">, </span><span class="hl-reserved">nil</span><span class="hl-code">, </span><span class="hl-reserved">nil</span><span class="hl-brackets">)
  
    </span><span class="hl-reserved">if </span><span class="hl-identifier">result</span><span class="hl-default"> != </span><span class="hl-reserved">nil then
      for </span><span class="hl-identifier">socket </span><span class="hl-reserved">in </span><span class="hl-identifier">result</span><span class="hl-brackets">[</span><span class="hl-number">0</span><span class="hl-brackets">]

        </span><span class="hl-comment"># detect if one end of the connection is closed and
        # close the other end
        </span><span class="hl-reserved">if </span><span class="hl-brackets">(</span><span class="hl-identifier">socket</span><span class="hl-code">.</span><span class="hl-identifier">eof</span><span class="hl-code">?</span><span class="hl-brackets">)
          </span><span class="hl-identifier">local</span><span class="hl-default">.</span><span class="hl-identifier">close
          remote</span><span class="hl-default">.</span><span class="hl-identifier">close
          alive</span><span class="hl-default"> = </span><span class="hl-reserved">false
          break
        end
        
        </span><span class="hl-comment"># read the information that one peer wants to send to the other
        </span><span class="hl-identifier">data</span><span class="hl-default"> = </span><span class="hl-identifier">socket</span><span class="hl-default">.</span><span class="hl-identifier">gets</span><span class="hl-brackets">(</span><span class="hl-var">$eom</span><span class="hl-brackets">)

        </span><span class="hl-comment"># encapsulate the data into an HTTP proxy request
        </span><span class="hl-identifier">res</span><span class="hl-default"> = </span><span class="hl-identifier">Net</span><span class="hl-default">::</span><span class="hl-identifier">HTTP</span><span class="hl-default">.</span><span class="hl-identifier">new</span><span class="hl-brackets">(</span><span class="hl-var">$proxy_host</span><span class="hl-code">, </span><span class="hl-var">$proxy_port</span><span class="hl-brackets">)</span><span class="hl-default">.</span><span class="hl-identifier">start </span><span class="hl-reserved">do</span><span class="hl-default"> |</span><span class="hl-identifier">http</span><span class="hl-default">| 
          </span><span class="hl-identifier">req</span><span class="hl-default"> = </span><span class="hl-identifier">Net</span><span class="hl-default">::</span><span class="hl-identifier">HTTP</span><span class="hl-default">::</span><span class="hl-identifier">Post</span><span class="hl-default">.</span><span class="hl-identifier">new</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">http://#{$dummyhttp_host}:#{$dummyhttp_port}/</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">)
          </span><span class="hl-identifier">req</span><span class="hl-default">.</span><span class="hl-identifier">body</span><span class="hl-default">= </span><span class="hl-identifier">data
          http</span><span class="hl-default">.</span><span class="hl-identifier">request</span><span class="hl-brackets">(</span><span class="hl-identifier">req</span><span class="hl-brackets">)
        </span><span class="hl-reserved">end

        </span><span class="hl-identifier">modified_data</span><span class="hl-default"> = </span><span class="hl-identifier">res</span><span class="hl-default">.</span><span class="hl-identifier">body</span><span class="hl-default">.</span><span class="hl-identifier">chomp

        </span><span class="hl-comment"># send the modified data to the other end of the connection        
        </span><span class="hl-reserved">if </span><span class="hl-brackets">(</span><span class="hl-identifier">socket</span><span class="hl-code"> == </span><span class="hl-identifier">local</span><span class="hl-brackets">)
          </span><span class="hl-identifier">remote</span><span class="hl-default">.</span><span class="hl-identifier">puts</span><span class="hl-brackets">(</span><span class="hl-identifier">modified_data</span><span class="hl-brackets">)
        </span><span class="hl-reserved">else
          </span><span class="hl-identifier">local</span><span class="hl-default">.</span><span class="hl-identifier">puts</span><span class="hl-brackets">(</span><span class="hl-identifier">modified_data</span><span class="hl-brackets">)
        </span><span class="hl-reserved">end
        </span><span class="hl-identifier">socket</span><span class="hl-default">.</span><span class="hl-identifier">flush
      </span><span class="hl-reserved">end
    end
  end
end</span></pre></div></div>
<p>What the script does can be summarized in the following steps:</p>
<ol>
<li>Create a TCP server, listening on the port the client is expecting.</li>
<li>For each connection accepted:
<ul>
<li>Open a connection with the remote server.</li>
<li>Wait until one end of the communication (first the client, then the server, then the client, etc.) has something to transmit.</li>
<li>Grab the XML message.</li>
<li>Put that message as a payload of a new <a href="http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html">Net::HTTP::Post</a> request.</li>
<li>Send the request to the external web proxy.</li>
<li>Grab the body of the response given by the proxy (already modified by the user using the external proxy).</li>
<li>Send the modified request to the other end of the line.</li>
</ul>
</li>
</ol>
<p>The most interesting piece of the code is the one regarding <a href="http://ruby-doc.org/docs/ProgrammingRuby/html/ref_m_kernel.html#Kernel.select">Kernel#select</a> function that waits for data to become available from input/output devices. </p>
<p>A note regarding the specifics of the protocol we were dealing with, each peer ends its messages using a special character (a <code>NULL</code> byte), that caracter is defined in the <code>$eom</code> variable and the script keeps reading the socket until that <em>end of message</em> character is read.</p>
<p>The last piece of the puzzle is the dummy HTTP server. I coded two flavours: a <a href="/data/code/ruby/webrick.rb">ruby version</a> and a <a href="/data/code/java/SimpleHTTPServer.java">java version</a> (<del>not yet available for download</del> based on the <a href="http://www.oreilly.com/catalog/javanp2/chapter/ch11.html#53648">SingleFileHTTPServer example</a>). You can pick your choice. Here is the ruby one:-</p>
<div class="hl-surround" ><div class="hl-main"><pre><span class="hl-reserved">require </span><span class="hl-quotes">'</span><span class="hl-string">webrick</span><span class="hl-quotes">'

</span><span class="hl-identifier">include WEBrick

</span><span class="hl-comment"># create the server, no output, disable logging
</span><span class="hl-identifier">s</span><span class="hl-default"> = </span><span class="hl-identifier">HTTPServer</span><span class="hl-default">.</span><span class="hl-identifier">new</span><span class="hl-brackets">(</span><span class="hl-code">
  :</span><span class="hl-identifier">Port</span><span class="hl-code"> =&gt; </span><span class="hl-number">2000</span><span class="hl-code">,
  :</span><span class="hl-identifier">Logger</span><span class="hl-code"> =&gt; </span><span class="hl-identifier">Log</span><span class="hl-code">.</span><span class="hl-identifier">new</span><span class="hl-brackets">(</span><span class="hl-reserved">nil</span><span class="hl-code">, </span><span class="hl-identifier">BasicLog</span><span class="hl-code">::</span><span class="hl-identifier">FATAL</span><span class="hl-brackets">)</span><span class="hl-code">,
  :</span><span class="hl-identifier">AccessLog</span><span class="hl-code"> =&gt; </span><span class="hl-brackets">[]  )

</span><span class="hl-comment"># the *echo* functionality
</span><span class="hl-identifier">s</span><span class="hl-default">.</span><span class="hl-identifier">mount_proc</span><span class="hl-brackets">(</span><span class="hl-quotes">&quot;</span><span class="hl-string">/</span><span class="hl-quotes">&quot;</span><span class="hl-brackets">) </span><span class="hl-reserved">do</span><span class="hl-default"> |</span><span class="hl-identifier">req</span><span class="hl-default">, </span><span class="hl-identifier">res</span><span class="hl-default">|
  </span><span class="hl-identifier">res</span><span class="hl-default">.</span><span class="hl-identifier">body</span><span class="hl-default"> = </span><span class="hl-identifier">req</span><span class="hl-default">.</span><span class="hl-identifier">body
  res</span><span class="hl-brackets">[</span><span class="hl-quotes">'</span><span class="hl-string">Content-Type</span><span class="hl-quotes">'</span><span class="hl-brackets">]</span><span class="hl-default"> = </span><span class="hl-identifier">req</span><span class="hl-brackets">[</span><span class="hl-quotes">'</span><span class="hl-string">Content-Type</span><span class="hl-quotes">'</span><span class="hl-brackets">]
</span><span class="hl-reserved">end

</span><span class="hl-comment"># clean tear down
</span><span class="hl-identifier">trap</span><span class="hl-brackets">(</span><span class="hl-quotes">'</span><span class="hl-string">INT</span><span class="hl-quotes">'</span><span class="hl-brackets">)</span><span class="hl-default"> { </span><span class="hl-identifier">s</span><span class="hl-default">.</span><span class="hl-identifier">shutdown</span><span class="hl-default"> }

</span><span class="hl-identifier">s</span><span class="hl-default">.</span><span class="hl-identifier">start</span></pre></div></div>
<p>And this completes the XML protocol man-in-the-middle <acronym title="Do It Yourself">DIY</acronym> kit. Hope you find it useful. <img src='http://weblog.nomejortu.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=38&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/xml-man-in-the-middle-xmitm/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>check for robots.txt</title>
		<link>http://weblog.nomejortu.com/shell-script/check-for-robotstxt</link>
		<comments>http://weblog.nomejortu.com/shell-script/check-for-robotstxt#comments</comments>
		<pubDate>Tue, 23 Oct 2007 15:54:04 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=12</guid>
		<description><![CDATA[Some times it is useful to check if a given HTTP server has a robots.txt file in it. If it exist it may disclose interesting information, useful for a pentest 

 From the Wikipedia:

The robots exclusion standard or robots.txt protocol is a convention to prevent cooperating web spiders and other web robots from accessing all [...]]]></description>
			<content:encoded><![CDATA[<p>Some times it is useful to check if a given HTTP server has a <code>robots.txt</code> file in it. If it exist it may disclose interesting information, useful for a pentest <img src='http://weblog.nomejortu.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<span id="more-12"></span><br />
 From the <a href="http://en.wikipedia.org/wiki/Robots.txt">Wikipedia</a>:</p>
<blockquote><p>
The robots exclusion standard or robots.txt protocol is a convention to prevent cooperating web spiders and other web robots from accessing all or part of a website. The information specifying the parts that should not be accessed is specified in a file called robots.txt in the top-level directory of the website.
</p></blockquote>
<p>Here is a script that checks for the presence of the file in a list of hosts (you can download the <a href="http://weblog.nomejortu.com/data/code/bash/robots.sh">source code</a>). Two main parts can be distinguished: command line parsing and file download. </p>
<p>You can call the script in two different ways. Either you do not specify the protocol (and HTTP will be used):-</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>./robots.sh &lt;host1&gt; &lt;host2&gt; ...</pre></div></div>
<p>Or you specify the protocol with:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>./robots.sh  -p [http|https] &lt;host1&gt; &lt;host2&gt; ...</pre></div></div>
<p>Let&#8217;s see how this is done:</p>
<div class="hl-surround" ><div class="hl-main"><pre>PROTO=( http https )
HTTP=${PROTO[0]}
FILE=/tmp/robots.txt

# command line parsing
if [ &quot;-p&quot; == $1 ]
then
  for bar in ${PROTO[*]}
  do
    if [ $bar == $2 ];
    then
      HTTP=$2
      HOSTS=${*:3}
    fi
  done
else
  HOSTS=$*
fi</pre></div></div>
<p>We check if the first argument is &#8220;-p&#8221; in which case, the next argument should be one of the allowed values (those in <code>$PROTO</code> array). If that is the case, we strip the first two parameters and put everything else in the <code>$HOSTS</code> variable. At the end of the code above, <cod>$HTTP</cod> will contain either <strong>http</strong> or <strong>https</strong> and <code>$HOSTS</code> will consist of a list of hosts whose robots.txt file existance we want to verify. </p>
<p>Once we know what protocol are we using and the list of targets, the only thing left is to try to download the <code>robots.txt</code> file of each server:-</p>
<div class="hl-surround" ><div class="hl-main"><pre>for foo in $HOSTS; do
  echo &quot;================&quot;
  echo &quot;Server: $foo ($HTTP)&quot;
  CODE=`wget -O $FILE $HTTP://$foo/robots.txt 2&gt;&amp;1 | grep HTTP | head -1 | awk '{print $6}'`
  echo &quot;Code: $CODE&quot;
  if [ &quot;200&quot; == $CODE ]
  then
    echo &quot;Contents:&quot;
    echo &quot;----------------&quot;
    cat $FILE
    rm $FILE
    echo &quot;----------------&quot;
  fi
done</pre></div></div>
<p>If the response code is <code>200 OK</code> we <strong>cat</strong> the file to standard output. Otherwise we just move on to the next target of the list. The only tricky bit of the previous code is:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>wget -O $FILE $HTTP://$foo/robots.txt 2&gt;&amp;1 | grep HTTP | head -1 | awk '{print $6}'</pre></div></div>
<p>Where we try to download the file saving it to the location specified by <code>$FILE</code>. In order to get the HTTP error code we redirect standard error to standard output using <code>2&gt;&amp;1</code>.</p>
<p>One last word, it is acknowledged that the script does not follow HTTP redirects, but if the server replies with a redirect this means that effectively, no <code>robots.txt</code> file is present.</p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=12&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/check-for-robotstxt/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>rComic: comic strip downloader</title>
		<link>http://weblog.nomejortu.com/shell-script/rcomic-comic-strip-downloader</link>
		<comments>http://weblog.nomejortu.com/shell-script/rcomic-comic-strip-downloader#comments</comments>
		<pubDate>Tue, 23 Oct 2007 12:26:56 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=28</guid>
		<description><![CDATA[rComic is a small script to download and display Internet comic strips. To add new strips, you only need to modify the config file. And it is an interesting exercise to play with the Net::HTTP and YAML libraries.

rComic makes use of two external programs: wget and display for downloading and displaying the image. Both tools [...]]]></description>
			<content:encoded><![CDATA[<p>rComic is a small script to download and display Internet comic strips. To add new strips, you only need to modify the config file. And it is an interesting exercise to play with the <a href="http://www.ruby-doc.org/core/classes/Net/HTTP.html">Net::HTTP</a> and <a href="http://www.ruby-doc.org/core/classes/YAML.html">YAML</a> libraries.<br />
<span id="more-28"></span><br />
rComic makes use of two external programs: <code>wget</code> and <code>display</code> for downloading and displaying the image. Both tools are available as packages in all major distros (look for <code>imagemagick</code>). Get <a href="/data/code/ruby/rcomic.tar.gz">the code</a> and let&#8217;s get it started.</p>
<p>To store the information of our comic strips we will be using <acronym title="YAML Ain'tMarkup Language">YAML</acronym>:</p>
<blockquote><p>The YAML library serializes and deserializes Ruby object trees to and from and external, readable, plain-text format.</p></blockquote>
<p>In the config file (<code>rcomic.yaml</code>) every comic strip definition will have the following appearance:</p>
<div class="hl-surround" ><div class="hl-main"><pre>xkcd:
  desc: A webcomic of romance, sarcasm, math, and language.
  host: www.xkcd.com
  path: /
  rexp: &lt;img\ssrc=\&quot;(.*comics.*?)\&quot;.*?&gt;</pre></div></div>
<p>You need a <strong>key word</strong> that will be used to refer to the strip and a set of configuration parameters, the host name, the path inside the server and a regular expression to identify the desired image.</p>
<p>In order to add a new strip, you only need to append a block like the one above to your configuration file.</p>
<p>Three steps are performed in the script: command line parsing, HTTP connection and download of the page, image download and display.  In order to know what strip are we working on, first we need to load the configuration file as show:-</p>
<div class="hl-surround" ><div class="hl-main"><pre>#load configuration
config = YAML.load_file('rcomic.yaml')</pre></div></div>
<p>Then some simple logic determines if the requested strip (the first argument provided) is configured in the <code>.yaml</code> file. If no reference to the <strong>key word</strong> is found  in the YAML file, a help message is displayed. Otherwise, we carry on with the next steps:</p>
<div class="hl-surround" ><div class="hl-main"><pre># prepare an HTTP connection
http = Net::HTTP.new($host)
# get the page
response = http.get($path)

# scan for the image
img = response.body.scan($rexp).first.first
file = File.basename(img)</pre></div></div>
<p>First we request the page and then we apply the regular expression to the body of the HTML returned. The <code>img</code> variable will contain the full URL to the image (i.e. <code>http://imgs.xkcd.com/comics/gyroscopes.png</code>) and the <code>file</code> will contain only the file name (i.e. <code>gyroscopes.png</code>). </p>
<p>With this information is dead easy to download and display the images:</p>
<div class="hl-surround" ><div class="hl-main"><pre># download (if not already downloaded)
unless File.exist?(&quot;/tmp/#{file}&quot;)
  `wget -O /tmp/#{file} #{img}`
end

# display
`display /tmp/#{file}`</pre></div></div>
<p>As a side note, we will only download the file if the file is not already present in our <code>/tmp/</code> folder.</p>
<p>Happy comics <img src='http://weblog.nomejortu.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=28&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/rcomic-comic-strip-downloader/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ninja iptables for your server</title>
		<link>http://weblog.nomejortu.com/shell-script/ninja-iptables-for-your-server</link>
		<comments>http://weblog.nomejortu.com/shell-script/ninja-iptables-for-your-server#comments</comments>
		<pubDate>Fri, 14 Sep 2007 11:15:37 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=24</guid>
		<description><![CDATA[Security is often about layers on top of layers on top of layers&#8230; And one of these layers is usually an iptables firewall installed in your server. Let&#8217;s create a small script to provide our server with the kung-fu fighting techniques needed to defeat the black hats!!

You can download the script from here. But let&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>Security is often about layers on top of layers on top of layers&#8230; And one of these layers is usually an <code>iptables</code> firewall installed in your server. Let&#8217;s create a small script to provide our server with the <a href="/data/img/mastering_kung-fu.jpg">kung-fu fighting techniques</a> needed to defeat the black hats!!<br />
<span id="more-24"></span><br />
You can download the script from <a href="/data/code/bash/firewall.sh">here</a>. But let&#8217;s have it on the screen so we can walk through the rules:-</p>
<div class="hl-surround" style="height:280px;"><div class="hl-main"><pre>#!/bin/bash

###
### IPTables config file
### Based on the rules compiled by Ranjit San aka 'the grasshopper'
### Created 2007-09-14 by Daniel Martin Gomez &lt;etd[-at-]nomejortu.com&gt;
### Revision 1
###

###
### define variables
###

### path to iptables 
IPT=/sbin/iptables

### This contains a list of approved Debian sites to get software updates.
DEBIAN_SITES=('194.109.137.218' '212.219.56.139' '212.219.56.133' '212.219.56.134' '212.219.56.135' '212.219.56.138')

### This contains the authorised DNS servers configured in /etc/resolv.conf. 
DNS_SERVERS=('') 

### This is a list of external IPs that you want to allow ssh access from.
OTHER_GATEWAYS=('') 

### This is a list of hosts authorised to try ICMP probes to check if the
### server is running. This could be your ISP's IPs
CONTROL_GATEWAYS=('')

### Types of ICMP probes to allow from the previous servers
ICMP_TYPES=('echo-reply' 'destination-unreachable' 'echo-request' 'ttl-exceeded')


#### NTP servers for time synch
NTP_SERVERS=('')

### ------------------------------------------------- do not change below this line

###
### INPUT
###

### will flush the chains or all rules one by one. Therefore all new rules will be created. 
$IPT -F 

### allows inbound packets to be processed
$IPT -P INPUT ACCEPT

### drops packets so that they can not come through one interface and flow out of another. 
$IPT -P FORWARD DROP 

### This allows outbound packets to be processed
$IPT -P OUTPUT ACCEPT


### allows ICMP types (defined above) for hosts in the control list 
for IP in ${CONTROL_GATEWAYS[@]}; do
	for ICMP in ${ICMP_TYPES[@]}; do
		$IPT -A INPUT -s $IP -p icmp --icmp-type $ICMP -j ACCEPT 
	done
done

### this accepts connections for http and https access from anywhere
$IPT -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT

### this allows remote administration using ssh from your other gateways.
for IP in ${OTHER_GATEWAYS[@]}; do 
    $IPT -A INPUT -s $IP -p tcp -m tcp --dport 22 -j ACCEPT
done


### this allows packets to start a new connection or allows packets that are
### already associated with a connection, required for stateful inspection.
$IPT -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

### this allows NTP traffic from NTP server
for NTP in ${NTP_SERVERS[@]}; do 
    $IPT -A INPUT -s $NTP -p udp -m udp --sport 123 -j ACCEPT
done

### we are about to drop everything else, so first log the discarded traffic
### just in case we want to know what *they* are trying.
$IPT -A INPUT -j LOG

### this drops any traffic that does not match to the INPUT rules
$IPT -A INPUT -j DROP 



###
### OUTPUT
###

### Allows traffic to authorised DNS servers
for IP in ${DNS_SERVERS[@]}; do 
    $IPT -A OUTPUT -d $IP -p udp -m udp --dport 53 -j ACCEPT
done

### Allows http traffic to debain sites for software updates. 
### Initial config rule
for IP in ${DEBIAN_SITES[@]}; do 
    $IPT -A OUTPUT -d $IP -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
done

### this allows packets to start a new connection or allows packets that are
### already associated with a connection, required for stateful inspection. 
$IPT -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT 

### this allows NTP traffic to the NTP servers
for NTP in ${NTP_SERVERS[@]}; do 
    $IPT -A OUTPUT -d $NTP -p udp -m udp --dport 123 -j ACCEPT
done

### this logs all OUTPUT traffic that does not match the rules before it beign
### dropped.
$IPT -A OUTPUT -j LOG 

### this drops any traffic that does not match to the OUTPUT rules
$IPT -A OUTPUT -j DROP</pre></div></div>
<p>Just two things to add: First, do not forget to set your own values for the variables <code>DNS_SERVERS</code>, <code>OTHER_GATEWAYS</code>, <code>CONTROL_GATEWAYS</code> and <code>NTP_SERVERS</code>. And second, if you want your kung-fu up and ready after boot you may need to issue the following:-</p>
<div class="hl-surround" ><div class="hl-main"><pre>cd /etc/init.d/
wget http://weblog.nomejortu.com/data/code/bash/firewall.sh
chmod +x firewall.sh
update-rc.d firewall.sh defaults</pre></div></div>
<p>If you ever want to remove it from the boot sequence just issue:-</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>update-rc.d -f firewall.sh remove</pre></div></div>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=24&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/ninja-iptables-for-your-server/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ruby bot: email processing</title>
		<link>http://weblog.nomejortu.com/shell-script/ruby-bot-email-processing</link>
		<comments>http://weblog.nomejortu.com/shell-script/ruby-bot-email-processing#comments</comments>
		<pubDate>Mon, 06 Aug 2007 22:11:56 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=20</guid>
		<description><![CDATA[
Pinky: Gee, Brain, what are we going to do tonight?
Brain: The same thing we do every night, try to take over the world!

Have you ever wanted to have the ability to send commands to your box using email? Use RubyBot, the brand new plugin-driven ruby script that makes the task of taking over the world [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>
<strong>Pinky</strong>: Gee, Brain, what are we going to do tonight?<br />
<strong>Brain</strong>: The same thing we do every night, try to take over the world!
</p></blockquote>
<p>Have you ever wanted to have the ability to send commands to your box using email? Use RubyBot, the brand new plugin-driven ruby script that makes the task of taking over the world a bit easier!<br />
<span id="more-20"></span><br />
Goals of the project:</p>
<ul>
<li>We want to have a script that can be used directly by the <acronym title="Mail Transfer Agent">MTA</acronym> (much in the way <a href="http://www.procmail.org/">procmail</a> works).</li>
<li>We want to deal with the internals of email format as less as possible.</li>
<li>Flexibility is an issue! We want to be able to do all sorts of things.</li>
<li>We want to have some feedback/output from our commands</li>
</ul>
<p>But first, stand and relax, there is lots of stuff comming in this post, so maybe it is a good idea to download <a href="/data/code/ruby/rubybot.tar.bz2">the code</a> and have a look at it before we start. <img src='http://weblog.nomejortu.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><acronym title="Mail Transfer Agent">MTA</acronym>s can usually be configured to pass received messages to certain applications. The internals of how this mechanism works is out of the scope of this post. However, as an example, let&#8217;s see how <a href="http://www.qmail.org/">qmail</a> uses the <strong>.qmail</strong> files to do it. The following <strong>.qmail</strong> file will pipe the contents of all the incoming mail to our script:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>|./rubybot.rb</pre></div></div>
<p>The first thing thatour script needs to do is to get the piped message. In ruby we do this by reading the contents of the standar input:</p>
<div class="hl-surround" ><div class="hl-main"><pre>#0: get email from standard input
email = ''
while gets
  email &lt;&lt; $_
end</pre></div></div>
<p>The previous code will store in the <code>email</code> variable the contents of the email. Instead of trying to parse the email with regular expressions we are going to use the <a href="http://wiki.rubyonrails.org/rails/pages/ActionMailer">ActionMailer</a> package of the Ruby on Rails (RoR) framework.</p>
<blockquote><p>
<strong>What is ActionMailer?</strong><br />
Action Mailer is a framework for designing email-service layers.
</p></blockquote>
<p>Sounds like ideal, does it? In order to use the package we will need to include it and also to create a class that extends the <code>ActionMailer::Base</code>, here is the code:</p>
<div class="hl-surround" ><div class="hl-main"><pre>require 'rubygems'
require_gem 'actionmailer'

#wrapper of RoR ActionMailer
class RubyBot &lt; ActionMailer::Base
  def receive(email)
    return email
  end
end</pre></div></div>
<p>Now we can convert the raw email string into a ruby object with the following call:</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>msg = RubyBot.receive(email)</pre></div></div>
<p>We can send signals such as <code>msg.subject</code> or <code>msg.parts</code> to the object to query the email&#8217;s information.</p>
<p>Before continuing with the rest of the script a word should be said regarding <strong>logging</strong> and <strong>configuration</strong>. After all, our <code>RubyBot</code> is <em>quick-and-dirty</em> script so for configuration we will use a hash at the begining of the file:</p>
<div class="hl-surround" ><div class="hl-main"><pre>#--------------------------------------- config
$options = {
  :myself =&gt; 'rubybot[_at_]nomejortu.com',
  :admin =&gt; 'etd[_at_]nomejortu.com',
  :subject =&gt; '[rubybot] notificacion:',
  :plugins_dir =&gt; './rbplugins',
  :pluginopt =&gt; { 
    :tmpdir =&gt; './tmp',
    :logger =&gt; nil
  }
}
#--------------------------------------- /config</pre></div></div>
<p>All options are self explanatory except maybe two: </p>
<ul>
<li><strong>:plugins_dir</strong> will contain all of our plugins.</li>
<li><strong>:pluginopt</strong> contains the options that we will be passing to the plugins (mainly an object for logging and a temporary directory).</li>
</ul>
<p>For logging we are going to use ruby&#8217;s standard <a href="http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc/classes/Logger.html">Logger</a> and we are going to store it&#8217;s output in a log file under the <strong>:plugins_dir</strong> directory. This is the code that initializes the logger:</p>
<div class="hl-surround" ><div class="hl-main"><pre>logfile = $options[:plugins_dir]+'/msg.log'
File.rm_f(logfile) if File.exist?(logfile)
log = Logger.new(logfile)

log.level = Logger::DEBUG
$options[:pluginopt][:logger] = log</pre></div></div>
<p>We are saving the name of the file for the last bit of the script where we attach the log file to the notification that <code>RubyBot</code> sends to the administrator. Also we are saving a reference to the logger in the configuration hash so we can pass it to out plugins.</p>
<p>Our script will use the subject line to decide which plugin should handle the request. The dispatching algorithm is show below:</p>
<div class="hl-surround" ><div class="hl-main"><pre>#2rd process the command (from email's subject)
module_name = msg.subject.split[0]
module_file = $options[:plugins_dir] + '/' + module_name + '.rb'
if (FileTest.exists?(module_file))
  log.info{ &quot;valid plugin found: #{module_name}&quot; }
  begin
    load module_file
    plugin = Kernel.const_get(module_name.capitalize + 'Plugin').new
    output = plugin.process(msg, $options[:pluginopt])
  rescue
    log.error{ &quot;error while processing command: #{$!}&quot; }
    log.debug{ $!.backtrace.join(&quot;\n&quot;) }
    output = &quot;error while processing command: #{$!}&quot;
  end
else
  log.error {&quot;module not found in plugins dir (#{$options[:plugins_dir]})&quot;}
end</pre></div></div>
<p>A few things are going on in the previous piece of code. First we split the <code>subject</code> of the email and we take the first word as a module name. Then we try to determine if a file called <code><em>module_name</em>.rb</code> exists in the plugin directory. An error is logged if the file is not found. However, if we find the file we try to load the file and create an instance of the module:</p>
<div class="hl-surround" ><div class="hl-main"><pre>load module_file
plugin = Kernel.const_get(module_name.capitalize + 'Plugin').new</pre></div></div>
<p>For example, if our message&#8217;s subject is &#8220;<em>simple</em>&#8221; te previous lines will try to instantiate a copy of <code>SimplePlugin</code> from the file <code>./rbplugins/simple.rb</code>. If something goes wrong we capture and log the exception, otherwise we send the <code>.process</code> signal to the plugin passing the email and the options as arguments.</p>
<p>All <code>RubyBot</code>&#8217;s plugins should include the <code>Plugin</code> module as defined in <code>./rbplugins/plugin.rb</code>. The module has five methods and I will not give details of all of them here for the sake of clarity in the post. However, a brief description follows (<a href="http://en.wikipedia.org/wiki/MIME">MIME</a> stands for <em>Multipurpose Internet Mail Extensions</em>):-</p>
<ul>
<li><strong>part_filename</strong>: returns the filename that we should use for a given part in a <a href="http://en.wikipedia.org/wiki/MIME#Multipart_Messages">MIME multipar messages</a>.</li>
<li><strong>ext</strong>: given a <acronym title="Multipurpose Internet Mail Extensions">MIME</acronym> type the method returns a file extension.</li>
<li><strong>save</strong>: saves all the attachments of the email into a given folder.</li>
<li><strong>clear</strong>: given a folder, deletes it&#8217;s contents.</li>
</ul>
<p>The last and most interesting method is <code>process</code>. It will perform three operations: first save all the email&#8217;s attachments to the temporary folder, then process the body of the message looking for commands and finally delete the attachments from the temporary folder.</p>
<p>Depending on whether the email received is multipart or not a slightly different approach is needed to get the requested commands:</p>
<div class="hl-surround" ><div class="hl-main"><pre>#process the body, 1 command per line
    if (@msg.parts.empty?)
      commands = @msg.body.split(/\n/)
    else
      commands = @msg.parts[0].body.split(/\n/)
    end</pre></div></div>
<p>Now we have an array that contains all the commands. The processing cycle goes as follows:</p>
<div class="hl-surround" ><div class="hl-main"><pre>commands.each do |cmdline|
      args = cmdline.split
      if (self.respond_to?(args[0]))
        begin
          @log.info( 'plugin' ) { &quot;[#{args[0]}] processed by #{args[0]} plugin. &quot; }
          out &lt;&lt; self.send(args[0], args[1,args.size-1])
        rescue
          @log.error('plugin') { &quot;error while processing command: #{$!}&quot; }
          @log.debug('plugin') { $!.backtrace.join(&quot;\n&quot;) }
          out &lt;&lt; &quot;error while processing command: #{$!}&quot;
        end
      else
        @log.error('plugin') { &quot;undefined command: #{args[0]}&quot; }
        out &lt;&lt; '&lt;command not found / no output from command&gt;'
      end
    end</pre></div></div>
<p>Appart from the error handling the interesting calls are two: <code>self.respond_to?</code> and <code>self.send</code>. With the first one we check whether the plugin implements the requested command and with the second one we delegate the execution of the command to the implementation.</p>
<p>Following our previous example let&#8217;s say that we receive the following email:</p>
<div class="hl-surround" ><div class="hl-main"><pre>Subject: simple
[...]
echo hello world
echo good bye</pre></div></div>
<p><code>RubyBot</code> will parse the <code>Subject</code> line and will load and instantiate <code>SimplePlugin</code>. Then a <code>process</code> signal will be sent to the plugin. Since our example has no attachments, the <code>process</code> method (of the <code>Plugin</code> module) will just walk through the commands checking if we have implemented <code>echo</code> in <code>SimplePlugin module</code>. Provided that <code>SimpleCode</code> is defined as follows (in <code>./rbplugins/simple.rb</code>):</p>
<div class="hl-surround" ><div class="hl-main"><pre>require 'rbplugins/plugin'

class SimplePlugin
  include Plugin
  def echo(args)  
    return &quot;good to go: #{args.join('|')}&quot;
  end
end</pre></div></div>
<p>The output of the commands issued above would be:</p>
<div class="hl-surround" ><div class="hl-main"><pre>good to go: hello|world
good to go: good|bye</pre></div></div>
<p>To comply with our last goal we need to add an extra method to the <code>RubyBot</code> class. The method <code>notification</code> will be used at the end of the script to send us a notification with all the details of the procession of our commands.</p>
<div class="hl-surround" style="height:280px;"><div class="hl-main"><pre>class RubyBot &lt; ActionMailer::Base
[...]
  def notification(msg, out, log)
    recipients $options[:admin]
    subject &quot;#{$options[:subject]} #{msg.subject}&quot;
    from $options[:myself]
    
    commands = 'empty'
    if (msg.parts.empty?)
      commands = msg.body
    else
      commands = msg.parts[0].body
    end

    body =&lt;&lt;EOF
    ------------------------------------
    Se ha recibido el mensaje anterior
    From: #{msg.from}
    Subject: #{msg.subject}
    Date: #{msg.date}
    Body:
      #{commands}
    Output: 
      #{out} 
    ------------------------------------
EOF
      
    part :content_type =&gt; 'text/plain', :body =&gt; body

    attachment :content_type =&gt; 'text/plain', :body =&gt; File.readlines(log).join(&quot;\n&quot;)
  end
end</pre></div></div>
<p>The method creates a new email message with the recipient and subject specified by the options of the plugin. Then it creates a body for the email consisting of information regarding the received commands and at last attaches the log file created during the processing of the commands.</p>
<p>The last call of our script will be <code>RubyBot.deliver_notification(msg, output, logfile)</code>. ActionMailer&#8217;s <code>deliver_<em>something</em></code> will first call <code><em>something</em></code>, that should return an email object, and then will attempt to send the email to the specified recipients.</p>
<p>And that was all for today&#8230;</p>
<blockquote><p>
<strong>Pinky</strong>:  Why?  What are we going to do tomorrow night?<br />
<strong>Brain</strong>:  The same thing we do every night, Pinky.  Try to take over the world!
</p></blockquote>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=20&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/ruby-bot-email-processing/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>send files through email from the command line</title>
		<link>http://weblog.nomejortu.com/shell-script/send-files-through-email-from-the-command-line</link>
		<comments>http://weblog.nomejortu.com/shell-script/send-files-through-email-from-the-command-line#comments</comments>
		<pubDate>Wed, 20 Dec 2006 13:09:15 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=16</guid>
		<description><![CDATA[Every now and then I need to send by email some file to a friend or coworker or even myself. I have found that the easiest way to do this is just having a shell script that do the hard work for you.
After some research I found a set of scripts that actually do what [...]]]></description>
			<content:encoded><![CDATA[<p>Every now and then I need to send by email some file to a friend or coworker or even myself. I have found that the easiest way to do this is just having a shell script that do the hard work for you.</p>
<p>After some research I found a set of scripts that actually do what I want (credit goes to Heiner Steven). The bad news is that this is not a <emph>full-bash</emph> solution. The scripts use the <code>metasend</code> command to send files as MIME atachments.</p>
<p><span id="more-16"></span></p>
<p>This is a easy two-step process. First, you need to install the <strong>metamail</strong> (this is the name of the Debian GNU/Linux package) in your box. Then grab this two scripts (sendfile,  getmimetype). The first one does the call to <code>metasend</code>. From it&#8217;s usage information:</p>
<div class="hl-surround" ><div class="hl-main"><pre>usage: sendfile [-f] [-s subject] [-m mimetype] recipient file ...
    -f:  force sending of mail even for invalid recipients
    -s:  subject of the mail message
    -m:  mime-type (i.e. &quot;application/octet-stream&quot;)

Multiple files may be specified. If no mimetype was given,
it is determined via a call to &quot;getmimetype&quot;.</pre></div></div>
<p>And you are ready to go.</p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=16&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/send-files-through-email-from-the-command-line/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>matar: bloodlust</title>
		<link>http://weblog.nomejortu.com/shell-script/matar-bloodlust</link>
		<comments>http://weblog.nomejortu.com/shell-script/matar-bloodlust#comments</comments>
		<pubDate>Fri, 15 Dec 2006 13:43:18 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=15</guid>
		<description><![CDATA[Here is a tiny script that can be usefull to terminate (kill -9) all the programs which contain a certain string (i.e.: kill all the running copies of ping).
#!/bin/bash

for foo in `ps aux &#124; grep $1 &#124; awk '{print $2}'`;  do kill -9 $foo; done
Just run: matar &#60;program name&#62; and that&#8217;s it. They are [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a tiny script that can be usefull to terminate (<code>kill -9</code>) all the programs which contain a certain string (i.e.: kill all the running copies of <code>ping</code>).</p>
<div class="hl-surround" ><div class="hl-main"><pre>#!/bin/bash

for foo in `ps aux | grep $1 | awk '{print $2}'`;  do kill -9 $foo; done</pre></div></div>
<p>Just run: <code>matar &lt;program name&gt;</code> and that&#8217;s it. They are all gone.</p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=15&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/matar-bloodlust/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>icmp timestamps</title>
		<link>http://weblog.nomejortu.com/shell-script/icmp-timestamps</link>
		<comments>http://weblog.nomejortu.com/shell-script/icmp-timestamps#comments</comments>
		<pubDate>Thu, 14 Dec 2006 18:53:12 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=14</guid>
		<description><![CDATA[The Timestamp is an ICMP (rfc792) message which is used for time synchronization.  The Timestamp Reply  message consists of the originating timestamp sent by the sender of the Timestamp as well as a receive timestamp and a transmit timestamp.
If your machine answers  ICMP Timestamp messages an attacker can learn the date which [...]]]></description>
			<content:encoded><![CDATA[<p>The <em>Timestamp</em> is an <strong>ICMP</strong> (<a href="http://www.faqs.org/rfcs/rfc792.html">rfc792</a>) message which is used for time synchronization.  The <em>Timestamp Reply</em>  message consists of the originating timestamp sent by the sender of the Timestamp as well as a receive timestamp and a transmit timestamp.</p>
<p>If your machine answers  <strong>ICMP</strong> <em>Timestamp</em> messages an attacker can learn the date which is set on your machine. This may help him to defeat all your time based authentication protocols.</p>
<p><span id="more-14"></span><br />
Here is the <a href="http://weblog.nomejortu.com/data/code/bash/icmp-ts.sh">code</a> of a script that can be used to check if a remote host listens <em>Timestamp</em> requests:</p>
<div class="hl-surround" ><div class="hl-main"><pre># Check if the script is being run as root exit if it is not.
if [ &quot;$UID&quot; -ne &quot;0&quot; ]
then
  echo &quot;[ERROR] This script must be run as root&quot;
  exit 1
fi

for foo in $*; do 
  echo -n &quot;$foo &quot;
  output=`hping3 -c 3 --icmp-ts $foo 2&gt;/dev/null | grep &quot;ICMP timestamp&quot; | wc -l`
  if (( output &gt; 0  ))
  then
    echo &quot;reacts to ICMP timestamp.&quot;
  else
    echo &quot;doesn't react.&quot;
  fi
done</pre></div></div>
<p>First we need to check that <code>root</code> is the one running the script because otherwise we won&#8217;t be able to craft <strong>ICMP</strong> packages. For this task we will be using <a href="http://www.hping.org/">hping</a> (i.e: <strong>hping3</strong> package in Debian GNU/Linux).</p>
<p>The script just sends three (<code>-c 3</code>) <strong>ICMP</strong> Timestamps (<code>--icmp-ts</code>) to each of the hosts feeded in the command line. We grep the output of <code>hping3</code> looking for the <em>magic</em> string &#8220;<code>ICMP timestamp</code>&#8220;, and if found, we print a success message.</p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=14&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/icmp-timestamps/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>replace spaces in filename</title>
		<link>http://weblog.nomejortu.com/shell-script/replace-spaces-in-filename</link>
		<comments>http://weblog.nomejortu.com/shell-script/replace-spaces-in-filename#comments</comments>
		<pubDate>Thu, 14 Dec 2006 11:25:33 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Shell Script]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=4</guid>
		<description><![CDATA[Just a quick tip!
You have to use the bash function ${foo//string1/string2}.  Check the Advanced Bash-Scripting Guide for a complete list of string manipulating functions.
for foo in *; do mv &#34;$foo&#34; ${foo// /_}; done
]]></description>
			<content:encoded><![CDATA[<p>Just a quick tip!</p>
<p>You have to use the bash function <code>${foo//string1/string2}</code>.  Check the <a href="http://www.tldp.org/LDP/abs/html/refcards.html">Advanced Bash-Scripting Guide</a> for a complete list of string manipulating functions.</p>
<div class="hl-surround" style="height:28px;"><div class="hl-main"><pre>for foo in *; do mv &quot;$foo&quot; ${foo// /_}; done</pre></div></div>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=4&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/replace-spaces-in-filename/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>kde desktop background auto change</title>
		<link>http://weblog.nomejortu.com/shell-script/kde-desktop-background-auto-change</link>
		<comments>http://weblog.nomejortu.com/shell-script/kde-desktop-background-auto-change#comments</comments>
		<pubDate>Thu, 14 Dec 2006 11:21:26 +0000</pubDate>
		<dc:creator>etd</dc:creator>
				<category><![CDATA[Shell Script]]></category>
		<category><![CDATA[X Windows]]></category>

		<guid isPermaLink="false">http://weblog.nomejortu.com/?p=10</guid>
		<description><![CDATA[Much in the way we did with xfce here is the way to implement de auto change feature in KDE.
This is an easy one. Although you can perform background auto change from KDE control center, it may be usefull to have a script to do the task. You can use this script to create a [...]]]></description>
			<content:encoded><![CDATA[<p>Much in the way we did with <a href="http://weblog.nomejortu.com/?p=2">xfce</a> here is the way to implement de <em>auto change</em> feature in <a href="http://www.kde.org/">KDE</a>.</p>
<p>This is an easy one. Although you can perform background auto change from KDE control center, it may be usefull to have a script to do the task. You can use this script to create a link in your desktop to change the background image when you want.</p>
<p>The KDE applications can be controlled by scripts via the <a href="http://developer.kde.org/documentation/other/dcop.html">DCOP</a> mechanism. From the <a href="http://en.wikipedia.org/wiki/DCOP">Wikipedia</a>:</p>
<blockquote><p>
DCOP, which stands for Desktop COmmunication Protocol, is a light-weight interprocess and software componentry communication system. The main point of this system is to allow applications to interoperate, and to share complex tasks. Essentially, DCOP is a &#8216;remote control&#8217; system, which allows an application or a script to enlist the help of other applications. It is built on top of the X Window System&#8217;s Inter-Client Exchange protocol.</p></blockquote>
<p><span id="more-10"></span><br />
Let&#8217;s begin with the script, here is the <a href="http://weblog.nomejortu.com/data/code/bash/kde-desktop">code</a>:</p>
<div class="hl-surround" ><div class="hl-main"><pre>#!/bin/bash
dcop kdesktop KBackgroundIface changeWallpaper</pre></div></div>
<p>Now, you have to create a list of backgrounds using KDE&#8217;s control center. First open <code>kcontrol</code>, browse to  <code>Appearance &#038; Themes > Background</code> and select <code>Slide Show</code>. Click on <code>Settings</code></p>
<p><img src="http://weblog.nomejortu.com/data/img/kdebackgroundlist.jpg" alt="Slide Show Settings - list of backgrounds " /></p>
<p>Just create the list, and the script is ready to go.</p>
<img src="http://weblog.nomejortu.com/?ak_action=api_record_view&id=10&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://weblog.nomejortu.com/shell-script/kde-desktop-background-auto-change/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
