Reverse DNS with djbdns on private IP

Preface:

I remember long time ago when i had to mess around with BIND, the old, venerable, security flaws rich history, and of course the not for humans configuration file, name server. I’m so happy that i switched to djbdns and of course the very practical vegadns GUI.

End of preface.

So, in a a scenario where you have a network with private address(es), yes it can be in the same physical machine (like a private IP jail….) you can use tinydns to publish a PTR record for that IP(s) and force dnscache to use your own published PTR record to resolve the private IP to the configured domain/hostname.

First configure tinydns, you can use vegadns as usual, set a new in-addr.arpa domain according to the pretended IP(s) reverse. Ex:

For several 10.1.1.x addresses, configure a 1.1.10.in-addr.arpa domain, if you just want to configure a reverse record for 10.1.1.2 it’s enough to configure a 2.1.1.10.in-addr.arpa (note in both situations the inverted IP). Don’t forget to set the NS records to your own tinydns instance. Then it’s just a matter of configuring the IP PTR record. Let’s say 10.1.1.1 PTR my.domain.com, in vegadns you insert the IP in the hostname and my.domain.com in the address field (it’s a reverse) and choose PTR from the type select.

Now, for the dnscache resolver use this information, and query directly your server bypassing the normal reverse resolve process. Actually is a very simple, just create a file in /etc/dnscache/root/servers/ with the same tinydns logic. Ex: to bypass only for IP 10.1.1.2 create a 2.1.1.10.in-addr.arpa file, for all 10.1.1.x addresses a 1.1.10.in-addr.arpa file and so on. In the newly created file you just have to put the tinydns IP that dnscache will use to do the resolve queries.

You can easily test if everything is ok, with the good old reliable dig command:
dig +noall +answer -x 10.1.1.1

FreeBSD – Configure a private IP jail

If you use jails (or want to use jails) but your pool of IP addresses is somewhat limited don’t worry. You can fully configure and use a jail in a private IP, and even assign port forwarding from the “outside” network to reach the jail.

First things first, create a loopback interface clone and assign it an IP address:

ifconfig lo1 create
ifconfig lo1 inet 10.1.1.1/32

To make this live across reboots add the following lines to /etc/rc.conf:

cloned_interfaces="lo1"
ifconfig_lo1="inet 10.1.1.1 netmask 0xffffffff"

Now, use ezjail to create and configure a new jail and assign this internal IP address. If you start the jail now you will be able to access it, but in the jail itself you will not be able to access the outside world… this is where NAT comes in.

There is at least 2 options, the natd daemon + ipfw or the pf route. I opted for the pf route simply because the configuration is much more simple (but if you are more pro-efficient with natd and ipfw probably it’s the best bet).

As always be careful when messing with a firewall, specially if you are working on a remote server, as you can lock yourself out of your own server. I usually set up an at job that reboots to the previous state in half an hour or so to test everything before committing the changes permanently to rc.conf (to start and stop services with no rc.conf entry you can use the onestart/onestop option).

This is the most economical version of /etc/pf.conf (adjust the external interface and the jail IP (the first two lines):

ext_if="em0"
JAIL_SRV="10.1.1.1"

set skip on lo0
scrub in all

nat on $ext_if from lo1:network to any -> $ext_if

pass all

and fire up pf

service pf start

and now from inside the jail you can access the world. Actually, the FreeBSD manual (in it’s current writing) states an additional step, that is to enable the sysctl gateway_enable=”YES” option to nat work, but I didn’t enable it on two machines running FreeBSD 10 and is working perfectly. In set-ups with natd + ipfw you have to enable it for sure, on old FreeBSD versions with pf I just don’t know… but if you can’t access the world from within the jail enable this would be on top of my list.

To make this permanently just have to add to /etc/rc.conf

pf_enable="YES"

Now, that you have the jail all set-up, It’s about time to expose a service to the world (let’s say for example a HTTP server running clear and ssl – ports 80 and 443), you just need a tweak in /etc/pf.conf:

ext_if="em0"
JAIL_SRV="10.1.1.1"
PORT_WWW="{80,443}"

set skip on lo0
scrub in all

nat on $ext_if from lo1:network to any -> $ext_if
rdr pass on $ext_if proto tcp from any to $ext_if port $PORT_WWW -> $JAIL_SRV

pass all

You can jail services without using external IPs, assign HDD space via ZFS or virtual disk files, set CPU core(s) affinity, or fine grained memory and CPU limits via rctl.

Pretty cool!

PHP get a Youtube video duration

To make this work you need to go to Google Developers Console, create a project, enable the YouTube Data API v3, and get a key in authentication key in credentials. This is pretty much the difficult part.

Now the easy part, so easy and keystroke economic to do this in PHP… just a couple of lines, and it’s done:

define("API_KEY", ""); // Fill in your Google API Key
function getYoutubeDurationV3($id) { 
  $json = json_decode(
            file_get_contents('https://www.googleapis.com/youtube/v3/videos'.
                              '?part=contentDetails&d='.$id.'&key='.API_KEY)
          ); 

  $start   = new DateTime('@0');
  $youtube = new DateTime('@0'); 
  $youtube->add(new DateInterval($json->items[0]->contentDetails->duration));
    
  return $youtube->getTimestamp() - $start->getTimestamp();
}

Continue reading “PHP get a Youtube video duration”

How to calculate resistors for leds

For the, what resistor should i put in the circuit so my led don’t fry question. There is a very easy way, go to a on-line calculator site like http://ledcalculator.net/, input the values and bazinga you get an instant answer.

But that’s for sissies, the only way a real man does it, is calculating (preferably by head) applying Ohm’s Law:

ohm_law(behold, and bow twice, please)

Current (amps) equals to the proportion between potential difference (volts) and the resistance (ohms). Let’s say for a common red led (voltage is 2volts and current rating is 20mA), and a 9v battery power supply, the math is this:

(9v – 2v) / (20mA/1000A) = x Ohms
7 / 0.02 = 350 Ohms

But with these values in a led calculator, the result is 360 Ohms, what’s wrong with your math? Nothing. This is because of the so called “nearest preferred values resistors”. Resistors are available in a number of standard ranges (being the most common E24) in predefined scale. So you should round up to the next higher value. And from 350 Ohms the preferred resistor value is 360 Ohms.

With the resistance calculation done, you must find the right resistor. Again, there is the sissies method, go to a on-line resistor color code calculator like http://www.electronics2000.co.uk/calc/resistor-code-calculator.php, input the resistance and get the color codes (and vice-versa) or the mens method trough a resistor table:

resistor_table

So, a 360 Ohms resistor is the one in your resistors packs with a Orange (3), Blue (6) and Brown (36 * 10 = 360) band. The last band, that stands for tolerance is probably gold (with my very little experience in electronics never saw a silver resistor).

Disclaimer: remember that (as always) i decline every liability if you burn your LEDs, your head or the whole world because of this post.

Raspberry GPIO

Finally the fun stuff. Messing around with the General Purpose Input Output of the PI. So, first things first. First you must identify what revision PI you are working. Visually, looking at it, if there are 2 mounting holes is a revision 2, if there are no mounting holes it’s a revision 1. A much more scientific approach is to install WiringPi.

sudo bash
apt-get install git-core
apt-get update
apt-get upgrade
git clone git://git.drogon.net/wiringPi
cd wiringPi
git pull origin
cd wiringPi
./build

Then run

gpio -v

Raspberry Pinout DiagramAnd there you got the answer in the last line of the output. “This Raspberry Pi is a revision 2 board.”. So, first thing is to pull from the Internets a wiring diagram.

Now, for the actual cabling from the PI, in my opinion the best route is to get a set of male to female jumper cables. You can also find for sale some ribbon cables specific for the PI. In my opinion, unless you want to connect some device or accessory already wired to match the PI GPIO, the best option are the jumper cables, it’s very easy to visually  match the PI pin to a breadboard location, you only use the number of cables needed and they are easily routed trough the venting holes of the average PI case and easy to solder on a protoboard.

I ordered my jumper cables from Ebay, but has i waited for them, the inner MacGyver took over… with a old floppy drive flat cable is not so difficult to improvise. Just cut a segment of the cable with a sharp knife, so in one end you have the plastic connector and in the other you have the wires with a clean cut and no short circuits between them. One problem, is the floppy cable 34 pins versus 26 in the PI. What i did is simple to cut out of the way the first 8 cables of the ribbon (and just forget encasing the PI, the connector protrudes almost the same length as the SD card). Then with cable connected in the right way (not bad idea to test first at the end of the cable with a multimeter) the first cable of the ribbon corresponds to pin 1 of the PI and so on. Some pictures of this setup:

IMG_20131108_023031IMG_20131108_035153

Just another note, i have been messing with the GPIO, juggling and testing different setups without powering off the PI between rewiring, without no problem at all, but please use good judgment and common sense.

1 – Lighting up a LED with the PI (simple output example)

Connect physical pin 11 of the PI to the positive bus of the breadboard and physical pin 6 (ground) to the negative bus of the breadboard, and connect a led and >= 68Ω resistor (why?) closing the circuit between positive and negative bus strips (remember that a led is one way device, so long leg on the positive side and small leg to the negative). The diagram to make even easier:

Raspberry First Led

And now in the PI command line, the command to put the pin in output mode, switch off and on the LED:

gpio mode 0 out
gpio write 0 0
gpio write 0 1

Wait! But isn’t the cable connected to pin 11? What is this stuff with pin 0?
Well.. the logic in wiringPI is to abstract pin numbers in software so it remains “immune” to any hardware changes. As the pin diagram above (can be checked running gpio readall also), physical pin #11 (third column of gpio readall output) corresponds to wiringPI pin #0 (first column of gpio readall)  and to the GPIO #17 (the internal pin number used in the chip). So, regarding the logic of hardware abstraction with the gpio command, we can call a pin by the wiringPI numbering or the GPIO numbering (with the -g switch, ex: gpio -g write 17 0) but not by physical pin-out number…

2 – Reading state (simple input example)

To read state from a pin, you must devise a circuit that pulls up or pulls down the pin that you are going to read, then change the state of the circuit with a pushbutton (or any other suitable mean). This is a fucking bad explanation… so let’s look to the schematic:

raspberrypi_input_schemWe have physical pin #1, the 3.3v output (that’s the one that should be used for input reading) going to a 10kΩ resistor then split by a) a pushbutton that connects to physical pin #6 (ground) and b) a 1kΩ resistor that connects to physical pin #11. When the pushbutton is not pressed, no current passes trough there to ground, so the current goes to the 1kΩ resistor and pulls up pin #11. In this state, all the readings from pin #11 will be High. When the pushbutton is pressed the current will flow freely to ground (pin #6) and the reading from pin #11 will be Low. This is a bit counter intuitive, reading High (or 1) when the pushbutton is NOT pressed and Low (or 0) when the pushbutton IS pressed, but is very easy to take care in the software stage.

The diagram on the RaspberryPI and breadboard:

raspberry_input

And a very simple Python script to output when the push button is pressed:

import RPi.GPIO as GPIO
import time
buttonPin = 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(buttonPin,GPIO.IN)

while True:
    input = GPIO.input(buttonPin)
    if input == 0:
        print("Button pressed")
        exit();
time.sleep(0.1)

Save and run as “python script_name”. When the pushbutton is pressed it should output “Button pressed”. Note that with the RPi.GPIO module in the GPIO.BOARD mode, we are addressing the physical number of the pin in the board.

There! Raspberry PI, welcome to the real world. Just baby steps… laying the foundations for further developments.

Some references:
http://elinux.org/RPi_Low-level_peripherals
http://wiringpi.com/