Saturday, January 9, 2010

Calling GPG from PHP

I fell into the trap of just looking at the top result on google for calling PGP or GnuPG from a PHP script. After trying them I realized they are bad examples, and so are the next few results. Calling gpg using exec or even writing the data or private key passphrase to a file introduces unnecessary risks. It allows other users on the system to run ps and see you echo the data or passphrase to gpg. If you save the data to a file first then they can see where you are putting the files and attempt to read them before you encrypt them. The gpg process should be called using the proc_open command which will allow you to run gpg without using echo on the command line or writing unencrypted data to files. It will be sending it directly to the standard input stream of gpg. This is especially important if you do not have the ability to install GnuPG PHP libraries that already use this technique.

Using proc_open the ps command can see:
gpg -e -r 'Recipient'
Using exec the ps command can see:
echo SECRET | gpg -e -r 'Recipient'

Which one would you rather have?

Below i've provided some example code that can call gpg with proc_open. It will return the gpg result or the word "error" if there has been some kind of gpg error that did not produce a result.


/*---------------------------------------------------------------------------*/
// encrypt_command
//
// sends data to encrypt to stdin, returns result code
//
// expects a gpg command like
// /usr/bin/gpg --homedir /path/to/.gnupg --armor --batch -e -r 'Recipient'
//
/*---------------------------------------------------------------------------*/
function encrypt_command ($gpg_command, $data)
{
$descriptors = array(
0 => array("pipe", "r"), //stdin
1 => array("pipe", "w"), //stdout
2 => array("pipe", "w"), //stderr
);

$process = proc_open($gpg_command, $descriptors, $pipes);

if (is_resource($process)) {
// send data to encrypt to stdin
fwrite($pipes[0], $data);
fclose($pipes[0]);

// read stdout
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

// read stderr
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);

// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_code = proc_close($process);

$return_value = trim($stdout, "\n");
//echo "$stdout";

if (strlen($return_value) < 1) {
$return_value = "error: $stderr";
}

}

return $return_value;

}

/*---------------------------------------------------------------------------*/
// decrypt_command
//
// sends passphrase to stdin, returns decrypted data
//
// expects a gpg command like:
// /usr/bin/gpg --homedir /path/to/.gnupg --passphrase-fd 0 --decrypt file.gpg
//
/*---------------------------------------------------------------------------*/
function decrypt_command ($gpg_command, $passphrase)
{

$descriptors = array(
0 => array("pipe", "r"), //stdin
1 => array("pipe", "w"), //stdout
2 => array("pipe", "w"), //stderr
);

$process = proc_open($gpg_command, $descriptors, $pipes);

if (is_resource($process)) {
// send passphrase to stdin
fwrite($pipes[0], $passphrase);
fclose($pipes[0]);

// read stdout
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);

// read stderr
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);

// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_code = proc_close($process);

$return_value = trim($stdout, "\n");
//echo "$stdout";

if (strlen($return_value) < 1) {
$return_value = "error: $stderr";
}

}

return $return_value;
}

Sunday, November 15, 2009

The Paleo Diet

For the past month or two i've been following the paleo diet for athletes. The paleo diet is based on the types of foods humans ate during the stone age, before the agricultural revolution 20,000 years ago. This menu includes lean meats, poultry, fish, fruits and vegetables. It removes dairy, grains, and refined sugars. Since this is the athlete version there is also a recommendation for what to eat before, during and after workouts. Foods and sports drinks that are able to be digested during exercise and help maintain the body's performance.

I've had good success with this style of eating, and it has changed how I look at food. So much of the food in the aisles of the supermarket is not really what humans evolved to eat. When I go food shopping now I only have to go to a couple sections and can skip over many aisles. I load up my cart with fruits and vegetables then head to the meat/poultry/fish section and i'm done.

Most of the things I try and cook simply. Now and then i'll add some spices or easy sauces. For breakfast today I had a two egg omelette with diced onions and green peppers. I also had an orange and a banana. For lunch I had a salad and baked chicken. I had an apple for a snack later. Lunch was a few hours ago and I'm just starting to get a little hungry, so maybe i'll go hunt and gather some dinner soon. Tomorrow after my workout i'm going to make a strawberry banana smoothie, they taste so good, those things are like ice cream to me now! - and with frozen strawberries you can still get the brain freeze. I'm a caveman with a blender!

Monday, September 21, 2009

TDD Triathlon Race Report

This was my second triathlon and I was really looking forward to trying out my new wetsuit in the swim. It took place at the Douglas State Forest, a place I am familiar with because I hiked part of the Mid-State trail there last year. Saturday morning I arrived early and got a prime parking spot right near the entrance. Since it was so early I just wandered around the beach area for a while until the line formed to get race numbers.

After I got my number I got all my stuff over to the transition area, put my bike on the rack, and laid out my stuff next to my bike. I got my bearings in transition and then practiced going from the water to my bike so I know exactly where it is and won't get lost on my way there.

About 20 minutes before the start I put on my wetsuit and got in the water to see what the water was like. The water was fairly warm on such a cold morning, probably warmer than the air. This was also my first time racing in a wetsuit and I was eager to find out what my time would be like.

Then they had us all line up on the beach to start in waves for the 1/4 mile swim. I stayed on the side and near the back of my wave. My wave went first running into the water from the beach. I guess it's not surprising, but I didn't realize how difficult it would be to run through the water to where it was deep enough to start swimming. I held back for 5 or 10 seconds so I wouldn't end up hitting the feet of the people in front of me. Jumped in and got to the first buoy, swimming in a heads up style almost the whole way since so many people were around me. After the first turn it thinned out and I could put my head down and go a bit faster. I only just recently got enough coordination to more comfortably go between breathing every third stroke and every other stroke to take air more often, so that helped me keep a faster pace and not have to pause to catch my breath as much.

When i got out of the water there was a long run through the grass to the transition so I had ample time to get my arms an shoulders out of my wetsuit as I ran. I got to my bike and pulled off the wetsuits legs. I think the body glide on my ankles here helped a lot when getting it off. I put on my bike shoes, going sockless this time since I had been practicing without socks to help make transition faster. I dried my face and hair with my towel, put on my bike helmet, glasses, and bike gloves and ran out of transition with my bike.

The 11 mile bike course was quite hilly and they started right away with a gradual climb. I tried to conserve my energy on the hills and keep it in reserve so I could change into a higher gear at the top of the hill and cruise down the other side in the aero bars. This was my first race with aero bars and they came in very useful going down hill, though I didn't use them as much as I though I might since there the course was kind of crowded in spots and I wanted to be on the brakes. On the final down hill stretch I hit about 35mph, the fastest i've gone on the bike yet!

There was a dirt path one had to ride down to get to transition and I nearly wiped out on the dirt and gravel on my bike before dismounting. Narrow road tires don't like dirt gravel paths. Somehow I managed to stay upright and I got into transition and got pulled off my bike stuff and slipped into my running shoes. No socks here either, and I had bungie laces too which I think helped me cut a bit off my T2 time. As I was running for the exit I realized I still had my bike gloves on, so I turned around ran back to my area to pull them off, lost some time there. I realize now I probably could have just stuffed them in my jersey pockets and saved some time. The 3 mile run started out going up the same first long hill as the bike. My running legs didn't seem to adapt as quickly as I thought they would and felt tight during the whole first half of the run. At the turn around point they started to loosen up a little bit and I was able to pick up my pace a bit on the way back to the park.

Around the turn into the park and then one final small hill and then it was all downhill to the finish line. I was happily surprised by my time of 1:23. This time I even undid my own timing chip and handed it to them. I grabbed a water bottle and some post-race food and watched some other people finish.

Wednesday, August 19, 2009

Triathlon Wetsuit


I got my first triathlon wetsuit yesterday and tried it out this morning. Never mind staying warm in colder water, it adds so much buoyancy it feels like i'm cheating at swimming! Maybe it helped that I just listened to the latest tritalk episode 69 where they talked about paying less attention to swimming rotation but I think it was mostly the suit. Now i'm looking forward to my final race of the season in September and can get in some races early next season without freezing, yay!

Wednesday, June 17, 2009

My Desk

Trying out the qik live video app on my phone. This is my desk at work. Maybe i'll have something more interesting later.

Friday, February 13, 2009

You can watch 60 minutes, even captain kangarooo!

Most of the television, movies, and video I now get online. I can finally choose from a large selection of programs thanks to newer online video sites. Most of my television show viewing is now done from Hulu. I think it's funny when at the start of the show they have the message to tune in at such and such a time on some channel that I don't get. Don't they know if you use Hulu, watching television shows after they air is better than watching live or dealing with maintaining your own DVR service.

I also watch video podcasts using Miro. Miro has a guide to new podcasts and just came out with version 2.0 too! There are many podcasts that are technology and science related that I enjoy watching. This is a niche that would probably never make it on a broadcast tv station, and having it as a podcast can reach a global audience. One can also subscribe to youtube channels just as if they were regular podcasts, which makes it easy to keep up with them.

I've also started watching some academic lectures at academicearth.org - this site combined the open course videos that are available from top universities in an easy to navigate form. And you get a front row seat all the time, which is not really possible if you attended the class in person.

Some of the places I get shows from are:
Hulu - has many tv shows, only slightly delayed
Miro - internet video player with a built-in podcast guide
Academic Earth - watch online courses tuition free
Top Gear - top gear car videos
Revision3 - internet tv shows like tekzilla
A-Z of Bushcraft & Survival - actual survival information, not bear grylls doing the most dangerous thing they can think of.

You'll be able to download or stream many of the shows you watch now, and more will be available every day. Some content producers may have a subscription, but I think that will be pretty rare except for things that have enormous costs involved like mega-dollar sports teams. Some day having a subscription tv service will seem as quaint as having a landline dialtone service. You have gotten rid of your landline dialtone haven't you?

Monday, January 19, 2009

Inauguration Streaming Online

Watch the inauguration on Hulu:

Thursday, October 30, 2008

pygame number puzzle

This is my first little game using the pygame library. I seem to remember and old mac desk accessory that was a 4x4 number square puzzle, so I wanted to see if I could make something like that with pygame. With all the help from pygame it's only 75 lines. Programming in pygame reminds me of programming for Quickdraw, so it's sorta fitting to make a game similar to the old mac desk accessory game.

It needs a little tweaking and randomness, but it's playable.



You can dowload it here

Tuesday, June 24, 2008

Firefox 3 Usability

While I generally like Firefox, I think it's usability has suffered with the release of Firefox 3. They seem intent on making it look the same as the platform it's on. Firefox is my interface to everything, I really don't care whether I'm on windows, linux or mac. The browser is now MORE important than what platform it's on, and I think they can dictate their own look and feel. If you want a platform matching browser you can use the native one, IE, Safari, Epiphany, or Konqueror. I really want the keyhole button in my linux browser, since I move between different OS's, but now it looks inconsistent. In windows there is also an X for the Stop Loading button. I think of an X as close, and it's not clear that that means Stop Loading to me. Bring back the stop sign! I'll probably change my theme to work in these ways eventually, but it would have been nice to be better out of the box.