Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS 

Ruby password strength calculator

This method returns the password lifetime in years. Based on this:
http://www.codeandcoffee.com/2007/06/27/how-to-make-a-password-strength-meter-like-google

class String
  PASSWORD_SETS = {
    /[a-z]/ => 26,
    /[A-Z]/ => 26,
    /[0-9]/ => 10,
    /[^\w]/ => 32
  }
  
  def password_strength
    set_size = 0
    PASSWORD_SETS.each_pair {|k,v| set_size += v if self =~ k}
    
    combinations = set_size ** length
    
    # assuming 1000 tries per second
    days = combinations.to_f / 1000 / 86400
    
    days / 365
  end
end

Diffie-Hellman key exchange in Ruby

From: http://labs.musecurity.com/2007/05/09/diffie-hellman-in-ruby/
Author: kowsik


class Integer
    # Compute self ^ e mod m
    def mod_exp e, m
        result = 1
        b = self
        while e > 0
            result = (result * b) % m if e[0] == 1
            e = e >> 1
            b = (b * b) % m
        end
        return result
    end

    # A roundabout, slow but fun way of counting bits.
    def bits_set
        ("%b" % self).count('1')
        #to_s(2).count('1')   # alternative
        #count = 0         # alternative
        #byte = self.abs
        #count += byte & 1 and byte >>= 1 until byte == 0     # cf. http://snippets.dzone.com/posts/show/4233
        #count
    end
end


class DH
    attr_reader :p, :g, :q, :x, :e

    # p is the prime, g the generator and q order of the subgroup
    def initialize p, g, q
        @p = p
        @g = g
        @q = q
    end

    # generate the [secret] random value and the public key
    def generate tries=16
        tries.times do
            @x = rand(@q)
            @e = self.g.mod_exp(@x, self.p)
            return @e if self.valid?
        end
        raise ArgumentError, "can't generate valid e"
    end

    # validate a public key
    def valid? _e = self.e
        _e and _e.between?(2, self.p-2) and _e.bits_set > 1
    end

    # compute the shared secret, given the public key
    def secret f
        f.mod_exp(self.x, self.p)
    end
end

alice = DH.new(53, 5, 23)
bob   = DH.new(53, 5, 15)
alice.generate
bob.generate

alice_s = alice.secret(bob.e)
bob_s   = bob.secret(alice.e)
puts alice_s
puts bob_s


Password authentication without revealing your password

The majority of personalized web sites use some kind of form-based password authentication where you have two form fields for username and password, and a login button. When you submit your authentication, the password is sent in the clear to the server for verification against a user database.

Using a Javascript SHA library and one simple onsubmit protects the password in transit and also inside the user database:

<form onsubmit="pwField.value = b64_sha256(pwField.value);">


Read this for more elaborations with increased security.

Better textilize

A better textilize helper that doesn't use the :hard_breaks option of RedCloth, like Rails' built-in textilize does (for whatever reason). Also escapes any HTML entered by the user (instead of dismissing it, as RedCloth's :filter_html option would do).

This my not be what you need, but it's exactly what I need. :)

  def textilize(text)
    RedCloth.new(text.gsub(/</, '&lt;').gsub(/>/, '&gt;')).to_html
  end

Import not trusted certificates into JDK security

// Useful for open an SSL connection to a not trusted site
// keytool is provided by Sun's JDK

keytool -import -trustcacerts -alias <alias> -file <cert_file> -keystore $JAVA_HOME/jre/lib/security/cacerts

securing the /home directory

I'm still working on getting this one perfect.

chmod 701 /home/*
chmod 705 /home/*/public_html
chmod 604 /home/*/public_html/*.*

WWW-Authenticate example

// Shows how to use the WWW-Authenticate header to make login pages.You find a good tutorial at php.net
// (Source: http://codedump.jonasjohn.de/ - Public domain)

<?php

$login_successful = false;

// check user & pwd:
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){

    $usr = $_SERVER['PHP_AUTH_USER'];
    $pwd = $_SERVER['PHP_AUTH_PW'];

    if ($usr == 'jonas' && $pwd == 'secret'){
        $login_successful = true;
    }
}

// login ok?
if (!$login_successful){

    // send 401 headers:
    // realm="something" will be shown in the login box 
    header('WWW-Authenticate: Basic realm="Secret page"');
    header('HTTP/1.0 401 Unauthorized');
    print "Login failed!\n";

}
else {
    // show secret page:
    print 'you reached the secret page!';
}
?>

Random Password Generator

This is a complete, working, random password generator for PHP. It allows the implementor to customize the character sets that the password is generated from.

To configure the generator, create the following configuration array. It is an array of arrays where each element array defines the characters in the pool and the minimum and maximum number of these characters that must appear in the result password. Each member array is given a single character token that identifies it.
// Configuration definitions, move to config.php
$CONFIG['security']['password_generator'] = array(
	"C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 4, 'maximum' => 6),
	"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 1, 'maximum' => 2),
	"N" => array('characters' => '1234567890', 'minimum' => 2, 'maximum' => 2)
);


The GeneratePassword() function uses the configuration array to generate a password. It starts by creating a meta-password, which is a shuffled string of the tokens from the configuration data. After the meta-password is ready, it loops through it and uses each token to choose a character from the pool of available characters defined in the configuration arrays. Once it is done, it returns the result.
function STEM_GeneratePassword()
{
	// Create the meta-password
	$sMetaPassword = "";
	
	global $CONFIG;
	$ahPasswordGenerator = $CONFIG['security']['password_generator'];
	foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
		$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
		
	$sMetaPassword = str_shuffle($sMetaPassword);
	
	// Create the real password
	$arBuffer = array();
	for ($i = 0; $i < strlen($sMetaPassword); $i ++)
		$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];

	return implode("", $arBuffer);
}


--
Version 0.1.0 - 2006-02-14
STEM: The STEM Cells of PHP
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
http://creativecommons.org/licenses/by-sa/2.5/

MSN Messenger Password Decrypter for Windows XP & 2003

// MSN Messenger Password Decrypter for Windows XP & 2003

 /*
 *  MSN Messenger Password Decrypter for Windows XP & 2003
 *  (Compiled-VC++ 7.0, tested on WinXP SP2, MSN Messenger 7.0)
 *      - Gregory R. Panakkal
 *        http://www.crapware.tk/
 *        http://www.infogreg.com/
 */

#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>

#pragma comment(lib, "Crypt32.lib")


//Following definitions taken from wincred.h
//[available only in Oct 2002 MS Platform SDK / LCC-Win32 Includes]

typedef struct _CREDENTIAL_ATTRIBUTEA {
    LPSTR Keyword;
    DWORD Flags;
    DWORD ValueSize;
    LPBYTE Value;
}
CREDENTIAL_ATTRIBUTEA,*PCREDENTIAL_ATTRIBUTEA;

typedef struct _CREDENTIALA {
    DWORD Flags;
    DWORD Type;
    LPSTR TargetName;
    LPSTR Comment;
    FILETIME LastWritten;
    DWORD CredentialBlobSize;
    LPBYTE CredentialBlob;
    DWORD Persist;
    DWORD AttributeCount;
    PCREDENTIAL_ATTRIBUTEA Attributes;
    LPSTR TargetAlias;
    LPSTR UserName;
} CREDENTIALA,*PCREDENTIALA;

typedef CREDENTIALA CREDENTIAL;
typedef PCREDENTIALA PCREDENTIAL;

////////////////////////////////////////////////////////////////////

typedef BOOL (WINAPI *typeCredEnumerateA)(LPCTSTR, DWORD, DWORD *, PCREDENTIALA **);
typedef BOOL (WINAPI *typeCredReadA)(LPCTSTR, DWORD, DWORD, PCREDENTIALA *);
typedef VOID (WINAPI *typeCredFree)(PVOID);

typeCredEnumerateA pfCredEnumerateA;
typeCredReadA pfCredReadA;
typeCredFree pfCredFree;

////////////////////////////////////////////////////////////////////

void showBanner()
{
    printf("MSN Messenger Password Decrypter for Windows XP/2003\n");
    printf("   - Gregory R. Panakkal, http://www.infogreg.com \n\n");
}

////////////////////////////////////////////////////////////////////
int main()
{
    PCREDENTIAL *CredentialCollection = NULL;
    DATA_BLOB blobCrypt, blobPlainText, blobEntropy;

    //used for filling up blobEntropy
    char szEntropyStringSeed[37] = "82BD0E67-9FEA-4748-8672-D5EFE5B779B0"; //credui.dll
    short int EntropyData[37];
    short int tmp;

    HMODULE hDLL;
    DWORD Count, i;

    showBanner();

    //Locate CredEnumerate, CredRead, CredFree from advapi32.dll
    if( hDLL = LoadLibrary("advapi32.dll") )
    {
        pfCredEnumerateA = (typeCredEnumerateA)GetProcAddress(hDLL, "CredEnumerateA");
        pfCredReadA = (typeCredReadA)GetProcAddress(hDLL, "CredReadA");
        pfCredFree = (typeCredFree)GetProcAddress(hDLL, "CredFree");

        if( pfCredEnumerateA == NULL||
            pfCredReadA == NULL ||
            pfCredFree == NULL )
        {
            printf("error!\n");
            return -1;
        }
    }
    

    //Get an array of 'credential', satisfying the filter
    pfCredEnumerateA("Passport.Net\\*", 0, &Count, &CredentialCollection);


    if( Count ) //usually this value is only 1
    {

        //Calculate Entropy Data
        for(i=0; i<37; i++) // strlen(szEntropyStringSeed) = 37
        {
            tmp = (short int)szEntropyStringSeed[i];
            tmp <<= 2;
            EntropyData[i] = tmp;
        }

        for(i=0; i<Count; i++)
        {
            blobEntropy.pbData = (BYTE *)&EntropyData;
            blobEntropy.cbData = 74; //sizeof(EntropyData)

            blobCrypt.pbData = CredentialCollection[i]->CredentialBlob;
            blobCrypt.cbData = CredentialCollection[i]->CredentialBlobSize;

            CryptUnprotectData(&blobCrypt, NULL, &blobEntropy, NULL, NULL, 1, &blobPlainText);
            
            printf("Username : %s\n", CredentialCollection[i]->UserName);
            printf("Password : %ls\n\n", blobPlainText.pbData);
        }
    }

    pfCredFree(CredentialCollection);
}

Very minimal security of remote file fetching on Linux

Basic stuff, but stops bad users being able to grab stuff they shouldn't.

chmod 750 /usr/bin/rcp 
chmod 750 /usr/bin/wget 
chmod 750 /usr/bin/lynx 
chmod 750 /usr/bin/links 
chmod 750 /usr/bin/scp
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS