Sieve of Eratosthenes

Since I had a bad experience with the Sieve of Eratosthenes during a college test I sort of became traumatized with it and tried to avoid it. During this holiday break I decided to tackle on it and I successfully implemented it ruby (not very idiomatic but ruby still)

My favorite parts of this algorithm were:

  • The fact that I don’t have to iterate the whole sieve! I can do it just for sqrt(n) since the factors of any number are always composed by two numbers and one of them is always lower than the sqrt of any given number n.
  • The usage of ruby’s inline if statements

Now I can happily say, my trauma over this is over 🙂

An important note about slices in Go

I’m new in Go and this seems important so it’s better to digest it and point it out.

A slice is not an array. A slice describes a piece of an array.
Its internal structure can be illustrated as the following:

    type sliceHeader struct {
        Length        int
        ZerothElement *byte //Assuming that the array that we are pointing to has byte type.

It’s important to note that there is a pointer inside the structure, but what implications can that have?
Let’s check the following example:

  func AddOneToEachElement(slice []byte) {
      for i := range slice {
  func main() {
        slice := buffer[10:20]
        for i := 0; i < len(slice); i++ {
            slice[i] = byte(i)
        fmt.Println("before", slice)
        fmt.Println("after", slice)


    before [0 1 2 3 4 5 6 7 8 9]
    after [1 2 3 4 5 6 7 8 9 10]

So, slice is passed as value, that means that the slice that is inside AddOneToEachElement is a copy from the slice in main, right? so will the output in after calling that function will be the same? after all it's just a copy isn't it? Yes it's a copy but a copy containing a pointer, that means that even to copy will have access to the original referenced data, that implies the following affirmation: "The content of a slice can be modified"
But what happens if I do the following?

    func SubtractOneFromLength(slice []byte) []byte {
        slice = slice[0 : len(slice)-1]
        return slice

    func main() {
        fmt.Println("Before: len(slice) =", len(slice))
        newSlice := SubtractOneFromLength(slice)
        fmt.Println("After:  len(slice) =", len(slice))
        fmt.Println("After:  len(newSlice) =", len(newSlice))

The creation of a slice inside the subtraction function implies a new allocation, that means a new place to point, but wait a minute, am I allowed to modify the pointer inside my head structure? well for sure the program will compile and run but the behavior won't be the one that we expect, the output will be:

    Before: len(slice) = 50
    After:  len(slice) = 50
    After:  len(newSlice) = 49

And that means: "The contents of a slice argument can be modified by a function, but its header cannot."

It's important to keep this in mind to be aware of unexpected behaviors while we are working.
If you are an experienced Go programmer you may find this example familiar, it took it from here.

Hope it helps anyone in the way that writing this helped me to understand it 🙂

A Client / Server prototype in Go

I started hacker school two weeks ago, one of my goals during this time is become proficient in go or golang. So to get hands towards that goal I started working on “A tour of Go”, I’ve managed to get trough all the tour and became some way comfortable with the language and at that point I decided to start a small project looking for enlightenment and of course my “Eureka moment” in Go.

The project started as an FTP client, but it quickly evolved in a Client / Server conversation, a limited conversation. As a client you are able to connect to an IP:PORT server and send three commands to the server: {1: ls, 2: who, 3: pwd}. As a server you are able to bind a port on your localhost and listen, execute and resolve (return) the requests of the client. The server is able to support multiple clients and request at the same time thanks to Goroutines.

So, what challenges I’ve faced during this project? well, being my first project in go the simple fact to make the program compile was a challenge in the beginning but my concerns quickly evolved as my understanding of the language too. Maybe one of the “really think about” parts of the project was the for loop which allows me to read a response from the server:

readed := 0
response := make([]byte, 8)

for {
    //Read from server
    readed, err = con.Read(response)
    if readed != len(response) {
    //Read request from keyboard
        fmt.Print("ftp> ")
        _, err = fmt.Scanf("%s", &request)
     if request == "quit" {
     //Send to server
     _, err = con.Write([]byte(request))
     //Valid terminated string
     _, err = con.Write([]byte("\r"))
    if err != nil {
        return fmt.Errorf("Interact error: %s", err)
    response = make([]byte, 8)

When am I going to stop? how do I know that all the data has been received and the request finished? Well, the previous code addresses all that concerns and works as long as it receives a header from the server, that means the header has to write first.

I can happily conclude that this project teach me a lot of Go, I feel way more confortable at the language now than two weeks ago (self.go==NULL) I know that maybe this isn’t the best go code that the world has ever seen but I can feel myself learning and at this point I’m happy with that, now I’ll be back to work!

If you are interested, here is the Github repo of the project.


Connect to Airport Extreme Shared Disk from Linux

Recently I bought an Apple Airport Extreme to improve my house WiFi network, the result was remarkable, my old access point signal wasn’t able to reach all rooms on the house but the Airport Extreme performed very well on this task.

Anyway, as you know, you are allowed to share a hard drive using the network created by the Airport, and since one of my computers runs only Linux (on #! flavor) I decided to modify my fstab file in order to auto mount my Airport shared drive and access to it on this Linux box.

The process is quite simple:

marin@Corsair$> sudo mkdir /media/airport
marin@Corsair$> sudo vim /etc/fstab

Add the following information at the end of that file (in one line):

/media/airport/ cifs auto,

And then auto mount your new fstab entry using:

marin@Corsair$> sudo mount -a

That’s all!

Violent Python Chapter #1 Final

And that’s all for the chapter #1! The last exercise was quite easy after the ones before. It is a Zip File cracker. It uses a dictionary attack, hope you like it.

# Violent Python
# Chapter #1
# Exercise #3 Zip file cracker
# By: Marin Alcaraz

import zipfile
import sys

def decrypt_file(filename):
    zFile = zipfile.ZipFile(filename)
    dict_file = open("dict.txt", 'r')
    print "[*] Decrypting file..."
    for line in dict_file.readlines():
        password = line.strip('\n')
            return password
        except Exception, e:

def main():

    if (len(sys.argv) == 2):
        filename = sys.argv[1]
        p = decrypt_file(filename)
        if p:
            print "[+] Password[" + p + "]"
        print "Usage: python"

if __name__ == '__main__':

Violent Python Chapter #1 Part 2

I’ve finished the second exercise from the Chapter #1 “The cuckoo’s egg” it’s a password decrypter. It uses dictionary method and sha512.
Here’s the code:

# Violent Python Chapter #1
# The Cuckoo's Egg: a simple password decrypter
# By: Marin Alcaraz

import crypt
import hashlib

def testPass(cryptPass):
    salt = cryptPass[0:2]
    dictFile = open('dictionary.txt', 'r')
    for word in dictFile.readlines():
        word = word.strip('\n')
        cryptWord = crypt.crypt(word, salt)
        if (cryptWord == cryptPass or hashlib.sha512(word) == cryptPass):
            print "[+] Found Password: " + word + "\n"
    print "[-] Password not found.\n"

def main():
    passFile = open("passwords.txt", 'r')
    for line in passFile.readlines():
        if ":" in line:
            user = line.split(':')[0]
            cryptPass = line.split(':')[1].strip(' ')
            print "[*] Cracking Password for: user[" + user + "]\n"

if __name__ == "__main__":

Violent Python Chapter #1 Part 1

Violent Python Chapter #1

I’ll try to post a little brief about violent python chapters here.
This is the first part of chapter #1.

As any Python book “Violent Python” starts with the basic Python stuff, a quick review to
the well known basics: variables, data types, control flow, etc…
The difference with this book and what makes it cool is the purpose of the book and the
examples. Violent Python is oriented to pentest topics so the examples are related to it.

In chapter one you work on three mini projects:

  • Vulnerability Scanner
  • The Cuckoo’s egg
  • Zip file Cracker

This is my first mini-project: Vuln Scanner:

# Violent Python Chapter #1
# Vuln Scanner
# By: Marin Alcaraz

import sys
import os
import socket

def retBanner(ip, port):
        s = socket.socket()
        s.connect((ip, port))
        banner = s.recv(1024)
        return banner
    except Exception, e:
       return  str(e)

def checkFile(filename):
        if not os.path.isfile(filename):
            raise Exception("File doesn't exist")
            return -1
        if not os.access(filename, os.R_OK):
            raise Exception("Permission Denied")
        f = open(filename, 'r')
        return f
    except Exception, e:
        print str(e)
        return -1

def checkVulns(banner, filename):
    print "[+] Reading Vulnerable Banner list from: " + filename
    f = checkFile(filename)
    for line in f.readlines():
        print "[+] Checking for banner: " + line.strip('\n')
        if line.strip('\n') in banner:
            print "[+] Server is Vulnerable: " + banner.strip('\n')
            print '[-] FTP Server is not vulnerable'

def main():
    portList = [21, 22, 25, 80, 110, 443]
    if (len(sys.argv) == 2):
        filename = sys.argv[1]
        filename = "vuln_banners.txt"
    for x in range(1, 255):
        ip = '192.168.95.' + str(x)
        for port in portList:
            banner = retBanner(ip, port)
            if banner:
                print '[+] ' + ip + ': ' + banner
                if (checkVulns(banner, filename) == -1):

if __name__ == '__main__':


  • Python reserves memory space for variables when programmer declares them. Python interpreter decides the type of the variable. You can get the type of a variable via type() function.
  • Python string module provides a very robust series of methods for strings.
  • The list data structure in Python provides an excellent method for storing arrays of objects. The list can be from any type. There are many built in methods to manipulate the list.
  • The Python dictionary provides a hash table that can store any number of Python objects. It follows the classic key->value method. You can get the available keys via the .keys() function, you are also able to verify the existence of one key with has_key() or see the whole list with items(). Direct access to the elements is provided via data[‘key’] scheme.
  • The socket module provides a library for making network connections using Python.
  • Python provides exception handling capability with try and except.
  • The keyword def() begins a function, the variables between de () are passed by reference meaning that any changes to these variables inside the function will affect their value from the calling function.
  • Python provides an easy way to interact with files through the open() and readlines functions. Full i/o API is of course available at Python’s website.
  • The built in sys modules provides access to objects used or maintained by the Python interpreter. Ex: argv.
  • OS module allows Python to communicate with local OS library.

Django-Vim code autocomplete

Recently I came back on Django development and after a year my own set of coding tools had changed a lot, mainly because Vim became my main text editor. On this came back many of my friends suggested PyCharm as the right tool to use (I’m working as Django developer) but I just can’t work with an IDE, it just doesn’t feel smooth and fast as Vim.

So, if you are like me and love Vim a simple wrapper will transform Vim into a more powerful tool to work with Django and Python, but before we set up the wrapper we have to configure some things inside or .vimrc:


filetype plugin on
set omnifunc=syntaxcomplete#Complete
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS

"--SuperTab Integration
set completeopt-=previewtj
let g:SuperTabDefaultCompletionType = ""
let g:SuperTabDefaultCompletionType = "context"

First lines are activating the Omni Completion feature of Vim for those type of files and the last lines are very helpful and comfortable to work with Super Tab which must be inside of our .vim folder.

Now we will be able to define or little wrapper which I built based on a few examples that I found over the internet, those examples were not working for me but once I understood the idea it was very easy to code.

paste this lines inside a file called djvim (DON’T FORGET TO MODIFY YOUR PROJECT PATH):

if [ $# -eq 2 ]
        export PYTHONPATH="$PROJECT_PATH/$1"
        export DJANGO_SETTINGS_MODULE=$1.settings
        vim $2
        echo "Usage: djvim [Project] [File]"

then make the file executable and move it to your /bin folder, that will do the trick. Test djvim with:

user@machine:$ djvim myproject

and inside Vim type:

:python from django import db

Then test the autocomplete with some functions, launch it with the Tab key.

if it doesn’t work you can check out my dotfiles repo and use them as personal files or guide. Happy Coding, improvements are always welcome