Powershell random password generator – with complexity!

Recently we needed to automate password randomization for account creation purposes. In order to ensure the password policy was met we needed, 8 characters total, 1 uppercase letter, 1 number, and 1 special character. We also needed to control the character set of special characters due to certain finicky applications. This script grabs a base password from http://random.org, verifies that it has all but our special character, and finally randomly inserts one of our special characters into the password.

Function Get-Seed{
# Generate a seed for future randomization
$RandomBytes = New-Object -TypeName 'System.Byte[]' 4
$Random = New-Object -TypeName 'System.Security.Cryptography.RNGCryptoServiceProvider'
[BitConverter]::ToInt32($RandomBytes, 0)

$initialPW = $(Invoke-RestMethod https://www.random.org/passwords/?num=1&len=7&format=plain&rnd=new) -replace "`n"

if($initialPW -cmatch "[A-Z]") { $containsUpper = $True } else { $containsUpper = $False }
if($initialPW -cmatch "[a-z]") { $containsLower = $True } else { $containsLower = $False }
if($initialPW -match "[0-9]") { $containsNumbr = $True } else { $containsNumbr = $False }

$specCharArray = [Char[]]"!#$&*_-"
$specChar = $($specCharArray | Get-Random -Count 1)

if (($containsUpper -eq $True) -and ($containsLower -eq $True) -and $($containsNumbr -eq $True))
$seed = $(Get-Random -Maximum 7 -Minimum 1 -SetSeed $(Get-Seed))
While ($True)

Puppet: Passing a hash of variables to a defined type

One of the more interesting challenges I had recently involved a bit of automation with regard to user creation. If you’ve ever tried to automate resource creation with either defined types or classes, the nuances of puppet can be a bit of a pain, but they can also be very powerful. Here’s an example of a defined type that can execute an arbitrary number of commands with any number of variables (We just happen to be importing certificates in this example):

First the defined type:

define import_certs($cert_path, $cert_name) {
  exec {"Import $cert_name":
    command => "/usr/bin/certutil -A -d /path/to/certificate/db -a -i ${cert_path} -t C,C,C -n \"${cert_name}\"",

As you can see the type accepts 2 variables, $cert_path and $cert_name. Certutil requires a friendly name and this allows us to name our certificates appropriately. NOTE: that double quotes are required for variable interpolation (This bit me a couple of times). Now let’s take a look at how to pass a hash to this defined type so that we can import as many certificates as needed:

In your declaration, you end up creating a hash of hashes and pass the defined type the entire hash of hashes using “create_resources”:

$my_certificates = {
  certificate_file_1 => { cert_path => '/path/to/certificate/file', cert_name => 'Friendly Certificate Name' },
  certificate_file_2 => { cert_path => '/path/to/certificate/file', cert_name => 'Friendly Certificate Name' },
  certificate_file_n => { cert_path => '/path/to/certificate/file', cert_name => 'Friendly Certificate Name' },

create_resources(import_certs, $my_certificates)

As you can see, this is a quick and dirty way to shove a lot of certificates into a database (For a browser perhaps). Of course the limits are boundless, I know this will come in handy again in the future so I put it on <virtual> paper.

Open vSwitch: basic initial setup on Ubuntu 12.04

Software defined networking is all the rage these days in IT, and Open vSwitch is where most people get their first introduction. Whether you’re running KVM or Xen, Open vSwitch will allow you to abstract network setup functions from the hypervisor. Here’s a quick guide to setting up Open vSwitch and replacing a physical interface with a virtual one:
Continue reading

haproxy + keepalived – the free HA load balancer

Load balancers are cool, especially free ones. haproxy and keepalived together can give you a simple HA load balancer at the cost of the hardware you run it on. Here’s how to setup a basic active/passive load balancer with haproxy and keepalived. First the environment:
Continue reading

Galera / WSREP – MySQL cluster on Ubuntu 12.04 LTS – basic initial setup

mysql-logoIt took me about 4 hours of actual research, and trial and error, however I finally got a working Galera based WSREP MySQL cluster up and running. Here’s what it took and how the pieces came together:

Getting the install right took a couple of hours by itself for some reason, here’s the order that worked best on Ubuntu 12.04 LTS:
Continue reading

OpenStack API python script example

Recently I was given a number of API test cases for OpenStack to manually execute via curl. It was quite tedious figuring out the nuances of the OpenStack API using curl; manually constructing HTTP headers and substituting JSON values into a curl command got old real fast. I decided to run all the test cases through python, this was the first bit I had to finish, authentication!

OpenStack API call requesting a token. Tokens are valid for authentication for 24 hours:


import argparse
import getopt
import json
import sys
import urllib2

def getToken(url, osuser, ostenant, ospassword):

    Returns a token to the user given a tenant,
    user name, password, and OpenStack API URL.

    url = url + '/tokens'
    tokenRequest = urllib2.Request(url)
    tokenRequest.add_header("Content-type", "application/json")
    jsonPayload = json.dumps({'auth' : {'tenantName' : ostenant, 'passwordCredentials' : {'username' : osuser, 'password' : ospassword}}})
    request = urllib2.urlopen(tokenRequest, jsonPayload)
    json_data = json.loads(request.read())
    return json.dumps(json_data)

# Build our required arguments list
parser = argparse.ArgumentParser()
mandatory = parser.add_argument_group("mandatory")
mandatory.add_argument("-l", "--login", help="The administrative user for your OpenStack installation", type=str)
mandatory.add_argument("-p", "--password", help="The administrative user's password", type=str)
mandatory.add_argument("-t", "--tenant", help="The administrative user's tenant / project", type=str)
mandatory.add_argument("-u", "--url", help="The Keystone API endpoint from running, 'nova endpoints'", type=str)
args = parser.parse_args()

# Validate arugments were given
if type(args.url) != type(str()):
    sys.stderr.write('Invalid URL: %s\n' % args.url)
if type(args.tenant) != type(str()):
    sys.stderr.write('Invalid tenant: %s\n' % args.tenant)
if type(args.password) != type(str()):
    sys.stderr.write('Invalid password: %s\n' % args.password)
if type(args.login) != type(str()):
    sys.stderr.write('Invalid login: %s\n' % args.login)
# Since we return a raw JSON payload from getToken,
# we need to load it into a readable object.
adminToken = json.loads(getToken(args.url, args.login, args.tenant, args.password))

# Access the token portion of the JSON payload and grab the token and tenant ID
adminTokenID = adminToken['access']['token']['id']
adminTokenTenantID = adminToken['access']['token']['tenant']['id']

for item in adminToken['access']['serviceCatalog']:
    The "name" of each OpenStack service catalog item from
    the item list changed between versions.  Things like
    "glance" became "volume" and "keystone" became "identity".  
    You will need to update this based on your installation.

    if item['name'] == "nova":
        adminNovaURL = item['endpoints'][0]['adminURL']
    if item['name'] == "glance":
        adminGlanceURL = item['endpoints'][0]['adminURL']
    if item['name'] == "nova-volume":
        adminVolumeURL = item['endpoints'][0]['adminURL']
    if item['name'] == "ec2":
        adminEc2URL = item['endpoints'][0]['adminURL']
    if item['name'] == "swift":
        adminSwiftURL = item['endpoints'][0]['adminURL']
    if item['name'] == "keystone":
        adminAuthURL = item['endpoints'][0]['adminURL']

print "------ Admin information ------"
print "Token ID = ", adminTokenID
print "Tenant ID = ", adminTokenTenantID
print "Nova URL = ", adminNovaURL
print "Glance URL = ", adminGlanceURL
print "Volume URL = ", adminVolumeURL
print "EC2 URL = ", adminEc2URL
print "Swift URL = ", adminSwiftURL
print "Keystone URL = ", adminAuthURL
print "------ End Admin info ---------"

When passed the appropriate parameters, this script will print your environment information in a nice readable format:

uesr@localhost:~$ ./token.py -l admin -t admin -p password -u http://localhost:35357/v2.0
------ Admin information ------
Token ID =  abc123def456ghi789jkl012mno345pq
Tenant ID =  qp543onm210lkj987ihg654fed321cba
Nova URL =  http://localhost:8774/v2/qp543onm210lkj987ihg654fed321cba
Glance URL =  http://localhost:9292/v1
Volume URL =  http://localhost:8776/v1/qp543onm210lkj987ihg654fed321cba
EC2 URL =  http://localhost:8773/services/Admin
Swift URL =  https://localhost:8080/v1/
Keystone URL =  http://localhost:35357/v2.0
------ End Admin info ---------

Hack the planet automobile?

I’ve been complaining to the wife that her car’s infotainment system is behind the curve a bit. This is an attempt to help spread the word about Automotive Grade Linux (AGL), and perhaps aid the open-source automotive community a bit. Here’s an excerpt from an article posted on wired:

The major roadblock to the rapid adoption of technology in cars has always been vehicles’ long production cycles. But automakers are also guilty of hampering wide-scale innovation with their proprietary approach to infotainment systems and software, while dragging their feet on a collaborative, open source solution that would benefit consumers and car tech overall.

Read the full post here.