Facebook: Identity Disclosure through Followjacking

Using the Facebook follow button plugin on any third-party site, it is feasible to automatically disclose all public Facebook information if a user is currently logged into Facebook. Therefore, the clickjacking attack allows targetted attacks against the anonymity and the privacy of any Facebook user. In conjunction with connection-based data (such as IP geolocation, ISP information etc.), the attack can be used on a low scale in order to further deanonymize users (including the exposure of the user’s residence by consulting public phone books) to the third-party site with little interaction consisting of only one click. Since users have not necessarily chosen to make their public information available to any third-party using the follow button on their website, the attack violates Facebook’s privacy model. However, according to Facebook, it does not qualify for a bug fix.
Furthermore, the attack can be conducted on behalf of the user when using a registered Facebook application in order to detect whether the user is currently logged in or not.

The vulnerability can be reproduced in any modern browser which it is optimized for.

  1. Create a new Facebook account and add your mobile phone number in order to choose a username and allow public followers.
  2. Create a Facebook web application in order to make use of the login detection capabilities of the Facebook JavaScript API as described on developers.facebook.com.
  3. Detect on your third-party site whether the user is logged into Facebook. If so, create a follow button using the Facebook plugin API.
  4. Set the CSS opacity property of the button’s parent container to 0.0.
  5. Position the invisible follow button over a real button.
  6. Detect clicks on the iframe which represents the follow button by checking whether the mouse is hovered over the iframe and listening to the window blur event in order to perform an additional interaction to raise less suspicion when the apparently real button is clicked.
  7. Now wait for new Facebook followers to show up at your timeline’s follower section. This process can be automated.

According to Facebook, they have implemented backend heuristics detecting possible abuse of embedded plugins. Indeed, the attacker account was blocked from accepting new followers through the follow button after excessive testing. However, they have been proven to be useless in small-scale and specifically targetted attacks.

Countermeasures

  • Blocking third-party cookies in general is one countermeasure preventing this kind of attack. In this case, cookies are not transmitted when loading the subscription button. This means that a click onto the button will trigger a popup window asking the current user to log in.
  • The usage of browser extensions like Ghostery or AdBlock Plus is another method of preventing the subscription button to be rendered in the first place.
  • An implementation by Facebook to always trigger popups when interacting with “social” plugins asking for a confirmation would also eradicate the attack vector.
  • Proof of Concept

    Vulnerability in HP Color LaserJet 4650 and 4700 printers

    Talking about cyber-security, the first thing coming to your mind might be personal computers or server racks, maybe surveillance cameras considering the NSA affair. At least, printers will probably not be the first thing you might think of. However, it is important to not neglect them.

    Basics of PJL

    PJL is an acronym for printer job language, a protocol developed by Hewlett Packard (HP) in order to provide a simple communication method between a host, usually a personal computer commanded to print a document, and the printer. Being running on port 9100 by default, PJL is not only restricted to HP printers but being used by other printer models as well. The language provides a set of commands, including file system commands to download and upload files remotely from and to the printing device.
    A basic PJL session might look like this:

    user@client:~$ telnet 192.168.178.100 9100
    Trying 192.168.178.100...
    Connected to 192.168.178.100.
    Escape character is '^]'.
    
    ^[%-12345X@PJL
    @PJL INFO ID
    @PJL INFO ID
    "Brother MFC-7840W:8C5-C17:Ver.L"
    
    @PJL ECHO Hello World
    @PJL ECHO Hello World

    While the INFO command having the parameter ID requests the printer to reply with its model name and version, ECHO has the printer reply with the subsequent message Hello World. This is not too thrilling yet until you are playing around with the file system commands prefixed by FS*. For example, @PJL FSDIRLIST NAME=”0:\” ENTRY=0 COUNT=999 replies with a list of files located on volume 0:\. On most HP printers, this exposes some web server related files to curious eyes. However, what should not happen is that you can escape volume 0:\ by using a double-dot. But this is exactly what you can do and is called directory traversal attack. 0:\..\ reveals the parent directory of volume 0:\ and 0:\..\..\ is sufficient on most HP printers to get access to the root directory of the underlying Unix system.

    Open file systems

    Open printer file systems allow you to directly upload files to the printer’s web directory. Visit http://lks-350-375e-038-d.ls.berkeley.edu/hp/device/pjlexploit/PoC.html for a proof of concept. Although there is a protection against file system access, namely a 16-bit PJL password which has to be set via the PJL interface, it is too complicated for standard or even advanced users who would have to know the PJL specifications in order to set it up. Secondly, a 16-bit PJL password can be successfully brute-forced within hours.

    Plain text passwords

    Storing plain text passwords is a sin which you are only allowed to commit as an absolute security beginner. You may not practice this technique when you are an embedded systems developer for a company whose printers are shipped worldwide. However, this is exactly what HP developers have done. Since you have access to a large part of the Unix file system which only seems to be restricted by native file permissions, you are now allowed to download the file at 0:\..\..\hpmnt\dsk_cf0a\PermStore\ps_3D_0D.dat using the PJL-command FSUPLOAD (PJL commands are named based on the perspective of the printer). Guess what this file consists of. If you read a null-terminated ASCII-string starting at position 0x0c, you will notice that this string contains the web interface administration password.
    Just look at the following short PJL session which will fully exploit this vulnerability. This was a session to 164.67.135.16 at the University of Calfornia in Los Angeles and selected as an example because of the highly creative password choice.

    ^[%-12345X@PJL
    @PJL FSUPLOAD NAME="0:\..\..\hpmnt\dsk_cf0a\PermStore\ps_3D_0D.dat" OFFSET=12 SIZE=16
    @PJL FSUPLOAD FORMAT:BINARY NAME="0:\..\..\hpmnt\dsk_cf0a\PermStore\ps_3D_0D.dat" OFFSET=12 SIZE=16
    password

    Explore printers yourself

    PJL ExplorerA web-based PJL exploring tool called PJL Explorer has been developed in order to allow easy graphical access to the printer file system. You can access it at http://blechschmidt.saarland/printers/. PJL Explorer allows you to browse the printer file system, upload and delete files. To find vulnerable printers, run the following search query using a free Shodan account: port:9100 hp.
    The source code of the PJL Explorer is available on Github.

    Universities of Harvard, Princeton and Cambridge affected

    Harvard: 140.247.118.185, 140.247.92.198, 128.103.90.40
    Massachusetts Institute of Technoloy: 18.115.2.89, 18.116.0.129
    Princeton: 128.112.35.10, 128.112.112.112, 128.112.32.43
    Cambridge: 131.111.168.138, 131.111.39.27
    Stanford University: 171.67.204.34
    University of California, Berkeley: 128.32.208.18, 128.32.19.225, 169.229.207.65
    University of California, Los Angeles: 128.97.11.33, 164.67.135.16, 128.97.64.72

    For legal reasons, passwords are not included in this blog post. To view a printer password, please click one of the above links in order to use the PJL Explorer in order to display the passwords.

    View the vulnerability report which I have sent to Hewlett Packard. According to the reply of HP, two security bulletins have already been published, one in 2010 and another one in 2013.

    Skype: Hide your IP address from resolvers on Linux

    How to hide your IP address from Skype resolvers on Linux

    On Windows, Skype offers an option called “Allow direct connections to contacts only” which prevents from being tracked by so-called Skype resolvers. Unfortunately, Linux does not offer such an option in its graphical user interface. However, there is a detailed description on the Skype community boards on how to enable this feature on Windows 8, which does not seem to have the option integrated into the GUI either. On Linux, it is possible to follow the instructions as well, replacing the corresponding file name by its Linux equivalent:

    1. Quit Skype
    2. Open a terminal and enter cd /home/{linux username}/.Skype/{skype name}/ (replace {linux username} with your Linux username and {skype name} with your skype name)
    3. Enter gedit config.xml in order to open the configuration file
    4. Find <Account> in the file using Ctrl+F
    5. Enter <PrivateSkypeMode>1</PrivateSkypeMode> after <Account>
    6. Save the file using Ctrl+S
    7. Restart Skype

    If you successfully followed the described steps above, you will notice that Skype resolvers will not be able to resolve your IP address anymore. However, for contacts in your contact list this might still be possible using network packet inspectors like Wireshark.

    Why you should not purchase Skype resolver blacklisting services

    There are several reasons to not purchase blacklisting offered by several Skype resolving services.
    Firstly, Skype resolvers violate your privacy and in order to protect yourself you should pay the operators. This is morally reprehensible and – in my opinion – close to blackmailing.
    Secondly, many operators behind these services seem to be cybercriminals which have infected a various number of machines in order to run distributed denial of service attacks. It is not uncommon that after you have successfully resolved the IP address of a Skype user, you will be asked whether you wish to take the IP address down using some commercial “booter”. In most countries, this is illegal and therefore, the operators should not be supported.
    Most importantly, if you have purchased the blacklisting service, this blacklisting only applies to the Skype resolver for which you have purchased it. If the IP address resolvement fails using one Skype resolver, a malicious attacker will just move on to the next one. And even if you would purchase blacklisting for all available Skype resolvers offering this service, which might not be all, I doubt you could afford it.
    Furthermore, there are native methods, like the one described in this blog post, to prevent your IP being found by Skype resolvers – for free.

    RAM Scraping: Reading passwords off your browser

    In this post I want to point out, how it is possible to recover sensitive information like PayPal passwords from computer memory with a specific example. The idea relies on sensitive data still being stored in the process memory, even after TLS/SSL-encryption.

    Intuitive approach
    The attacking program is supposed to iterate through all memory pages of interesting processes, where interesting processes are browsers (on Windows being named “iexplore.exe”, “firefox.exe” and “chrome.exe”), in order to scan for essential HTTP parameters like “login_email=” and “login_password=” in order to find HTTP POST data like “login_email=john.doe@example.com&login_password=secret” and extract the email address and the password.

    The search algorithm
    Although the attack itself is very interesting but not too challenging, let us begin with the somewhat more challenging and – from the perspective of a computer scientist – more elementary part: the search algorithm. As we want to scan one large amount of binary data for a bunch of parameters, an algorithm allowing to scan for multiple words at the same time is required, preferably with a runtime of O(n). The intuitive idea is to create a deterministic finite automaton (DFA) from the given set of words. For example, if we search for the words “ab” and “car”, our automaton might look like this:

    AutomatonThe programmatic creation of this automaton is difficult to some extent because it does not only need to match “ab” and “car” but also “cab”. If there is no edge from one state to another, the algorithm continues to search from the initial state. Please be aware, that every state which is not an accepting state still has edges for all characters of its input alphabet to the initial state. Those are simply not shown in the illustration for reasons of readability. This described algorithm is not new but a slight modification of an algorithm being known since 1975 as Aho-Corasick-algorithm.
    The automaton is programmatically built by creating a non-deterministic finite automaton (NFA) which is then converted to the desired DFA using the powerset construction method. Conversion takes place so that only one pointer at a time is required to hold the current state which again allows to fulfill the runtime requirement of O(n). Furthermore, we convert the DFA (which is in my implementation based on the map-STL-library) to an array structure so that we are really sure to meet the runtime of O(n) as close as possible in order to make iterations over the maps unnecessary as you can see in the table below.

    Array index Input character Projection index
    -1 (not an element of the input alphabet)
    0x61 (97) a 0
    0x62 (98) b 1
    0x63 (99) c 2
    -1 (not an element of the input alphabet)
    0x72 (114) r 3
    -1 (not an element of the input alphabet)

    The above table basically shows an array from 0x00 (0) to 0xFF (255) holding the indices of the input symbols. Knowing this projection, this allows us to implement an automaton using the following recursive structure:

    struct StateArray
    {
    public:
    	StateArray** Transitions;
    };
    

    In our case, an accepting state is represented by a NULL-pointer which saves us a byte (which is the size of a boolean) per state. The first asterisk is used to point to a dynamically allocated array which is possible as soon as the cardinality of the input alphabet is known and is based on the table above, the second one indicates a pointer to the successing state. In case of the example automaton, this means that any state of the example automaton is represented by an array consisting of four pointers.

    Reading the process memory
    To be honest, this is what I consider the ugliest part, although I do not really know the source of my aversion for the Windows API. What I (and many other people) find very surprising, is the fact that the Windows API allows to open and read the process memory of foreign processes without elevated priviliges. Practically, this means that it is possible to just read out any browser’s process memory without requiring administrator privileges. This makes it easy for trojan horses to just read off the unencrypted data. At the moment, I do not wish to further elaborate on this part, as you will be able to inspect the corresponding class (MemorySpy) in the code below.

    Video example

    Continue reading / Weiterlesen

    ARD-Mediathek Zeitsperre umgehen

    Da ich mir, wenn ich den Tatort sonntags im Ersten Deutschen Fernsehen einmal verpasst habe, diesen gerne mal in der Mediathek ansehe, mich jedoch oft darüber ärgere, dass man ihn aufgrund von Jugendschutzbeschränkungen nur zu bestimmten Zeiten (20.00 Uhr bis 6.00 Uhr) ansehen kann, möchte ich niemandem meine Lösung unter http://blechschmidt.saarland/ARD/ vorenthalten. Aufgrund einer fehlenden Zeitüberprüfung der Content-Server der ARD-Mediathek ist es damit dennoch möglich, sich die Videos auch zu annehmbareren Zeiten anzusehen. Im Hintergrund wird einfach anhand des zugehörigen ID-URL-Parameters die Adresse des Videos auf dem Medienserver bestimmt, die zu Sperrzeiten dem Nutzer lediglich vorenthalten wird.

    Guide to doxing: Tracking identities across the web

    Did you ever consider, how easy it can be to track you down the web just based on a nickname and just little additional information? Let me tell you: In many cases this is very easy. The technique being employed to de-anonymize users is often referred to as doxing, which is derived from the abbreviation of the word “documents”. It relies on the aggregation and linkage of personal information from various internet sources. Reasons for doxing include intimidation, extortion, denunciation and aid of law enforcement agencies.

    You are given the username

    Let us begin with the most common scenario. You are given the username of some apparently anonymous user, be it a Skype name, an ingame name or some other nickame. As we are talking about a real person behind a nickname, you can assume that the person associated with this nickname has common idiosyncrasies including simple convenience – and convenience is a security and privacy killer. Why do people use the same password for securing a whole bunch of accounts? Due to convenience. Why do people use the same nickname for a set of web services? For exactly the same reason: convenience.
    At first, if you know a nickname, hope that the person has been convenient in her choice which means that they use the nickname for other services as well. Look it up using Facebook on http://facebook.com/username, try the integrated Skype contact search or just use Google to find other services like forums or instagram.

    You know the Skype name

    Knowing the Skype name of a person is a real advantage. A user having a non-standard avatar might allow you to find additional web accounts by profile picture search.
    Another method is based on the linkage between Facebook and Skype accounts. In detail, there are at least two ways, this kind of connection can be created: Either the user has once used the Facebook friend finder function, then the Skype user name is automatically linked to the user’s Facebook account, or the user has linked their Facebook account to their Skype account directly in Skype in order to use the Facebook chat within Skype. This can result in an immense privacy leak. If you are friended with the user on Skype, you can use the Facebook friend finder function which is basically a reverse search by Skype name. You are just required to enter your Skype credentials into the form on Facebook and you will automatically be suggested to add all your Skype friends that have their accounts linked to Facebook.

    You have the email address

    Email addresses also impose your privacy to an immense risk. If an email address is known to a hacker, you can in many cases uses the password reset functions of Facebook being an ideal email validator. Any hacker will just pretend to be some user and submit the email to the password reset form on Facebook. If Facebook cannot associate the address to an existing account, it is not registered at Facebook. If an account can be associated to a profile, you might already see the name and the profile picture of that account. In some cases you will just see the standard profile picture of an account. Actually, the cases when you see the profile picture seem to depend on a mixture of privacy settings and IP address range matching. Although my profile picture is available to friends only, Facebook does display it for my account when I use the password reset function.

    Finding by profile picture

    If you are given a unique profile picture that is not some common internet meme, you have a chance to find associated accounts using the Google image reverse search. As many people do not have their Facebook timelines indexed however, this chance is rather tiny. If the profile picture you want to search was a Skype image and the Skype name was “test”, you might consider to download the profile picture directly at http://api.skype.com/users/test/profile/avatar instead of risking that taking inaccurately cropped screenshots reduce the chance of finding it with Google.

    Profiling by friends

    Profiling by friends is actually a method which requires some more work. This is especially useful if you could not retreive information which was obtainable more easily. In this case you are given some web account which exposes some names of a user’s friends. Services like Ask.fm or Instagram might allow you to find out whom a person is interacting with very frequently which might be an indicator for a closer relationship like real-life friendship. In this case, the approach consists of googling these names together using quotation marks. E.g. you know the URL of the instagram account of a person named John Doe you find out that John Doe frequently interacts with Max Mustermann and Erika Steinbach, I would suggest to google for “John Doe” “Max Mustermann” “Erika Steinbach” (with quotation marks) or “Doe, John” “Mustermann, Max” “Steinbach, Erika”. Results you might find include school, sporting events or work relationships.

    Fetching Facebook accounts by known properties

    Another privacy killer is the Facebook graph search allowing you to query identities based on preferences or other properties. Useful phrases include “People named John”, “People who live in Berlin”, “People who live near Berlin”, “People who have friends named Max Mustermann named John Doe” “People who work at Google”, “People who like Google” where Google in the last two cases refers to a Facebook page. In general, the principle applies that less people matching a criterium result in a faster search. It is also possible to combine two statements with the conjunction and, e.g. “People who like Google Chrome and Mozilla Firefox”. However, you should note that this option relies on the search criteria being available to a public audience which was beforehand chosen with the Facebook privacy selector.

    Finding additional details using Facebook

    Using the password reset function, Facebook provides a useful feature: Facebook validates the email address while exposing it partially showing the first character of the local part, the last character of the local part, the first character of each domain label and the full top-level-domain (like .com or .net). For example “john.doe@hotmail.com” becomes “j******e@h******.com and “max.muster@subdomain.example.net” becomes “m********r@s********.e******.net”. Now it’s time to guess the most common email providers. You are well-advised to test GoogleMail (gmail.com, googlemail.com), Hotmail (hotmail.com, live.com) and Yahoo (yahoo.com) in that order together with the most common combinations of the first and the last name. If people use serious email addresses, you might try firstname.lastname@emailprovider.tld. Remember that emails are validated by entering them again into the password reset form.
    If you want to circumvent Facebook privacy restrictions while staying anonymous, you might create a fake account and send friend requests to friends of the target person. Only one friend accepting a request means that you will now be able to see all information of the target person made available to their friends’ friends. One hint is to add a fake profile picture to your account since this perceivedly increases the chance of the requests being confirmed exponentially – at least as soon as you already have some friends in the people’s social environment – because many people look at common friends when they decide whether to accept or decline a friend request. It might also be worth a try to request the target person’s friendship directly.

    Finding by telephone number

    This is an easy task. Use the Facebook password reset form and enter the number into the text field. You might get the name of a Facebook account associated with the number. Secondly, try adding the person to your phone contact book and use common applications like Whatsapp or Snapchat to find a picture or another nickname of the person. Also Skype supports a backwards search querying Skype accounts by telephone numbers.

    Finding by domain name

    Use WHOIS-servers to find people’s addresses and full names very fast. On the Internic website you can find out where to query full whois information for .com- and .net-domains. A faster way might just consist in looking out for legal information on the webpage.

    Finding location by IP

    If you have given an IP address, you might use tools like Utrace or Ip-Adress [sic] in order to find the approximate location for a user. Services like MostwantedHF or other so-called Skype-resolvers allow you to find your IP address based on a Skype name under certain conditions, although this mostly just works when the user is currently online.

    Finding details using git

    Sometimes, git logs from platforms like GitHub may provide additional information about the real identity of a person. Cloning a repository and then executing “git log” may suffice in order to find out real name and email address.

    Clickjacking vulnerabilities

    Clickjacking is a serious threat to online anonymity. It refers to a technique tricking users into clicking an invisible element on a third-party site (e.g. a social follow button plugin) without noticing the click to the plugin. As pointed out in another blog post, Facebook followjacking allows to automatically retrieve public information from the Facebook profile of any logged in user clicking onto a malicious element within any website.

    To conclude: All methods do more or less rely on the name uniqueness of a person’s real name and the fact whether a person just one single or a whole set of nicknames. In general, one approach is to throw everything into Google, Facebook search or Skype and other online monopolys.

    If you are interested in how to prevent being tracked, keep an eye on this blog as I soon want to post some ideas of countermeasures.

    You are not anonymous on the web. Never. In many cases not even for private persons.

    Connecting an Arduino to an Android phone

    Since I wanted to debug my Arduino using my mobile phone (Samsung Galaxy S2) using the Arduino’s comfortable serial library, I bought a cheap USB-OTG adapter cable (male micro-USB-B to female USB-A) in order to connect the Arduino to my phone. The USB-A plug of the normal Arduino cable connecting an Arduino to the computer can be plugged into the above mentioned USB-A socket and again, the USB-B plug of that cable is connected to the phone.
    After connecting it I had some difficulties to find a working app for my phone allowing to communicate with my Arduino using the serial interface. After some searching I found Slick USB 2 Serial Terminal which fulfilled its job fine for me. It is important to select “Prolific” mode in order to receive and send data from and to your Arduino. If your phone supports USB host mode, you can even use your phone to power the Arduino, so no external power supply is required.

    Linked list – Library for Arduino

    As I was struggling with my HC-05 Bluetooth module which might return an unspecified count of lines when responding to a command in AT (attention) mode, I have written a small library for a single chained list. It is just a dynamic data structure supporting chronological pushing while it allows iterating through all its elements.

    /*
      List.h - Linked List (single chain)
      Created by B. Blechschmidt (Ovex), 16 August 2013
      Released into the public domain.
    */
    #ifndef List_h
    #define List_h
    
    #include "Arduino.h"
    
    template <class T> class ListElement
    {
    	public:
    		ListElement(T Element)
    		{
    			Content = Element;
    			NextElement = NULL;
    		}
    		~ListElement()
    		{
    			delete NextElement;
    		}
    		T Content;
    		ListElement<T> *NextElement;
    };
    
    template <class T> class List
    {
      public:
    	~List()
    	{
    		Clear();
    		delete FirstElement;
    		delete LastElement;
    		delete CurrentElement;
    	}
    	List()
    	{
    		FirstElement = NULL;
    		CurrentElement = NULL;
    		LastElement = NULL;
    		Length = 0;
    	}
    	void Clear()
    	{
    		ToBegin();
    		delete CurrentElement;
    		FirstElement = NULL;
    		CurrentElement = NULL;
    		LastElement = NULL;
    		Length = 0;
    	}
    	void Push(T Element)
    	{
    		if(LastElement)
    		{
    			LastElement->NextElement = new ListElement<T>(Element);
    			LastElement = LastElement->NextElement;
    		}
    		else
    		{
    			FirstElement = new ListElement<T>(Element);
    			LastElement = FirstElement;
    			CurrentElement = FirstElement;
    		}
    		Length++;
    	}
    	bool IsEnd()
    	{
    		if(CurrentElement)
    		{
    			return false;
    		}
    		else
    		{
    			return true;
    		}
    	}
    
    	bool IsEmpty()
    	{
    		return FirstElement == NULL;
    	}
    
    	unsigned long Count()
    	{
    		return Length;
    	}
    	void ToBegin()
    	{
    		CurrentElement = FirstElement;
    	}
    	void Next()
    	{
    		if(CurrentElement)
    		{
    			CurrentElement = CurrentElement->NextElement;
    		}
    	}
    	T GetValue()
    	{
    		return CurrentElement->Content;
    	}
      private:
    	  unsigned long Length;
    	  ListElement<T> *FirstElement;
    	  ListElement<T> *LastElement;
    	  ListElement<T> *CurrentElement;
    };
    
    #endif

    Usage:

    #include <List.h>
    
    void setup()
    {
    	List<String> StringList;
    	StringList.Push("a");
    	StringList.Push("b");
    	StringList.Push("c");
    
    	//Iterate through list
    	bool ListEmpty = StringList.IsEmpty(); //false
    	Serial.println("Count: "+String(StringList.GetCount()));
    	StringList.ToBegin();
    	while(!StringList.IsEnd())
    	{
    		Serial.println(StringList.GetValue());
    		StringList.Next();
    	}
    	/*Output:
    		Count: 3
    		a
    		b
    		c
    	*/
    	StringList.Clear();
    	ListEmpty = StringList.IsEmpty(); //true
    }
    
    void loop()
    {
    }

    HiTechnic Infrared Seeker library for Arduino

    Today I have created a class allowing you to connect a HiTechnic IR Seeker V2, which is originally designed for use with a LEGO Mindstorms NXT robot, to an Arduino Due board with a 9V battery. I struggled a bit with the the different sensor pins but I could finally manage to connect the sensor correctly.

    1. white -> battery +9V (Vcc)
    2. black -> Arduino GND
    3. red -> battery – (GND)
    4. green -> Arduino +3.3V (Vcc)
    5. yellow -> Arduino SCL
    6. blue -> Arduino SDA

    The following code is executed by the Arduino:

    #include <Wire.h>
    
    /*
      IRSeeker.ino - A library/class for the HiTechnic IRSeeker V2 infrared sensor.
      Created by B. Blechschmidt, August 1, 2013.
      Released into the public domain.
    */
    
    struct InfraredResult
    {
      byte Direction;
      byte Strength;
    };
    
    class InfraredSeeker
    {
      public:
        static void Initialize();
        static boolean Test();
        static void ReadACRaw(byte* buffer);
        static void ReadDCRaw(byte* buffer);
        static InfraredResult ReadAC();
        static InfraredResult ReadDC();
        static int DirectionAngle(byte Direction);
      private:
        static InfraredResult PopulateValues(byte* buffer);
        static void ReadValues(byte OffsetAddress, byte* buffer);
        static const int Address = 0x10 / 2; //Divide by two as 8bit-I2C address is provided
    };
    
    void InfraredSeeker::Initialize()
    {
      Wire.begin();
      Wire.beginTransmission(InfraredSeeker::Address);
      Wire.write(0x00);
      Wire.endTransmission();
      while(Wire.available() > 0)
        Wire.read();
    }
    
    boolean InfraredSeeker::Test()
    {
      Wire.beginTransmission(InfraredSeeker::Address);
      Wire.write(0x08);
      Wire.endTransmission();
      Wire.requestFrom(InfraredSeeker::Address, 16);
      char Manufacturer_Model[16];
      while(Wire.available() < 16);
      for(byte i=0; i < 16; i++)
      {
        Manufacturer_Model[i] = Wire.read();
      }
      while(Wire.available() > 0)
        Wire.read();
      return strncmp(Manufacturer_Model, "HiTechncNewIRDir", 16)==0;
    }
    
    void InfraredSeeker::ReadValues(byte OffsetAddress, byte* buffer)
    {
      Wire.beginTransmission(InfraredSeeker::Address);
      Wire.write(OffsetAddress);
      Wire.endTransmission();
      Wire.requestFrom(InfraredSeeker::Address, 6);
      while(Wire.available() < 6);
      for(byte i = 0; i < 6; i++)
      {
        buffer[i] = Wire.read();
      }
      while(Wire.available() > 0)
        Wire.read();
    }
    
    void InfraredSeeker::ReadACRaw(byte* buffer)
    {
      ReadValues(0x49, buffer);
    }
    
    void InfraredSeeker::ReadDCRaw(byte* buffer)
    {
      ReadValues(0x42, buffer);
    }
    
    InfraredResult InfraredSeeker::PopulateValues(byte* buffer)
    {
      InfraredResult Data;
      Data.Direction = buffer[0];
      if(buffer[0] != 0)
      {
        if(buffer[0] % 2 == 0)
        {
          Data.Strength = (buffer[buffer[0] / 2] + buffer[buffer[0] / 2 + 1]) / 2;
        }
        else
        {
          Data.Strength = buffer[buffer[0] / 2 + 1];
        }
      }
      else
      {
        Data.Strength = 0;
      }
      return Data;
    }
    
    InfraredResult InfraredSeeker::ReadAC()
    {
      byte buffer[6];
      ReadACRaw(buffer);
      return PopulateValues(buffer);
    }
    
    InfraredResult InfraredSeeker::ReadDC()
    {
      byte buffer[6];
      ReadDCRaw(buffer);
      return PopulateValues(buffer);
    }
    
    int DirectionAngle(byte Direction)
    {
      return Direction * 30 - 150;
    }
    
    void setup()
    {
      Serial.begin(9600);
      Serial.println("HiTechnic IRSeeker V2");
      Serial.println();
      Serial.println();
      Serial.println("Dir\tAngle\tStrength");
      Serial.println();
      InfraredSeeker::Initialize();
    }
    
    void loop()
    {   
      InfraredResult InfraredBall = InfraredSeeker::ReadAC();
      Serial.print(InfraredBall.Direction);
      Serial.print("\t");
      Serial.print(DirectionAngle(InfraredBall.Direction));
      Serial.print("\t");
      Serial.print(InfraredBall.Strength);
      Serial.println();
      delay(100); //optional
    }

    To download the compressed zip-archive of the library just go to https://blog.blechschmidt.saarland/wp-content/uploads/2013/08/HTInfraredSeeker.zip. This archive can be imported using the “Sketch” menu of your Arduino IDE. Just click “Import library” and choose “Add library…”. Then just #include <HTInfraredSeeker.h> and use it as shown above in the loop- and main function.

    HC-SR04 Ultrasonic Sensor Library for Arduino

    Some days ago my new HC-SR04 ultrasonic sensor for my new Arduino board arrived. In order to keep the overview of my programs, I have written a small library for the sensor which I want to share with you here. As the library is pretty much self-explicatory in my opinion, I will not further comment the following code at this point.

    UltraSonic.h

    /*
      UltraSonic.h - A library for the HC-SR04 UltraSonic sensor.
      Created by B. Blechschmidt, May 25, 2013.
      Released into the public domain.
    */
    
    #ifndef UltraSonic_h
    	#define UltraSonic_h
    
    	#include "Arduino.h"
    
    	class UltraSonic
    	{
    	  public:
    		byte TriggerPin, DataPin;
    		UltraSonic(byte TriggerPort, byte DataPort, unsigned int MaximumRange = 400);
    		unsigned int ReadCentimeters();
    		void ReadCentimetersAsync(int &Centimeters);
    	  private:
    		unsigned long AsyncTime;
    		byte AsyncState;
    		unsigned long AsyncLength;
    		unsigned int Timeout;
    	};
    
    #endif
    

    UltraSonic.cpp

    /*
      UltraSonic.cpp - A library for the HC-SR04 UltraSonic sensor.
      Created by B. Blechschmidt, May 25, 2013.
      Released into the public domain.
    */
    
    #include "Arduino.h"
    #include "UltraSonic.h"
    
    UltraSonic::UltraSonic(byte TriggerPort, byte DataPort, unsigned int MaximumRange)
    {
      Timeout = MaximumRange * 58;
      TriggerPin = TriggerPort;
      DataPin = DataPort;
      pinMode(TriggerPin, OUTPUT);
      digitalWrite(TriggerPin, LOW);
      pinMode(DataPin, INPUT);
      AsyncState = 0;
    }
    
    unsigned int UltraSonic::ReadCentimeters()
    {
          digitalWrite(TriggerPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(TriggerPin, LOW);
          return pulseIn(DataPin, HIGH, Timeout)/58;
    }
    
    void UltraSonic::ReadCentimetersAsync(int &Centimeters)
    {
      switch(AsyncState)
      {
        case 0:
        {
          Centimeters = -1;
          digitalWrite(TriggerPin, HIGH);
          AsyncTime = micros();
          AsyncState++;
          break;
        }
        case 1:
        {
          if(micros() >= AsyncTime + 10)
          {
            AsyncState++;
            digitalWrite(TriggerPin, LOW);
            AsyncTime = micros();
          }
          break;
        }
        case 2:
        {
          if(digitalRead(DataPin) == HIGH)
          {
            AsyncState++;
            AsyncTime = micros();
    
          }
          else if(micros() - AsyncTime > Timeout)
          {
            Centimeters = 0;
            AsyncState = 4; 
          }
          break;
        }
        case 3:
        {
          if(digitalRead(DataPin) == LOW)
          {
            Centimeters = (micros() - AsyncTime) / 58;
            AsyncState++;
          }
          else if(micros() - AsyncTime > Timeout)
          {
            Centimeters = 0;
            AsyncState++;
          }
          break;
        }
        case 4:
        {
          Centimeters = -1;
          AsyncState = 0;
          break;
        }
      }
    }

    Copy the above files to your Arduino libraries located at C:\Program Files\Arduino\libraries. Please be aware that you might need to create a new folder.