How To: Use PHP to Change a Bluehost Email Account Password

This is a PHP script I wrote that allows you to incorporate an email password update option into your own webpage styling. Normally, with Bluehost (and FastDomain and HostMonster), your users can only change their email account password by either having the admin login to their cpanel and changing it for them, or by accessing the Bluehost provided webmail interface. Neither are very inviting solutions, especially in a professional environment.

The script works by accessing the shadow file associated with the email account’s domain name. It looks for the username whose password is being changed in the shadow file and, if found, compares the password stored in the shadow file with the password that the user enters as their current password. If those passwords match, it then updates the shadow file with the users’ new password. The password is stored in the shadow file as a Base64 encoded salted MD5 hash which is generated using either the PHP crypt function (if available) or the openssl command line.

This script will work out of the box, however, I recommend using it with the current visual theme of your website otherwise you’re defeating the purpose. The hidden input field named “domain” may be edited so that users only have to enter the name portion (ie: joesnuffy) of their email address without the domain portion. If left un-edited, your users will be required to enter in the domain portion of their email address along with the name portion (ie: joesnuffy@linuxr0ckz.com).

This script will work with Bluehost, FastDomain, HostMonster (all operated by Bluehost) and I’m guessing it will also work with any other host that uses cpanel (unverified).

<?php

$message = "";
$found = $valid = false;

if (isset($_POST['username']) && $_POST['username'] != "") {
    $domain_pos = strpos($_POST['username'], "@");
    if ($domain_pos === false) {
        $username = $_POST['username'];
        $domain = $_POST['domain'];
    } else {
        $username = substr($_POST['username'], 0, $domain_pos);
        $domain = substr($_POST['username'], $domain_pos + 1);
    }
    
    $current_password = $_POST['current_password'];
    $new_password1 = $_POST['new_password1'];
    $new_password2 = $_POST['new_password2'];
    
    $root = $_SERVER['DOCUMENT_ROOT'];
    $path_elements = explode('/', $root);
    $root = "/{$path_elements[1]}/{$path_elements[2]}"; // for bluehost, extracts homedir ex: /homeN/blueuser may work with other hosts?
    $shadow_file = "$root/etc/$domain/shadow";

    // check if the shadow file exists. if not, either an invalid
    // domain was entered or this may not be a bluehost account...?
    if (file_exists($shadow_file)) {
        // compare the new passwords entered to ensure they match.    
        if ($new_password1 == $new_password2) {
            if (trim($new_password1) != "") {
                // get the contents of the shadow file.
                $shadow = file_get_contents($shadow_file);
                $lines = explode("\n", $shadow);
                
                // go through each line of shadow file, looking for username entered.
                for ($i = 0; $i < count($lines); $i++) {
                    $elements = explode(":", $lines[$i]);
                    // found the user...
                    if ($elements[0] == $username) {
                        $found = true;
                        $passwd = explode("$", $elements[1]);
                        $salt = $passwd[2]; // get the salt currently used 
                        
                        // crypt the "Current Password" entered by user. Can use either builtin 
                        // php crypt function or command line openssl command.
                        if (CRYPT_MD5 == 1) { // indicates whether or not the crypt command supports MD5.
                            $current = crypt($current_password, '$1$'.$salt.'$');
                        } else {
                            $current = trim(`openssl passwd -1 -salt "$salt" "$current_password"`);
                        }
                        // check if the current password entered by the user
                        // matches the password in the shadow file.
                        $valid = ($current == $elements[1]);
                        
                        if ($valid) {
                            // if they match then crypt the new password using the same salt
                            // and modify the line in the shadow file with the new hashed password
                            if (CRYPT_MD5 == 1) {
                                $new = crypt($new_password1, '$1$'.$salt.'$');
                            } else {
                                $new = trim(`openssl passwd -1 -salt "$salt" "$new_password1"`);
                            }
                            $elements[1] = $new;
                            $lines[$i] = implode(":", $elements);
                        }
                        
                        break;
                    }
                }
                
                if (!$found) {
                    $message = "The username you entered is not valid.";
                } else if (!$valid) {
                    $message = "The password you entered is not valid.";
                } else {
                    // write the new contents of the shadow back to the shadow file.
                    $shadow = implode("\n", $lines);
                    file_put_contents($shadow_file, $shadow);
                    $message = 'Your password has been updated.';
                }
            } else {
                $message = "Your password cannot be blank.";
            }
        } else {
            $message = "Both new passwords must match.";
        }
    } else {
        $message = "The domain you entered is not valid.";
    }
}

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
        <title>Change Password</title>
    </head>
    
    <body>            
        <?php
            if ($message != "") {
                $color = $found && $valid ? "green" : "red";
                echo "<span style=\"color:$color;\">$message</span>";
            }
        ?>
        
        <form action="" method="post">
            <input type="hidden" name="domain" value="somebluehostdomain.com" />
            <table>
                <tbody>
                    <tr>
                        <td><label for="username">Username</label></td> 
                        <td><input name="username" id="username" type="text" /></td> 
                    </tr>
                    <tr>
                        <td><label for="current_password">Current Password</label></td> 
                        <td><input name="current_password" id="current_password" type="password" /></td> 
                    </tr>
                    <tr>
                        <td><label for="new_password1">New Password</label></td> 
                        <td><input name="new_password1" id="new_password1" type="password" /></td> 
                    </tr>
                    <tr>
                        <td><label for="new_password2">New Password</label></td> 
                        <td><input name="new_password2" id="new_password2" type="password" /></td> 
                    </tr>
                    <tr>
                        <td colspan="2" style="text-align:center;">
                            <input type="submit" value="Update Password" />
                        </td>
                    </tr>
                </tbody> 
            </table> 
        </form>
    </body>
</html>

Windows 7 as a Wi-Fi Access Point

Ever needed a wireless router but didn’t have one handy? Ever use an ad-hoc wireless network with Internet Connection Sharing to get other devices connected quickly? What if you have say an Android phone with no cell network data connection but really need to connect it to the Internet but don’t have a wireless router handy (Android won’t connect to an ad-hoc network without rooting the device)? Here’s how to setup Windows 7 to act as a Wi-Fi access point (aka infrastructure) for you and anyone else you want to allow to connect. Note: This doesn’t work on Windows 7 Starter Edition as Internet Connection Sharing is not enabled.

  1. Open an elevated command prompt.
  2. Execute the following command, replacing <some_ssid> with an ssid of your choosing and <some_passphrase> with a wpa2 compatible passphrase. If either contain spaces, enclose that portion of the command in quotes:
        netsh wlan set hostednetwork mode=allow <some_ssid> <some_passphrase> persistent
  3. Enable Internet Connection Sharing. See Using ICS (Internet Connection Sharing)
  4. Execute the following command, again using an elevated command prompt:
        netsh wlan start hostednetwork
  5. All done. Your other Wi-Fi devices should now see your wireless network and be able to connect to it.

Note: Using this method to connect an Android device, I could not get T-Mobile Wi-Fi Calling to connect to their service. I’m guessing the double-NAT would’ve caused an issue, although I have been able to connect through a double-NAT before.

Grammar, Spelling and Numbers

Here are some common mistakes people make when writing that bug the crap out of me. I don’t care what degrees you have or how much you think you know, when you make these simple mistakes no one is going to listen to you. I know there are mistakes that I make too, but the following are not them.

  1. The difference between there, their and they’re:
    1. there: a place. She is over there.
    2. their: shows possession of something to someone (the possessive form of they). I left the keys in their car (implies the car belongs to them).
    3. they’re: contraction of they are. They’re not here, they’re over there, in their car.
  2. The difference between your and you’re:
    1. your: the possessive form of you. It’s your house, the carpet belongs to you.
    2. you’re: contraction of you are. It’s your house, you’re responsible for clearing the sidewalk.
  3. When to spell out numbers vs. when to write the number itself:
    1. Spell out numbers that begin a sentence:
      1. Correct: Seventy people went missing today.
      2. Incorrect: 6 pairs of shoes are better than five.
    2. Spell out single digit numbers, not multi-digit numbers, except in the same category:
      1. Correct: I bought five candy bars for my students.
      2. Correct: My 10 cats need to be spayed and neutered.
      3. Correct: I need five Snickers bars and four Mars bars.
      4. Incorrect: I want eight yellow buckets and 12 green buckets. (buckets are in the same category, spell out twelve or write 8.)
  4. Format addresses correctly (use proper case). When on a resume do not use abbreviations:
    1. Correct: 100 N 10th St., Tacoma, WA 98409
    2. Incorrect: 100 n 10 st., tacoma wa 98409
    3. Correct: 1715 E Main, Puyallup, WA 98372
    4. Incorrect: 1715 e Main St., Puyallup, WA 98372
    5. Correct: 1108 E 98th St Ct S, Tacoma, WA 98466
    6. Incorrect: 1108 e 98 st ct s, Tacoma, WA 98466
    7. Correct (on a resume): 1108 East 98th Street Court South, Tacoma, Washington 98466
    8. Incorrect (on a resume) 1108 E 98th St Ct S, Tacoma, WA 98466
  5. Don’t use @ to refer to someone, either by name or handle, unless you’re on twitter:
    1. Correct: SomeCleverHandle, you are exactly right!
    2. Incorrect: @SomeCleverHandle, you are completely wrong!

Collage Generator

I needed to find images of money. I searched the Internet but couldn’t find anything that great or multiple images that were unique but in the same style. I decided to download images of bills from Wikipedia and write my own program to generate a few different collages. Below I’ve included some screen shots of example usages and their corresponding output. Scroll to the bottom of this post to download the program.

Collage Generator v1.0.0 Copyright (c) 2011 Tanner Jepsen

Identify This Cipher

Using cryptographic analysis on a cipher produced by an existing software program, I was able to write my own compatible algorithm for re-producing the cipher. The only trouble is I have no idea which cipher it is. Perhaps combinations of different ciphers or maybe even a new cipher all together? No, I won’t say which software program uses this cipher, but I wonder if anyone can identify and/or classify it. I believe it to be a symmetric key stream cipher–albeit, very weak and very easy to analyze.

Disclaimer: I invoke my right to free speech to post cryptographic source code. See Bernstein v. United States.

Usage Examples:

Console.WriteLine(Convert.ToBase64String("mypassword".Cipher("378518030611953")));
// or
Console.WriteLine("mypassword".Cipher("378518030611953").ToHexString());
// or
Console.WriteLine("mypassword".Cipher(ASCIIEncoding.ASCII.GetBytes("somekey")).ToHexString());

Corresponding Output Examples:

// y8kJikhp6ItISg==
// or
// cbc9098a4869e88b484a
// or
// c5c4a58605c4c785a527

The Code:

using System;
using System.Text;

namespace MyExtensions
{
    public static class Extensions
    {
        public static byte[] Cipher(this string password, string key)
        {
            byte[] cipher = System.Text.ASCIIEncoding.ASCII.GetBytes(password);
            return cipher.Cipher(key);
        }

        public static byte[] Cipher(this string password, byte[] key)
        {
            byte[] cipher = System.Text.ASCIIEncoding.ASCII.GetBytes(password);
            return cipher.Cipher(key);
        }

        public static byte[] Cipher(this byte[] password, string key)
        {
            try
            {
                byte[] k = key.ParseBytes();
                return password.Cipher(k);
            }
            catch (Exception e)
            {
                throw new Exception("The key can consist only of a string of numbers. No letters or special characters.", e);
            }
        }

        public static byte[] Cipher(this byte[] password, byte[] key)
        {
            byte[] cipher = password;
            for (int i = 0; i < cipher.Length; i++)
            {
                int first = 0x09;
                int last = 0xE9;
                int rounds = cipher[i] ^ key[i % key.Length];

                for (int y = 0; y <= rounds; y++)
                {
                    last += 32;
                    if (last > 255) last = first = first + (y % 16 / 2) - 3;
                    if (last < 0) last = first = 14;
                }
                cipher[i] = (byte)last;
            }
            return cipher;
        }

        public static byte[] ParseBytes(this string s)
        {
            return s.ToCharArray().ParseBytes();
        }

        public static byte[] ParseBytes(this char[] data)
        {
            byte[] p = new byte[data.Length];
            for (int i = 0; i < data.Length; i++)
            {
                byte parsed;
                if (!byte.TryParse(data[i].ToString(), out parsed))
                    throw new Exception("The input can only consist of numbers. No letters or special characters.");
                p[i] = parsed;
            }
            return p;
        }

        public static string ToHexString(this byte[] data)
        {
            string s = string.Empty;
            for (int i = 0; i < data.Length; i++)
            {
                s += data[i].ToHexString();
            }
            return s;
        }

        public static string ToHexString(this byte b)
        {
            return Convert.ToString(b, 16).PadLeft(2, "0");
        }

        public static string PadLeft(this string s, int totalWidth, string padding)
        {
            return s.PadLeft(totalWidth, char.Parse(padding));
        }

        public static string PadRight(this string s, int totalWidth, string padding)
        {
            return s.PadRight(totalWidth, char.Parse(padding));
        }
    }
}