Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

EDUCATION SERVICES

Wind River 5.x and Intel Gateway Solutions for IoT

Version 1.0 A

LAB GUIDE Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

LAB GUIDE Wind River Linux 5.x and Intel Gateway Solutions for IoT, Version 1.0 A Education Services Production Date: October 2014

Copyright 2014 Wind River Systems, Inc.

All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any means without the prior written permission of Wind River Systems, Inc.

Wind River, Tornado, and VxWorks are registered trademarks of Wind River Systems, Inc. The Wind River logo is a trademark of Wind River Systems, Inc. Any third-party trademarks refer- enced are the property of their respective owners. For further information regarding Wind River trademarks, please see:

http://www.windriver.com/company/terms/trademark.html

Wind River may refer to third-party documentation by listing publications or providing links to third-party Web sites for informational purposes. Wind River accepts no responsibility for the information provided in such third-party documentation.

This document is designed to support the Wind River Linux 5.x and Intel Gateway Solutions for IoT course. It is not designed as a stand-alone document, nor is it intended as a substitute for documentation that accompanies Tornado, VxWorks, or Wind River Workbench or any other Wind River Systems, Inc. software or hardware product.

http://education.windriver.com Education Services Department Wind River Systems, Inc. 500 Wind River Way, Alameda, CA 94501 510-748-4100 (phone) 510-749-2454 (fax) E-mail: [email protected] For training outside of North America, please contact your local sales office. Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Contents

1 Building and Customizing a Wind River Linux Platform Lab 1

2 Managing Wind River Linux Platforms in Workbench Lab 13

3 Integrating New Applications Lab 29

4 Patching Packages Lab 37

5 Integrating Compiled Applications Lab 43

6 Integrating Python Applications Lab 65

7 Reconfiguring Projects Lab 73

8 Creating Layers Lab 85

9 Getting Started with IDP 99

10 Generating Keys for IDP 117

11 Tamper-proof File System 127

12 Deploying Signed RPMS 133

13 Using McAfee Embedded Control 139

14 Configuring Encrypted Storage 155

15 Exploring Webif 171

16 Using IDP MultiWAN 187

17 Working with Lua and MQTT Software 199

18 Using OpenJDK 205

19 Integrating Python Applications 213

v Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

20 Integrating SQLite3 Applications 221

21 Using grsecurity 229

vi Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Building and Customizing a Wind River Linux Platform Lab

© 2013 Wind River Systems, Inc

1 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Building and Customizing a Wind River Linux Platform Lab

Objective In this lab, you will create, build, and test a new Wind River Linux platform using a simulated target. You will also learn how to:  make changes to the target file system  configure and build individual packages

NOTE: This lab should take approximately 45 minutes.

Setting Up the Build Environment In this section, you will set up a new Wind River Linux platform build environment using command line tools provided with the Wind River Linux product. The build environment provides all the tools and configuration needed to cross compile and deploy a Wind River Linux kernel and user space for a particular target. 1. In a shell on the host, create a new directory structure to house your platform build. This can be located anywhere you like, but in this example, use the directory $HOME/myplatform:

mkdir -p $HOME/myplatform cd $HOME/myplatform

2 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Building and Customizing a Wind River Linux Platform Lab

2. To establish the build environment for building the platform, you must invoke the Wind River Linux configure script. This script is located within the Wind River Linux product installation. Using syntax similar to GNU autoconf, configure supports a number of command-line arguments for selecting a BSP, kernel type, and file system profile, as well as many other settings. Commonly used options are summarized in the table below: Option Name Purpose --help Display an extensive list of supported options. --enable-board Specify the target BSP. --enable-kernel Select the type of Wind River Linux kernel to use. Select the type of Wind River Linux user space to --enable-rootfs use. --enable-build Select how software should be built. --with-layer Include an additional layer. --with-template Include an additional template. Enable the compiler cache (ccache) to speed up --enable-ccache build time. --with-ccache-dir Specify an external compiler cache directory. Bitbake shared state cache directory. Using a shared --with-sstate-dir state cache significantly improves build times. View the complete list of options available:

$WIND_BASE/wrlinux/configure --help

3. In this example, you will create a platform similar to the one shipped with the lab environment. Doing so will significantly reduce build time since the shared state cache found at /Labs/sstate can be used to accelerate the build.

$WIND_BASE/wrlinux/configure --enable-board=$BSP \ --enable-kernel=$KERNEL \ --enable-rootfs=glibc_small \ --with-sstate-dir=/Labs/sstate

The output of configure will stream by. Once configure finishes, your directory will contain the infrastructure needed to build and deploy your own customized . Take the time to familiarize yourself with the build environment. There are a few important directories to note:  The build directory hosts soft links to the build directories for each package. This subdirectory also hosts a Makefile used to build special targets associated with the packages. For more details, execute the following command:

make -C build help

Wind River Education Services 3 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

 The bitbake_build/conf directory contains the following important files:  local.conf, which contains crucial build configuration information. A soft link to this file is created in the top-level directory for your convenience.  bblayers.conf file lists the layers used in constructing the build environment.  The export directory will contain the output of the build, including:  An archive containing the target file system, which can be extracted directly to a device file system or NFS share  dist, a directory containing the target file system. When using a simulator such as QEMU, it mounts this directory as a root file system during boot.  The Linux kernel image. The name of this image might vary, depending on your target.  An archive containing the kernel modules.  The host-cross directory contains tools used to build the platform, including (but not limited to) the cross-compiling toolchain used to build programs for your target. Note that the directories inside host-cross are soft links to corresponding directories in bitbake_build/tmp/sysroots.  The directory layers/local constitutes a “local layer” which functions as a container for your project-specific customizations.  The layers directory also contains additional layers used in your project; the stock layers are all provided by the standard Wind River Linux installation, although you may include additional custom layers if needed.

4 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Building and Customizing a Wind River Linux Platform Lab

Building the Platform With a configured build environment in place, you may now build your platform. The output of this stage will be a Wind River Linux kernel image and root file system that are ready to use by the target; both will be found in the export directory as noted in the previous section. The time required to build a platform varies on a number of factors, not the least of which being the overall speed of your host. Other factors that have an impact are:  Whether or not the kernel needs to be built from source; a complete build of the kernel typically takes in the order of a half hour to an hour.  The number of target user-space packages that need to be built from source. A basic glibc_small system can be built entirely from source in about one to two hours. A glibc_std system, on the other hand, can take many hours.  Whether or not you are using a prepopulated shared state cache. If using a shared state cache containing all the needed objects, the above build time for a glibc_small system takes only minutes. To provide for a better lab experience, the lab environment you are using includes a shared state cache that prepopulated with all the objects needed to build a glibc_small system for your target. Leveraging this using the --with-sstate-dir argument minimizes the build time required. 4. To build your platform image, simply invoke make as follows:

make

5. After the build finishes, explore the contents of the export directory. In particular, take note of export/dist, which contains a complete copy of your target file system. Note however, that some file attributes aren’t quiet as expected. For example:

ls –l export/dist/dev -rw------. 1 wruser wruser 0 Jan 13 22:39 apm_bios -rw------. 1 wruser wruser 0 Jan 13 22:39 console -rw------. 1 wruser wruser 0 Jan 13 22:39 fb0 -rw------. 1 wruser wruser 0 Jan 13 22:39 hda -rw------. 1 wruser wruser 0 Jan 13 22:39 hda1 -rw------. 1 wruser wruser 0 Jan 13 22:39 hda10 -rw------. 1 wruser wruser 0 Jan 13 22:39 hda11 …

Wind River Education Services 5 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Compare this to what you see in /dev on your host:

ls –l /dev crw-rw----. 1 root video 10, 175 Jan 11 06:26 agpgart crw------. 1 root root 10, 235 Jan 11 06:26 autofs drwxr-xr-x. 2 root root 300 Jan 11 06:26 block drwxr-xr-x. 2 root root 80 Jan 11 06:26 bsg c------. 1 root root 10, 234 Jan 11 06:26 btrfs-control drwxr-xr-x. 3 root root 60 Jan 11 06:26 bus lrwxrwxrwx. 1 root root 3 Jan 11 06:26 cdrom -> sr0 drwxr-xr-x. 2 root root 3120 Jan 16 17:05 char crw------. 1 root root 5, 1 Jan 11 09:56 console …

Focus not on the entries themselves, but rather the ownerships and attributes. Notice that the entries in /dev on your host:  Have root:root ownership  Are primarily pipes or block or character device nodes rather than regular files (as evidenced by the b , c and p bits in the leftmost column)  The device nodes have major and minor numers associated with them (10,175, 5,1, etc) Whereas the entries in export/dist/dev all appear as regular files owned by wruser:wruser. The reason for this is because the entire build, including the generation of export/dist, was done as a regular user (wruser). Under these conditions, it would be impossible to generate device nodes or any files owned by root. Instead, the file system is built in a fake root environment called pseudo. To see the effect pseudo has on your view of the files, enter the pseudo environment and then reexamine the directory:

scripts/fakestart.sh ls –l export/dist/dev crw-rw---- 1 root 46 10, 134 Jan 13 22:39 apm_bios crw-rw--w- 1 root tty 5, 1 Jan 13 22:39 console crw------1 root root 29, 0 Jan 13 22:39 fb0 brw-rw---- 1 root disk 3, 0 Jan 13 22:39 hda brw-rw---- 1 root root 3, 1 Jan 13 22:39 hda1 brw-rw---- 1 root root 3, 10 Jan 13 22:39 hda10 brw-rw---- 1 root root 3, 11 Jan 13 22:39 hda11 …

Like magic, all is as it should be. Always remember that if you want to see the file system exactly as it was meant to be, that you must first enter the pseudo environment in which it was generated.

6 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Building and Customizing a Wind River Linux Platform Lab

6. To leave the pseudo environment, simply issue the command exit.

Deploying Your Platform With a built platform project in place, it is time to deploy and test your image on your target. For hardware targets, additional steps may be required as detailed in the Working with a Hardware Target lab. Otherwise, you can use the simulator to test your platform. 7. Test your platform in the simulator using the following command:

make start-target

8. Once your target boots, log in using the credentials root and password root. 9. Feel free to explore your target using the command-line shell. When done, the preferred method of shutting a Linux system is always using the poweroff command, although you can use other methods as well, as outlined in the Simulating Targets with QEMU lab.

Customizing the File System with changelist.xml In this section, you will tweak the target file system with the help of a changelist.xml file. This file will be located in the local layer and will be executed by the build system just before the final file system image is generated. Although these XML files might seem awkward to work with and edit, the main benefit is that they integrate nicely with the Workbench file system management tools. 10. Use a changelist.xml file to copy the README.txt file found in /Labs/BuildSystemLab directory into the /root directory of the target file system. To do this, create a file called changelist.xml in the conf/image_final subdirectory of the local layer (that is, layers/local/conf/image_final relative to the top-level directory of the project). Populate the file with the following content:

NOTE: This is important: the cl action line must be entered as one continuous line. Due to printing restrictions, it is broken across two lines in this document.

11. Once you have made your changes, rebuild the platform and start the target to test your changes. Verify that the file /root/README.txt can be found on the target, and that its contents match those on the host.

Wind River Education Services 7 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Customizing the File System with fs_final Scripts In this section, you will tweak the target file system with the help of some fs_final_*.sh scripts. Like changelist.xml files, these scripts will be located in the local layer and will be executed by the build system just before the final file system image is generated. Unlike changelist.xml files, fs_final scripts are plain shell scripts and are easier to write. But there is no integration with the Workbench file system management tools. 12. Use an fs_final script to add an /etc/motd file to your target file system. The contents of /etc/motd is displayed on the console right after you log in (motd originates from the phrase, “Message Of The Day”). To do this, create a file called fs_final_motd.sh in the same directory you used to create the changelist.xml file in the previous section. Populate the file with the following contents:

echo “Welcome to your Wind River Linux 5.x image” > etc/motd

NOTE: The lack of a leading slash in etc/motd is intentional. The fs_final scripts are executed in the root directory of the target file system, but are not executed within a chrooted environment. This allows fs_final scripts to have full access to the host file system as changelist.xml files do; but careful attention must be paid when referencing files. In this example, if you inadvertently wrote /etc/motd, you would actually be referring to /etc/motd in the host file system.

13. Rebuild your image and redeploy the updated image to your target. Log in to verify that your changes have taken effect; you should see the contents of the motd file display after you log in.

14. To see the benefits of the fs_final mechanism, suppose you want to embed information into your root file system that is not static. Suppose, for example, that you wanted to embed the build date and board name into the motd. Add the following code to fs_final_motd.sh:

echo “This image was built on $(date)” >> etc/motd

15. Now rebuild and redeploy the updated image to your target again. Log in to verify that your changes have taken effect. Notice that the date in the motd is hard-coded to the exact time that the fs_final_motd.sh script was executed in building the file system image.

8 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Building and Customizing a Wind River Linux Platform Lab

16. Now, apply what you’ve learned to create a new fs_final script that creates a FIFO entry, /mypipe with mode 0777. If you’re having difficulty, consult the online manual:

man mkfifo

If you’re stuck, a solution can be found in /Labs/BuildSystemLab/fs_final_fifo.sh. Simply copy this solution into the same directory as fs_final_motd.sh, rebuild the file system, and deploy the image to the target.

Customizing and Building Individual Packages Currently, your platform is built using the packages that ship with the Wind River Linux product. It’s possible to rebuild individual packages from source if needed. Common reasons for wanting to do this include:  You wish to apply a patch to the source of a particular package  You want to make configuration changes to a package  You want to be able to debug the software provided by a particular package. In this section, you will focus on the busybox package, which provides the core run-time for glibc_small systems. In this exercise, you will modify the source of the ls program to print an additional message when run. 17. To modify the source to busybox, open a development shell for the package, as follows:

$ make -C build busybox.devshell

This will open a new terminal where the busybox source is located with all relevant patches already applied. Note the name of the directory where the terminal opens, busybox-1.19.4, which will be used in a later exercise. 18. Edit the code which implements the ls command provided by coreutils/ls.c. Add an additional message to beginning of the ls_main() function; for example: init_unicode(); fprintf(stderr, "Hello from ls\n"); if (ENABLE_FEATURE_LS_SORTFILES) … 19. Once you finish editing the file, exit the development shell by typing exit or pressing CTRL+D. You will be taken back to your original shell.

Wind River Education Services 9 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

20. Now, rebuild busybox with your source changes:

make -C build busybox.rebuild

With the package rebuilt, once again rebuild the image and deploy it to the target to test your changes. Verify that every time you invoke the ls command, your message appears. Note that the changes you have made are only temporary. If you do a clean, distclean, or cleansstate, your changes will be lost, and the original behavior of ls will be restored. 21. Now that you have seen how to modify software for your platform, clean the build area as follows:

make -C build busybox.clean

22. Rebuild busybox, then rebuild the image and deploy it to your target. Now you will notice that the behavior of ls is restored to its original state.

Building a Boot Image As you have seen, building a kernel and target file system is relatively straightforward. The product of this build is:  A target file system rooted at export/dist  A compressed archive containing the file system contents in the export directory When deploying to hardware, you will often need a boot image; that is, a self-contained file system image for deploying on to some form of medium; for example, flash storage. Wind River Linux provides support for many common boot image formats:  JFFS2 is derived from the original Linux flash file system, JFFS. JFFS2 is a journaling read-write file system which performs on-the-fly compression. Operating on top of the MTD subsystem, JFFS2 addresses the unique requirements of flash, such as wear leveling.  UBIFS is a read-write file system designed specifically for raw NAND flash. It takes care of bad sectors in flash by implementing a logical layer that maps used flash sector numbers to only good sectors in the physical media. UBIFS is supported natively by the Linux kernel. Note that to deploy a UBIFS file on the target’s NAND you need to “ubinize” the UBIFS file first to generate a .ubi file.  CPIO is a common packing format used to pack the root file system into a single file. This file, usually in a compressed form, can then be appended to the kernel image itself in such a way that the Linux boot logic can use it as a root file system contained entirely in RAM.

10 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Building and Customizing a Wind River Linux Platform Lab

23. Reconfigure the project to generate JFFS2 and CPIO images by editing the file local.conf in your project directory and appending the following:

IMAGE_FSTYPES += “jffs2 cpio.gz” Again, the syntax might seem a little peculiar, but this is again a fragment of Python code used by At a high level, IMAGE_FSTYPES lists the types of images to build. Refer to local.conf for a full list of supported types. 24. Once you have saved your changes to the file local.conf, rebuilt your project. When this finishes, you will see three files in the export/images directory with the suffixes .jffs2 and .cpio.gz.

This concludes the lab. Do not proceed.

Wind River Education Services 11 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

12 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

© 2013 Wind River Systems, Inc

13 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Managing Wind River Linux Platforms in Workbench Lab

Objective In this lab, you will learn how to create and manage Wind River Linux platform projects in Workbench. You will also learn how to import existing Wind River Linux platforms into your Wind River Workbench workspace.

NOTE: This lab should take approximately 30 minutes.

Creating New Platform Projects In this section, we will set up a new Wind River Linux platform project in Workbench. 1. From the Workbench menu, select File > New > Wind River Workbench Project. 2. In the New Wind River Workbench Project dialog, select Wind River Linux Platform Base 5.0.1. 3. Click Next.

2

3

14 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

4. In the Build type field, select Platform. 5. Click Next.

4

5

Wind River Education Services 15 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

6. In the Project name field, enter myplatform_wb as the name for your new project and select Create project in workspace. 7. Click Next.

6

7

16 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

8. The next stage of the wizard provides access to all of the options that the command- line configure utility provides, the most important ones being incorporated directly into the GUI. For example:  The Board field corresponds to --enable-board.  The Production build setting corresponds to --enable-build=production.  The Layers and Templates lists provide interfaces to --with-layer and --with- template, respectively.  For all the rest, there is a generic UI near the bottom which allows you to specify arbitrary configuration options In the Board field, select a value matching $BSP in your lab environment.

NOTE: Use the shell command echo $BSP to obtain a value for the Board field.

9. In the RootFS field, select glibc_small. In the Kernel field, select $KERNEL.

NOTE: Use the shell command echo $KERNEL to obtain a value for the Kernel field.

10. Lastly, specify your sstate cache to expedite the build, as you did in the Building and Customizing a Wind River Linux Platform lab. Since there is no direct option for this in the main window, select Add. If the Add button is not visible, collapse the dialog to bring it into view by clicking the <

Wind River Education Services 17 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

8 9

10

11

18 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

11. In the Configure Options dialog, scroll down to locate and select the option --with- sstate-dir. 12. In the Options field, enter the value /Labs/sstate, or click Browse to navigate to the directory. 13. Click OK.

12 13 14

Wind River Education Services 19 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

14. In the New Wind River Linux Platform Project dialog, focus on the Configure command field (you may have to collapse the Advanced panel to see it). Notice how the command correlates to the command you used to configure a new platform project in the Building and Customizing a Wind River Linux Platform lab.

NOTE: Your exact command may appear differently, depending on the value of $BSP and $KERNEL in your lab environment.

15. Click Finish.

1315

16

20 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

16. Workbench will call out to configure to generate your build environment. This may take a few moments.

17. Using a file browser or a command-line terminal, navigate to your workspace directory. Note that Workbench has actually created two directories in the workspace for your new project:  The first directory, myplatform_wb, is named to match the project you created. This directory contains a small Workbench project that functions as a wrapper for the real platform project.  The second directory, suffixed with myplatform_wb_prj, contains the actual Wind River Linux platform project, and is identical in every respect to a platform project created from the command-line. In fact, you can manage this project outside of Workbench using techniques learned in the Building and Customizing a Wind River Linux Platform lab.

Wind River Education Services 21 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Building the Platform With a configured build environment in place, you may now build your platform. 18. In the Project Explorer view, under the myplatform_wb project, right-click on the fs project. 19. From the context menu, select Build Target.

19

20

20. As discussed previously, a platform build can be very quick or time-consuming, depending on a number of factors. The Build Console view displays the build output.

22 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

Importing Existing Platforms into Workbench Sometimes you may have a Wind River Linux platform which you configured from the command line. Workbench allows you to remotely control the platform by importing it into your workspace, leaving the original platform in its original spot on the file system. In this section, you will import the platform project you created in the Building and Customizing a Wind River Linux Platform lab, which you created in the directory /home/wruser/myplatform. 21. From the main Workbench menu, select File > Import. 22. In the Import dialog, select Wind River Linux > Existing Wind River Linux Platform Project from the Wind River Linux group. 23. Click Next.

23 24

24. Click Browse, then navigate to the directory containing the existing platform.

25

Wind River Education Services 23 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

25. Use the browser to navigate to the directory containing the platform project you wish to import. 26. Click OK.

26 27

24 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

27. In the Import dialog, you may now change the default name assigned to the project if you wish. This is the name of the Workbench project that displays in your workspace, and it has no effect on the original Wind River Linux platform. 28. Click Finish.

28 29

Wind River Education Services 25 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

29. Once the project creation finishes, the result will be as if you’d created the project from scratch using Workbench. You can manage the project from within Workbench via the myplatform-import project, or you can manage the platform at /home/wruser/myplatform using command-line techniques. The notable exception here is that the actual platform directory remains where it was originally, rather than residing in the workspace directory.

Deploying Your Platform With a built platform project in place, it is time to deploy and test your image on your target. For hardware targets, additional steps may be required as detailed in the Working with a Hardware Target lab. Otherwise, you can use the simulator to test your platform, as outlined in the Simulating Targets with QEMU lab. 30. Once your target boots, the following greeting displays.

Wind River Linux 5.0.1.0 qemu0 console

qemu0 login:

Log in as the user root, with the password root. 31. Feel free to explore your target using the command-line shell. When you are done, the preferred method of shutting a Linux system is always using the poweroff command, although you can use other methods as well, as outlined in the Simulating Targets with QEMU lab.

26 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Managing Wind River Linux Platforms in Workbench Lab

Deleting Projects To manage your workspace and disk space usage, you may need to delete projects from time to time, since built Wind River Linux platform projects can occupy several gigabytes of storages space. 32. In the Project Explorer view, right-click on the project you wish to delete. 33. In the context menu, select Delete.

33 34

Wind River Education Services 27 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

34. The Confirm Platform Project Delete dialog provides the following options:  Select Delete project description files on disk to delete the Workbench wrapper project (the myplatform_wb directory in this case) from the disk.  Select Also delete complete contents of platform projects to delete both the wrapper and the underlying Wind River Linux platform project (the myplatform_wb_prj directory in this case).  Select neither item to delete only the project from the workspace. 35. Click Yes.

35

36

This concludes the lab. Do not proceed.

28 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating New Applications Lab

© 2013 Wind River Systems, Inc

29 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Integrating New Applications Lab

Objective In this lab you will learn the basics of how to integrate third-party software components into Wind River Linux platforms.

NOTE: This lab should take approximately 30 minutes.

Lab Overview Wind River Linux comes with hundreds of validated software packages that are ready to use in Wind River Linux platforms. If you need a software package that is not included, or if you must integrate an application being developed in-house, you must integrate the package into the Wind River Linux build system and cross- compile it along with the rest of your platform software. A properly integrated package makes it easy to include the package into other projects as well. This lab uses a simple C application as a way to introduce the basic concepts behind the application integration process. The application is an implementation of the Tic-Tac-Toe game where the computer is the O player and you are the X player. You always have the advantage of the first move. The application is entirely contained in a single C file. All the integration steps will be done manually.

Before You Begin This lab modifies the configuration of an existing platform project. Use the pre-built project provided with your lab environment. Refer to the Getting Started lab to identify where to find this project in your lab environment. The location of this project will be referenced as $TARGET_BASE throughout this lab. This lab uses a command-line environment. Take the time now to open a command-line terminal and navigate to this directory.

The Packaging Workflow The purpose of this lab is to create a package for the application that you can integrate into the build system so you can operate on it as you would on any package normally bundled with Wind River Linux. The following describes the general packaging workflow:  Select a name for the application. You will use this name when creating the directories and files associated with the package. In this lab you will use the name tic-tac-toe.

30 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating New Applications Lab

 Select the build layer where you will maintain the new package. When you configure a platform project, Wind River Linux enables the local layer by default (in the directory layers/local of your platform project). In this lab you will maintain the tic-tac-toe application in the local layer. If you use any other layer you must use the option --with-layer when you configure your project (so the build system knows about it).  Define the license to associate with the application, and ensure that you have the full text of the license agreement available as one or more text files. Remember that it is a good practice to add an abridged version of the license at the beginning of all your source files. In this lab you will use the GPLv3 license.  Make the application and support files available to the build system in some convenient location (using a URL pointing to the location) in a format supported by the build system (a local or remote file, a Git repository and branch, or a subversion repository and commit number). In this lab you will use a URL pointing to a tar file in the directory /Labs/Packages.  Build the directory infrastructure inside the selected layer to tell bitbake about the new package, (including a new bitbake recipe file with the package details) and add all the support files.  Test the build and fix any problems. Repeat this workflow until your new package works as expected.

About the Tar File You can use any name for the application tar file — however, the general convention is to use the name of the application and the version number, separated by either a hyphen or an underscore character. In this lab you will use the base name tic-tac-toe-1.0. The file extension must be a recognized format so that bitbake can use the appropriate set of tools to extract the source code. Valid extensions include .tar, .tar.gz, .tar.bz2, .cpio, and .zip. In this lab you will use the extension .tar.gz. The tar file for the application is /Labs/Packages/tic-tac-toe-1.0.tar.gz. After bitbake extracts the tar file it expects to see a top directory named the same as the name and version number of the application (for example, tic-tac-toe-1.0). bitbake then looks inside for files with well-known names (such as Makefile, configure, and files with extensions such as .c or .cpp) to determine how to build the package. You can always make things differently and override how bitbake unpacks your application and how it analyzes the structure of the application. However, by following the default conventions you make the packaging exercise much easier.

Wind River Education Services 31 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

The following figure shows the content of the tar file /Labs/Packages/tic-tac-toe- 1.0.tar.gz. |-- tic-tac-toe-1.0 |-- COPYING |-- Makefile `-- ttt.c

About bitbake Recipe Files A recipe file provides bitbake with the necessary details to build the package (such as where to find the source, the license details, and the version number). Recipe files names have three components — the package name and the version number (separated by an underscore character) and the file extension. In this lab the recipe file name is tic-tac-toe_1.0.bb. The extension bb in the file name stands for bitbake and identifies this file as a bitbake recipe. You can use the extension .bbappend with a bitbake recipe file when the recipe file adds application context to an original .bb file located somewhere else. Typically this occurs when you want to add or modify the default build steps of a recipe provided by Wind River Linux or some third party organization. In these cases you create a .bbappend file that describes only the pieces you want to add, knowing that the .bb file provides the bulk of the recipe. This lab does not use .bbappend recipe files.

Creating the Layer Structure 1. Open a command-line terminal and navigate to the directory $TARGET_BASE directory. 2. Execute the following command to add the directory structure to your platform project. Note that the local layer already has several other directories and files on it — do not touch them.

mkdir -p layers/local/recipes-applications/tic-tac-toe/files

The directory recipes-applications is the directory where you will maintain your own application packages. You can use any other directory name, but it must follow the pattern recipes-* for bitbake to recognize it as a source of packages. The file layers/local/layer.conf defines the valid patterns. The subdirectory tic-tac-toe is where you will maintain the application. It hosts the bitbake recipe file and other support files that you may need in the future. The subdirectory files is a utilitarian directory found in most maintenance directories. As the application evolves over time you will likely create patches, documentation files, and other objects that you want to keep together inside the build system. This lab does not use this directory, but you will include it in the bitbake search path for future use.

32 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating New Applications Lab

3. Create the recipe file layers/local/recipes-applications/tic-tac-toe/tic-tac-toe_1.0.bb for the package with the following content. The file is also available from the directory /Labs/Packages. # Copyright (C) 2013 Wind River Systems # Release under the GPLv3 license

SUMMARY = "The TIC-TAC-TOE game, console edition" DESCRIPTION = "An engaging and time killer console game" HOMEPAGE = "http://apps.company.com/tic-tac-toe"

FILESEXTRAPATHS_prepend := "${THISDIR}/files:" LICENSE = "GPLv3" LIC_FILES_CHKSUM = "file://COPYING;md5=d32239..." PR = "r1" SRC_URI = "file:///Labs/Packages/${PN}-${PV}.tar.gz" SRC_URI[md5sum] = "f4368e..." SRC_URI[sha256sum] = "b2c702..."

do_install() { install –d ${D}${bindir} install –m 0755 tic-tac-toe ${D}${bindir} } 4. The code above omits the full checksum values for clarity purposes. Execute the following commands to retrieve them from the application tar file, then update the values in the recipe file (the two lines with the variables SRC_URI[md5sum] and SRC_URI[sha256sum]) to match the retrieved values.

md5sum /Labs/Packages/tic-tac-toe-1.0.tar.gz sha256sum /Labs/Packages/tic-tac-toe-1.0.tar.gz

5. Execute the following command to unpack the application so that you have access to the source code.

make -C build tic-tac-toe.unpack

6. Execute the following command to retrieve the checksum value of the license file.

md5sum build/tic-tac-toe-1.0-r1/tic-tac-toe-1.0/COPYING

7. Update the value of the variable LIC_FILES_CHECKSUM in the recipe and save the file.

Understanding the Recipe File The sample recipe file you just created is about the minimum size you can have. It can be shorter if you remove comments and some documentation string variables, or as complex

Wind River Education Services 33 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

as you need it to be. The following provides short descriptions of the variables in the recipe:  SUMMARY, DESCRIPTION, HOMEPAGE — These are description variables that you can omit. They provide information about the recipe, and some tools may use them — you should always define these variables.  FILESEXTRAPATHS_prepend — bitbake prepends the value of this variable to the list of paths it uses when searching for source and support files. Note the colon at the end, which separates entries in the path expression. The expression ${THISDIR} is expanded to contain the directory where the recipe file is located (in this lab, /home/wruser/myplatform/layers/local/recipes-applications/tic-tac-toe). The whole expression ${THISDIR}/files then adds the subdirectory files to the search path.  LICENSE and LIC_FILES_CHKSUM — These variables define the licenses to apply to the application. Most well-known open source licenses (such as GPLv2, LGPLv2.1, BSD, and MIT) are predefined. The variable LICENSE accepts complex expressions — for example, a dual license (with a value like GPLv2 + MIT) or multiple licenses (with a value like BSD & MIT).  PR — The name of this variable represents the product revision. The default value is r0 — for clarity you should make this variable explicit in the recipe.  SRC_URI — This variable lists the source files that make up the package. This lab uses the URL prefix file:// but you can use other values such us http://, git://, and ftp://. It also uses the automatic variables PN (the package name) and PV (the package version) —this lab uses the values tic-tac-toe and 1.0 (as indicated by the name of the bitbake recipe file).  SRC_URI[md5sum] and SRC_URI[sha256sum] — These variables provide the checksum values of the source file. bitbake uses these values to verify the integrity of the source files.  do_install() — bitbake invokes this shell function to install the executable files of the application in the final target image. This lab uses the command install to create the destination directory (if it does not already exist) and to copy the binary file tic-tac-toe. The function uses D and bindir. The variable D expands to the destination directory where the target image is assembled. The variable bindir expands to /usr/bin. When the target boots, the application binary will be /usr/bin/tic-tac-toe.

Building the Tic-Tac-Toe Package 8. Execute the following command to add the package tic-tac-toe to the list of packages to build in your platform project.

make -C build tic-tac-toe.addpkg

34 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating New Applications Lab

9. Execute the following command to build the package.

make -C build tic-tac-toe

10. Execute the following command to build the project.

make

After the platform project builds, the directory export/dist contains a copy of the target root file system. 11. Execute the following command to verify that the binary tic-tac-toe is part of the new target image.

ls -l export/dist/usr/bin/tic-tac-toe -rwxr-xr-x 1 wruser wruser 10392 Aug 2 14:40 ...

12. If time permits, try the program on your target. The tic-tac-toe binary found in /usr/bin on the target file system.

This concludes the lab. Do not proceed.

Wind River Education Services 35 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

36 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Patching Packages Lab

© 2013 Wind River Systems, Inc

37 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Patching Packages Lab

Objective In this lab you will learn how to make permanent modifications to packages that ship with Wind River Linux.

NOTE: This lab should take approximately 30 minutes.

Lab Overview In the Building and Customizing a Wind River Linux Platform lab, you learned how to change the source code for a package included with the standard Wind River Linux product. Knowing how to do this comes in handy in situations like the following:  you find a bug that you must fix  you wish to add functionality not present in the standard package distribution  you want to change some aspect of the package configuration The techniques learned in the Building and Customizing a Wind River Linux Platform lab were only temporary — your changes were lost when you cleaned the package build directory. This lab will show you how to capture changes into patches that you can place into a layer, where you can be keep the changes indefinitely or share them with other projects.

Before You Begin This lab modifies the configuration of an existing platform project. Use the pre-built project provided with your lab environment. Refer to the Getting Started lab to identify where to find this project in your lab environment. The location of this project will be referenced as $TARGET_BASE throughout this lab. This lab uses a command-line environment. Take the time now to open a command-line terminal and navigate to this directory.

38 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Patching Packages Lab

Capturing Source Changes as a Patch In the Building and Customizing a Wind River Linux Platform lab, you saw that changes you make to packages in their build directory persist only as long as the package is not cleaned up with a command such as make -C build .clean. Often you will want your changes to be more permanent. You may also want to propagate these changes to other projects or other developers in your team. In this section, you will learn how to capture your changes into a patch. You can readily share patches with others, or embed them into a layer to easily reproduce your patch in other projects. In this section, you will focus on the busybox package, which provides the core run time for glibc_small systems. In this section you will modify the source of the program ls to print an additional message when you run it. 1. To modify the source to busybox, execute the following command to open a development shell for the package.

make -C build busybox.devshell

This opens a new terminal where the busybox source is located with all relevant patches already applied. Note the name of the directory where the terminal opens (busybox-1.19.4), which you will use in another exercise. 2. In the development shell, use the quilt utility (included with Wind River Linux) to assist in generating the patch. You can generate patches yourself manually, but the quilt utility simplifies the process greatly, particularly when you are working with several patches. Execute the following command to initialize a new patch.

quilt new add-ls-banner.patch Patch patches/add-ls-banner.patch is now on top

3. Now, execute the following command to instruct quilt to begin watching ls.c for changes.

quilt add coreutils/ls.c File coreutils/ls.c added to patch patches/add-ls-banner.patch

4. Edit the code that implements the ls command provided by coreutils/ls.c. Add an additional message like the following to the beginning of the function ls_main(). init_unicode(); fprintf(stderr, "Hello from ls\n"); if (ENABLE_FEATURE_LS_SORTFILES) …

Wind River Education Services 39 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5. With your changes saved, instruct quilt to update the patch file based on the current state of the files being watched:

quilt refresh Refreshed patch patches/add-ls-banner.patch

Examine the contents of patches/add-ls-banner.patch. You will see that it describes the changes you have made to ls.c. 6. Execute the following command to copy the patch to your home directory.

cp patches/add-ls-banner.patch ~

7. Exit the development shell.

Saving Source Changes in the Local layer In this section, you will learn how to make source changes permanent within your project by embedded them into the local layer. Once there, the changes are in a format that you can easily migrate to a custom layer to share with other projects. To accomplish this task, you must do the following:  Create a directory structure in the local layer to host your changes.  Add patch file(s) describing your changes.  Create a .bbappend file describing the name and the location of the patch file(s). 8. Execute the following command to make a directory.

mkdir –p layers/local/recipes-local/busybox

9. Execute the following command to copy the patch from the previous section and place it in the directory you just created.

cp ~/add-ls-banner.patch \ layers/local/recipes-local/busybox

40 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Patching Packages Lab

10. As a last step, create the file layers/local/recipes- local/busybox/busybox_1.19.4.bbappend with the following content. FILESEXTRAPATHS_prepend := “${THISDIR}:” SRC_URI += “file://add-ls-banner.patch” Although the syntax might seem a little peculiar at first, particularly if you’re not familiar with the Python programming language, it should seem pretty clear what these two lines of code are accomplishing. At a higher level:  The bitbake construct FILESEXTRAPATHS_prepend adds the directory containing your .bbappend file (referenced by ${THISDIR}) to the head of the list of paths to search for content (that is, your patch file).  SRC_URI is updated to include your patch file. 11. With your .bbappend and patch files in place, rebuild the busybox package.

make -C build busybox.rebuild

12. Build the project.

make

13. Try your new implementation of the ls command using busybox. Start the target, as outlined in the Getting Started lab, and execute the following command on the target:

busybox ls Hello from ls bin dev home ... boot etc lib ...

NOTE: The native command ls in this configuration is implemented by a package called coreutils, not by busybox. By invoking the command busybox ls above you are invoking the busybox implementation of ls which is the one you want to test. If you want to modify the command ls used by the system you can follow the procedure in this lab but operating on the coreutils package instead.

This concludes the lab. Do not proceed.

Wind River Education Services 41 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

42 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

© 2013 Wind River Systems, Inc

43 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Integrating Compiled Applications Lab

Objective In this lab you will learn how to integrate software which must be compiled into Wind River Linux platforms.

NOTE: This lab should take approximately 90 minutes.

Lab Overview Wind River Linux comes with hundreds of validated software packages which are ready to use in Wind River Linux platforms. Still, you will likely one day need a software package that is not included, or, you will be asked to integrate an application being developed in house. When that happens, you must integrate the package into the Wind River Linux build system, so that the package can be cross- compiled along with the rest of your platform software. A properly integrated package makes it easy to include the package into other projects as well. This lab will walk you through the integration of three examples you’re likely to encounter:  Packages driven by autoconf. These packages include a configure script, which you run before building the software with make. Configure probes the characteristics of the system it is running on, and generates customized Makefile and header files to enable the software to be built on that system.  Packages driven by a Makefile. In this scenario, the package does not automatically configure itself for the system it is being built on; rather it relies on the skills of the person who wrote the Makefile to ensure that it will compile on a wide variety of platforms.  A Wind River Workbench application project. These projects are based on Makefiles, but have unique constraints on how they are built, due to the managed build system that Workbench provides.

Before You Begin This lab modifies the configuration of an existing platform project. Use the pre-built project provided with your lab environment. Refer to the Getting Started lab to identify where to find this project in your lab environment. The location of this project will be referenced as $TARGET_BASE throughout this lab. This lab uses a command-line environment. Take the time now to open a command-line terminal and navigate to this directory.

44 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

Integrating Packages Driven by Autoconf In this section, you will work with a package called links, which implements a text-based web browser. This package can be downloaded using the following URL: http://www.jikos.cz/~mikulas/links/download/links-1.00pre23.tar.gz. For your convenience, a pristine copy of the upstream source is provided in the directory /Labs/Packages. The build system for links is configurable using autconf. autoconf provides a framework for generating a configure script, which the builder runs before building the software for the first time. This configure script detects and records various system settings needed to build the software, and generates custom Makefiles and header files according to those settings. This makes building the software easier on a variety of different systems, and also works well in a cross compiling environment like Wind River Linux. In this exercise, you will integrate this package using the local layer provided by all Wind River Linux platform projects. 1. Run the following command to start the package importing tool. This tool simplifies the task of integrating a new package by performing many of the routine initialization tasks.

make import-package

Wind River Education Services 45 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

2. The package importer GUI will appear. Set the Package Type field to Source Package. 3. If you have network access, you can enter the URL of the package into the Package Location text field. Otherwise, you may type the location of the package archive, or click Browse to use the GUI to locate the archive file.

2 3

46 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

4. Use the file system browser to locate the archive in /Labs/Packages and click OK.

4

Wind River Education Services 47 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5. Back in the main window, click Update to ensure that the tool picks up settings from the package location you entered. 6. Notice that the tool has automatically picked up proper values for Package Name and Version. 7. Now click IMPORT.

7 6 5

48 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

8. The tool will now copy the archive and generate a recipe template in your project’s local layer. You will see a progress report in the Progress area of the GUI. Once the operation succeeds you will see that the last log line says Package Import Completed! 9. Press Close to dismiss the window.

8 9

Wind River Education Services 49 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

10. Take note of the files which the package import tool added to your project:  layers/local/downloads/links-1.00pre23.tar.gz, which contains a local copy of the upstream source.  layers/local/recipes-local/links/links_1.00pre23.bb, which is a recipe template that you will have to finish customizing before you can proceed to build the links package.

NOTE: The package import tool also adds the new package to your image automatically.

Open the links_1.00pre23.bb file in the editor of your choice. The main objective at this point is to proceed through this file and customize the settings for your package. 11. The first items that need consideration are LICENSE and LIC_FILES_CHKSUM. These properties relate to the license associated with the software you’re importing. Because licensing is such an important consideration when deploying devices based on open source software, the notion of license awareness is tightly coupled into the build system. This awareness manifests itself at the package level in these two properties, which must be set accordingly:  LICENSE: this must describe the type of license governing the distribution of the package you’ve imported.  LIC_FILES_CHKSUM: this specifies the file containing the license terms as well as a reference MD5 checksum of the license text. This is used to authenticate the license text. If the licensing terms change in a future revision of the package, the MD5 checksum will no longer match the value recorded in the recipe, and the builder of the software will be warned. 12. To determine appropriate settings for LICENSE and LIC_FILES_CHKSUM, you must consult the package contents to determine the licensing terms and where these terms are recorded. With the package added to the local layer, you can easily extract the package source at this point:

make -C build links.unpack

50 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

The extracted source of the package can now be found in the directory build/links- 1.00pre23-r0/links-1.00pre23. The exact location of the licensing terms varies by package, although you will often find a file called LICENSE, license.txt, or COPYING which specifies the license terms. Sometimes it is even specified at the top of source, header, or Makefiles. You will find that the license for links is disclosed in the file COPYING. Referring to this file, the license disclosed is clearly GPLv2. So, set the values for the two license-related properties in links_1.00pre23.bb accordingly. SUMMARY = "The links package" DESCRIPTION = "The links package" HOMEPAGE = "http://www.your_company_here.com" LICENSE = "GPLv2" SECTION = "devel"

# You need to checksum the license for this package. Leave the… # and on the first compile pass bitbake will tell you what value… # This example is for a whole file... LIC_FILES_CHKSUM = "file://COPYING;md5=" # This example is for a section of a file... #LIC_FILES_CHKSUM = "file://Makefile;beginline=3;endline=9;md5=" 13. Because there is a dedicated file for the license, calculating the required checksum is a straightforward process using the md5sum utility:

md5sum build/links-1.00pre23-r0/links-1.00pre23/COPYING b0c80473f97008e42e29a9f80fcc55ff COPYING

Complete the LIC_FILES_CHKSUM line in links_1.00pre23.bb using the value you obtained: # This example is for a whole file... LIC_FILES_CHKSUM = "file://COPYING;md5= b0c80473f97008e42e29a9f80f…" # This example is for a section of a file...

NOTE: You can also let bitbake calculate the value for you by leaving this field empty. The first time you attempt to build the package, bitbake will complain. In the error message, it will tell you what the expected value should be, which you can then copy and paste into your recipe.

Wind River Education Services 51 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

14. Proceeding further down the recipe you will see places to declare package dependencies. #DEPENDS = "" #RDEPENDS_links="" If your package has build time dependencies (for example, it needs a particular to link against, or requires some unusual host tool to build), DEPENDS is how you declare these requirements. If, on the other hand, the package has run time dependencies (for example, it needs a particular system utility or shared library to function properly), RDEPENDS is how you declare these requirements. For now, leave these fields commented out. Dependencies can be fleshed out later when you attempt to build or run the software. 15. Next, adjust SRC_URI to reflect the URL of the package. This was provided in the beginning of this section. It is important to fill this out, even if a local copy of the archive is provided, since bitbake uses this value to determine the filename of the archive to search for in the downloads directory. # This is were you set the package tarball upstream location… # name at the end of the path is used as the package's tarba… # searched in the local 'download' directories. SRC_URI = "http://www.jikos.cz/…/links-1.00pre23.tar.gz" 16. To validate the integrity of the archive, bitbake uses SRC_URI[md5sum] and SRC_URI[sha256sum]. As before, you can leave these blank and allow bitbake to tell you the values to fill in, or you can obtain these values and fill them in now as follows. Obtain the value for SRC_URI[md5sum]:

md5sum layers/local/downloads/links-1.00pre23.tar.gz 4311895409dcf03125d767d645fdabf6 links-1.00pre23.tar.gz

Execute the following command to obtain the value for SRC_URI[sha256sum].

sha256sum layers/local/downloads/links-1.00pre23.tar.gz 6c90e08a0fd96bafb0878529ff855c36b8881762d75b1c6fc609209b2e05254a links…

52 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

17. Often, packages need additional arguments passed in when their makefile is invoked. EXTRA_OECONF is provided for this purpose. Without close examination of the makefile, it’s difficult to know what arguments (if any) to provide here. So it might be just as easy to leave this value alone until you attempt to build the package. If the do_build or do_install tasks are misbehaving, it’s often because some additional argument must be passed in. At that point, you would study the makefile to see if any additional arguments must be passed in. 18. Examining the package source code, you will see by the structure that it is clearly driven by autoconf, as evidenced by the presence of configure, Makefile.in, etc. Thus, you must enable autotools functionality by uncommenting the line in the recipe: # Enable this if the package uses automake/configure inherit autotools 19. Lastly, you will see that the tool has provided a do_install() task, which is populated with code which copies out a binary called my_bin. Clearly this is boilerplate code which must be customized for your package. Studying the package’s Makefile (or in this case, Makefile.in, since a custom Makefile is generated when configure is run) is the best way to determine what needs to be done in a do_install task. If the Makefile has an install rule (which most well- written Makefiles do), then you can usually just use the default do_install task provided by the autotools class, which is shown below: autotools_do_install() { oe_runmake 'DESTDIR=${D}' install # Info dir listing isn't interesting at this point so… if [ -e "${D}${infodir}/dir" ]; then rm -f ${D}${infodir}/dir fi }

NOTE: You can see this code, as well as all the code that implements the autotools class, in the file layers/oe-core/meta/classes/autotools.bbclass.

To use the default do_install() task, simply delete the do_install task that was provided by the import-package tool. 20. Save the changes to links_1.00pre23.bb and make your first attempt to build the package.

make -C build links

If you chose to leave the MD5 value for LIC_FILES_CHKSUM blank, the build will fail immediately with error reports associated with the license checksum similar to the following:

Wind River Education Services 53 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

ERROR: links: md5 data is not matching for file://COPYING;md5= ERROR: links: the new md5 checksum is b0c8047...

In that case, copy the MD5 checksum value listed in the error report into the appropriate place in links_1.00pre23.bb. Otherwise, the build will proceed through the various stages, which consists of the following tasks:  Unpack the source archive into the build stage directory, which you already did this manually earlier in this section.  Patch the extracted source with patches listed in the recipe, if applicable. In this case, there were no patches to apply.  Configure the source for the build environment. In this case, bitbake calls the configure script in the build stage directory.  Compile the source contained in the build stage directory by calling make.  Install the software into an install stage directory by invoking make install, as specified in the do_install task you created.  Generate binary RPMs based on the contents of the install stage. 21. Since the package import tool automatically adds the package to your image, you do not need to add it to your image explicitly. Instead, go ahead and build your image.

make

22. Once the build completes, perform a quick sanity check to verify that the links executable can be found within the target file system:

find export/dist -name links export/dist/usr/bin/links

23. Feel free to take the time to deploy your new image to the target to test links. Assuming that you followed the instructions carefully, this exercise likely seemed unexpectedly easy. The reality is that packages driven by autoconf are usually very easy to integrate, as the bitbake build engine is designed to work harmoniously with these types of packages.

Integrating Packages Driven by a Makefile For this example, you will import a package called figlet, which is a program that renders large decorative printing using standard ASCII characters. Figlet can be downloaded from ftp://ftp.figlet.org/pub/figlet/program/unix/figlet-2.2.5.tar.gz, but a pristine copy in contained in the directory /Labs/Packages.

54 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

This package, like many open source packages, has not been developed to use autoconf. Rather, the build is driven by a static makefile. The degree of difficulty involved in integrating packages like this one largely depends on how mindful the author was to flexibility when writing the makefile. For example, if the makefile uses conventional macros (like $(CC), shown below) in invoking build tools, it can adapt easily to the Wind River Linux cross compiling build environment. all: $(OBJS) libs ../config.mk $(CC) -o menu $(OBJS) input.a draw.a $(LDFLAGS) $(LDLIBS) By contrast, if the makefile is “hard-coded” as shown below, then it will require some degree of patching in order for it to cross compile smoothly. In other words, you will have to create a patch which modifies the Makefile to change gcc to $(CC). all: $(OBJS) libs ../config.mk gcc -o menu $(OBJS) input.a draw.a $(LDFLAGS) $(LDLIBS) In this scenario, the integration effort then depends on the number and complexity of the makefiles that need to be patched. A list of common macros supported by Wind River Linux is summarized below:

Macro Native Tool Equivalent $(CC) gcc C compiler $(CXX) g++ C++ compiler $(CPP) gcc -E C preprocessor $(AS) as Assembler $(LD) ld Linker $(GDB) gdb Debugger $(AR) ar Archiver for generating static libraries $(NM) nm List symbols in object files $(OBJCOPY) objcopy Copy and translate object files $(OBJDUMP) objdump Display information from object files $(RANLIB) ranlib Index symbols in an archive $(STRIP) strip Remove symbol information from object files In summary, the common goals to keep in mind when approaching packages with static makefiles are:  Makefiles must invoke the appropriate cross-compiling tools as specified by the build environment, rather than native tools.  Software must install correctly to the install stage directory, rather than absolute paths within the host file system.  Pay attention to any other installation actions the package might perform – these must be applied to the target file system, not the host.

Wind River Education Services 55 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

24. Run the package importer tool as you did in the previous section, this time using the file /Labs/Packages/figlet-2.2.5.tar.gz for the Package Location. 25. For reference in editing the recipe, extract the source for the newly imported package.

make -C build figlet.unpack

The extracted source of the package can now be referred to at build/figlet-2.2.5- r0/figlet-2.2.5. 26. Now, open the recipe layers/local/recipes-local/figlet/figlet_2.2.5.bb in the editor of your choice. 27. As in the previous section, the first issue which needs to be addressed relates to the license file. This can be handled in exactly the same way that it was done when importing the links package; identify the file within build/figlet-2.2.5-r0/figlet-2.2.5 containing the license text, and set LIC_FILES_CHKSUM to point to this file. Populate the MD5 checksum value at this time if you wish, or defer it and let bitbake disclose the value for you when you attempt to build the package. 28. By default, the value for LICENSE is set to GPLv2 by the package import tool, but it really should be set to accurately reflect the actual package license. Referring to the license file, build/figlet-2.2.5-r0/figlet-2.2.5/LICENSE, you will see that it is definitely not a GPLv2 license. It is, in fact, a 3-clause BSD license. Populate the value for LICENSE accordingly. LICENSE = "BSD-3-Clause"

NOTE: There are numerous open source licenses in circulation. Some are easy to identify, but recognizing all of them is not always easy. To see the complete list of standard open-source licenses known to the bitbake authors, check the contents of the directory layers/oe-core/meta/files/common-licenses. This resource provides you with the names of the licenses (to fill in the field LICENSE) as well as the license text. Open-source license recognition tools like Ninka (http://ninka.turingmachine.org/) can also be helpful.

29. Because this package is not driven by autotools, leave the inherit autotools line commented out, unlike the previous example. # Enable this if the package uses automake/configure #inherit autotools 30. Lastly, you must address the do_install task. Referring to this package’s Makefile , you will see that it provides an install rule. Rather than manually copying the files out, leverage the install rule with a simple do_install task like this: do_install() { oe_runmake 'DESTDIR=${D}' install }

56 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

31. With the changes to the recipe saved, attempt to build your package. Supply missing MD5 values, if needed. 32. Ultimately you will be met with a compile problem:

…/i686-wrs-linux-gnu-ld: unrecognized option '-Wl,-O1' …/i686-wrs-linux-gnu-ld: use the --help option for usage information make: *** [figlet] Error 1

Notice two things from the output:  The linker (in this case, i686-wrs-linux-gnu-ld; ppc-wrs-linux-gnu-ld if using a powerpc target) is being invoked directly.  The options being passed in to the linker (-Wl,-O1) are compiler options, not linker options. Referring to the Makefile for figlet, found at build/figlet-2.2.5-r0/figlet- 2.2.5/Makefile, you will see that it is invoking the linker directly in two places: figlet: $(OBJS) $(LD) $(LDFLAGS) -o $@ $(OBJS)

chkfont: chkfont.o $(LD) $(LDFLAGS) -o $@ chkfont.o It is generally not recommended to invoke $(LD) directly from a Makefile, unless you have a very good reason for doing so. Rather, it is advisable to use $(CC), since it handles setting additional flags that may get missed otherwise. To handle this situation properly, you are going to need to patch the Makefile. 33. Please refer to the Patching a Package lab to see how to develop a patch which makes the necessary changes to the Makefile before proceeding. 34. With your patch in place, rebuild the package.

NOTE: To fully test all cycles of a package build, it’s a good idea to “really clean” the package from your build environment after a period of incremental development. The clean target isn’t sufficient, because it merely cleans the build directory. To ensure that the build directory and sstate cache are clean, you should use distclean or cleanssstate (the two are synonymous). That is, make -C build figlet.cleanssate.

Wind River Education Services 57 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

35. This time, your package should build cleanly. Feel free to test it by rebuilding your image and deploying it to your target. Try figlet by running the following on the target:

echo "Hello" | figlet

Patching Package Source In integrating new packages and maintaining your project, it is not uncommon to need to modify the package source to get it to build or run properly. Because the package source is always assumed to be unmodified upstream source, the only way to modify source in an automated manner between source extraction and build is to supply a patch that makes these modifications for you. Patches are useful for both:  Fixing integration issues (fixing a Makefile or some other build related issue)  Fixing run time bugs or adding features that have not yet been incorporated upstream In this section you will patch the source for the figlet package, used in the previous section. In this particular use case, you will make a small fix to the Makefile to enable it to build properly. However, the same approach applies for any changes you wish to make to the source code, no matter how big or small. 36. To modify the source to figlet, open a development shell for the package, as follows:

make -C build figlet.devshell

This will open a new terminal where the figlet source is located with any existing patches already applied. 37. To generate the patches, you will be using the quilt utility, which is used extensively throughout Wind River Linux to manage patches. The workflow for generating a patch with quilt involves:  Initializing a new patch  Telling quilt which file(s) you are going to modify  Making your changes  Telling quilt to “refresh” the patch; that is, to capture the differences into the patch you initialized in the first step Begin by initializing the new patch in the development shell:

quilt new makefile-integration.patch Patch patches/makefile-integration.patch is now on top

58 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

38. Now, inform quilt that you want to include the modifications you are about to make to the Makefile in the patch.

quilt add Makefile File Makefile added to patch patches/makefile-integration.patch

39. Open the Makefile in the editor of your choice, and make the needed changes. In this particular case, you are going to replace the two invocations of $(LD) with $(CC). So, the lines that read: figlet: $(OBJS) $(LD) $(LDFLAGS) -o $@ $(OBJS)

chkfont: chkfont.o $(LD) $(LDFLAGS) -o $@ chkfont.o should read as follows once you are done: figlet: $(OBJS) $(CC) $(LDFLAGS) -o $@ $(OBJS)

chkfont: chkfont.o $(CC) $(LDFLAGS) -o $@ chkfont.o When done, save your changes and exit the editor. 40. Now, instruct quilt to capture your changes into the patch:

quilt refresh Refreshed patch patches/makefile-integration.patch

Examine the contents of the patch, found at patches/makefile-integration.patch, to ensure that everything got captured the way you intended. 41. When done, copy the patch into your project’s local layer.

cp patches/makefile-integration.patch \ $TARGET_BASE/layers/local/recipes-local/figlet/files

42. With patch generation complete, you may now exit the development shell by executing the command exit.

Wind River Education Services 59 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

43. In the package recipe (in this case, figlet_2.2.5.bb, you will add the new patch file to the existing set of resources listed in SRC_URI, as follows: SRC_URI = "ftp://ftp.figlet.org/pub/figlet/…/figlet- 2.2.5.tar.gz \ file://makefile-integration.patch" 44. With that, your patch is complete, integrated into your package recipe, and ready to test.

Integrating Workbench Application Projects For this example, you will work with a Wind River Linux Application Project developed using Wind River Workbench. This application contains a simple, console-based implementation of the game Minesweeper. Although the project is fairly simple, the approach outlined in this section can be applied to Workbench projects of any level of complexity. A copy of the application can be found in in contained in the directory /Labs/Packages/fkmines. Although you don’t have to, you can import it into your workspace within Workbench to satisfy yourself that it’s a genuine application project that you can build within Workbench. 45. Run the package importer tool as you did in previous sections.

make import-package

60 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

46. This time, set Package Type to Workbench Application Project. 47. For the Package Location field to, specify /Labs/Packages/fkmines. You may use the Browse button, or simply type the location in manually.

NOTE: If you type the Package Location manually, you must click Update afterward.

48. Manually specify fkmines and 0.2 for Package Name and Version, respectively. Ensure Build Spec is set to native-standard-native. 49. Click IMPORT. 50. When the tools complete the import, press Close to dismiss the window.

46 47 48 59 50

Wind River Education Services 61 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

51. Notice the difference in how the package import tool added the new package to the project:  Nothing has been added to layers/local/downloads.  layers/local/recipes-local/fkmines/fkmines_0.2.bb has been added, which contains the recipe template.  layers/local/recipes-local/fkmines/files has been added, which contains a copy of the original application project. In there, you will find all the files contained in the original project (except for the Workbench-specific project management files). Open the fkmines_0.2.bb file in the editor of your choice. 52. As always, the first items that you should address relate to LICENSE and LIC_FILES_CHKSUM. Since the application is based on open source, it carries its own license, which can be found in layers/local/recipes-local/fkmines/files/fkmines- 0.2 /COPYING. LIC_FILES_CHKSUM should then be specified as such: LIC_FILES_CHKSUM = "file://fkmines-0.2/COPYING;md5=…" 53. Depending on how the application is architected, there may be some dependencies that must be declared using DEPENDS or RDEPENDS_fkmines. But for now, it’s safe to leave these as is. 54. Notice that the Workbench tool has customized the remainder of the recipe differently than before, to handle the unique requirements of Workbench application projects. 55. At this point, this is all the customizations that are necessary. Save the changes to fkmines_0.2.bb and make your first attempt to build the package.

make -C build fkmines

If you chose to leave the MD5 value for LIC_FILES_CHKSUM blank, the build will fail and prompt you to fill out the MD5 checksum before proceeding. Otherwise, the build will fail in the install file, because the import package tool does not know which binary needs to be installed. 56. Edit fkmines_0.2.bb again. Modify the do_install task to copy the mines executable as follows: do_install() { install -d ${D}${bindir} install -m 0755 ${S}/mines ${D}${bindir} }

62 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Compiled Applications Lab

57. The Package Importer tool creates a Makefile in layers/local/recipes- local/fkmines/files. The fkmines application uses ncuress library and you need to manually add this library in this Makefile as follows. [...] $(mines): $(CC) $(CFLAGS) $(CINCLUDES) -c -o fkmines-0.2/generate.o fkmines-0.2/generate.c $(CC) $(CFLAGS) $(CINCLUDES) -c -o fkmines-0.2/mines.o fkmines-0.2/mines.c $(CC) $(LFLAGS) $(LINCLUDES) -o $(mines) fkmines- 0.2/generate.o fkmines-0.2/mines.o -l ncurses \ [...] 58. If you attempted to build the application before adding the ncurses library you may need to clean up the build environment to ensure the changes to the build instructions are included.

make -C build fkmines.clean

59. Build your image and deploy it to your target to test the new program mines.

This concludes the lab. Do not proceed.

Wind River Education Services 63 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

64 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications Lab

© 2013 Wind River Systems, Inc

65 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Integrating Python Applications Lab

Objective In this lab you will learn the basics of how to integrate third-party software components written in Python into Wind River Linux platforms.

NOTE: This lab should take approximately 45 minutes.

Lab Overview Wind River Linux comes with hundreds of validated software packages that are ready to use in Wind River Linux platforms. If you need a software package that is not included, or if you must integrate an application being developed in-house, you must integrate the package into the Wind River Linux build system and cross- compile it along with the rest of your platform software. A properly integrated package makes it easy to include the package into other projects as well. This lab uses a simple Python application as a way to introduce the concepts behind integrating a Python application. The application is a phone book that is listed from a Telnet session. The application supports multiple simultaneous Telnet sessions.

Before You Begin This lab modifies the configuration of an existing platform project. Use the pre-built project provided with your lab environment. Refer to the Getting Started lab to identify where to find this project in your lab environment. The location of this project will be referenced as $TARGET_BASE throughout this lab. This lab uses a command-line environment. Take the time now to open a command-line terminal and navigate to this directory.

The Packaging Workflow This lab assumes that you are already familiar with the basic packaging workflow described in the lab Integrating Packages. You should review its content — packaging a Python application is not very different. The following describes a slightly modified workflow that includes a few Python-specific steps:  Add the file setup.py to the application. This allows the application to be managed by the Python setuptools utilities. You must ensure that setup.py works properly and that you can install your Python application on a development workstation.

66 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications Lab

The setuptools utilities are Python libraries which are not connected with your Wind River Linux installation. You can use them to manage the native packaging of Python applications. However, using setuptools facilitates the packaging of the application for your Wind River Linux platform project.  Select a name for the application. In this lab you will use the name phonebook.  Select the build layer where you will maintain the new package. In this lab you will maintain the phonebook application in the local layer.  Define the license to associate with the application. In this lab you will use the GPLv3 license.  Make the application source code and support files available to the build system. In this lab you will use a URL pointing to a tar file in the directory /Labs/Packages.  Build the directory infrastructure inside the selected layer to tell bitbake about the new package, and add all the support files.  Ensure the application recipe file tells bitbake that the application can be managed with the setuptools utilities.  Test the build and fix any problems. Repeat this workflow until your new package works as expected.

About the Tar File The tar file for the application is /Labs/Packages/phonebook-1.0.tar.gz. The following figure shows the content of the tar file. phonebook-1.0 |-- COPYING |-- phonebook |-- README |-- setup.py |-- tslib |-- __init__.py |-- db.py `-- server.py

Wind River Education Services 67 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

About Setup.py The following is the sample file setup.py provided in the tar file: from setuptools import setup

setup(name='phonebook', version='1.0', description='Python Phonebook Application', long_description=open('README').read(), author='Wind River Systems', author_email='[email protected]', url='http://education.windriver.com', classifiers=[ 'Development Status :: Production', 'Environment :: Console', 'License :: OSI Approved :: GPLv3', ], packages=['tslib'], scripts=['phonebook'], data_files = [ ('/usr/share/doc/phonebook', ['README'])] ) It is beyond the scope of this lab to go into the details of this file, but most of its content is self-explanatory. However, it is worth adding a few words about the three last parameters passed to the setup function.  packages — This parameter identifies the Python packages included in the application. A Python package is a directory populated with a special file named __init__.py and zero or more Python modules (files with the extension .py). In the application phonebook, the directory tslib is the only Python package. bitbake installs the Python packages in the standard Python library for your target platform. In this lab this library is in /usr/lib64/python2.7/site-packages.  scripts — This parameter identifies standalone executable Python files that you want to be installed as commands in the target. These scripts usually import the Python packages defined by the application. In this lab the only script is the Python program phonebook. bitbake installs the scripts in the directory /usr/bin in the target.  data_files — This parameter lists all auxiliary files bundled with the application and specifies their location in the target system. In this lab the only auxiliary file is the README file which is installed in the directory /usr/share/doc/phonebook in the target. The sample file setup.py provided in this lab is minimal but it can become as complex as needed to address the specific needs of your application. Please refer to the standard Python documentation resources for further details.

68 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications Lab

About bitbake Recipe Files A recipe file provides bitbake with the necessary details to build the package. In this lab the recipe file name is phonebook_1.0.bb.

Creating the Layer Structure 1. Execute the following command to add the directory structure to your platform project. Note that the local layer already has several other directories and files on it — do not touch them.

mkdir -p layers/local/recipes-applications/phonebook

The directory recipes-applications is the directory where you will maintain your own application packages. The subdirectory phonebook is where you will maintain the application. It hosts the bitbake recipe file and other support files that you may need in the future. 2. Create the recipe file layers/local/recipes-applications/phonebook/phonebook_1.0.bb for the package with the following content. This file is also available in the directory /Labs/Packages. SUMMARY = "Phone Book Application" DESCRIPTION = "Sample Python code for a phone book" HOMEPAGE = "http://education.windriver.com" LICENSE = "GPLv3" LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

PR = "r1"

RDEPENDS_${PN} = "python-core python-io python-misc \ python-fcntl python-sqlite3 \ python-textutils netcat" inherit setuptools

SRC_URI = "file:///Labs/Packages/phonebook-1.0.tar.gz" SRC_URI[md5sum] = "6ab56a2ec66f9839daeead13702308d5"

Understanding the Recipe File The following provides short descriptions of the variables in the recipe file that you just created:  SUMMARY, DESCRIPTION, HOMEPAGE — These variables provide information about the recipe  LICENSE and LIC_FILES_CHKSUM — These variables define the licenses to apply to the application.  PR — This variable provides the product revision number.

Wind River Education Services 69 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

 RDEPENDS_{PN} — This variable expands to RDEPENDS_phonebook. The R before DEPENDS stands for run-time. The expanded expression tells bitbake about the run-time dependencies associated with the phonebook application. In this case, the run-time dependencies are a few Python modules and netcat. bitbake will ensure that the Python modules and the command netcat are installed in the root file system so that the application phonebook can run on the target. Note that the Python interpreter built for a platform project with a glibc-small root file system is functional but basic. By contrast the Python interpreter built for a platform project with a glibc-std root file system includes all modules in the Python standard library. In the latter case the run-time dependencies line in your recipe would look like the following: RDEPENDS_{PN} = "python netcat"  inherit setuptools — This instruction tells bitbake to use the Python setuptools libraries to determine how the phonebook application is organized and how to install it on the target root file system.  SRC_URI — This variable lists the source files that make up the package.  SRC_URI[md5sum] — This variable provides the checksum value of the source file.

Building the Phonebook Package 3. Execute the following command to add the package phonebook to the list of packages to build in your platform project.

make -C build phonebook.addpkg

4. Execute the following command to build the package. Note that other packages needed to run the application are built automatically. In particular, you may see that bitbake builds the Python interpreter. This may take some time.

make -C build phonebook

5. Execute the following command to build the project.

make

After the platform project builds, the directory export/dist contains a copy of the target root file system.

70 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications Lab

6. Execute the following command to verify that the Python script phonebook is part of the new target image.

ls -l export/dist/usr/bin/phonebook -rwxr-xr-x 1 wruser wruser 3051 Aug 2 14:40 ...

7. Execute the following command to verify that the phonebook libraries are part of the new target image.

ls export/dist/usr/lib64/python2.7/site-packages/tslib db.py __init__.py server.py

Running the Phonebook Application 8. Before you run the application you should understand how it works. Execute the following command to display the content of the file, then read and understand its content.

less build/phonebook-1.0-r1/phonebook-1.0/README

In summary, the file says that you must run two programs: the phonebook server (which provides the phonebook entries) and a client program to query the server. 9. Try your application. Start the target, as outlined in the Getting Started lab. 10. Execute the following command to start the phonebook server.

phonebook& Listening on ('127.0.0.1', 41215)

The character & sends the server to execute in the background. Wait until the server tells you the IP address and port number on which it is listening (in this case, the IP address 127.0.0.1 and port 41215).

Wind River Education Services 71 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

11. Execute the following command to start the netcat client. Remember that the bitbake recipe includes the netcat package as a run-time dependency for the application.

nc 127.0.0.1 41215 Connection accepted ======Select an option: 1- List the phonebook table 2- List the phonebook table sorted by name 3- Disconnect

option:

12. Explore options 1 and 2. 13. Select option 3 to exit the client. 14. Execute the following command to bring the server to the foreground.

fg %1 phonebook

15. Press CTRL+C to exit the server.

This concludes the lab. Do not proceed.

72 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Reconfiguring Projects Lab

© 2013 Wind River Systems, Inc

73 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Reconfiguring Projects Lab

Objective In this lab you will learn how to adjust the layer and template configuration of an existing Wind River Linux project. This will also give you a deeper understanding of how layers and templates work together and influence the end result of your project.

NOTE: This lab should take approximately 45 minutes.

Lab Overview Including layers and templates when you configure new projects is trivial; it is as easy as specifying a few additional command-line options to configure. In the course of maintaining Wind River Linux platform projects, however, it may become necessary from time to time to modify the layer and/or template configuration of a project. This lab will walk you through some common use cases that involve altering the layer and/or template configuration of an existing project.

Before You Begin This lab modifies the configuration of an existing platform project. Use the pre-built project provided with your lab environment. Refer to the Getting Started lab to identify where to find this project in your lab environment. The location of this project will be referenced as $TARGET_BASE throughout this lab. This lab uses a command-line environment. Take the time now to open a command-line terminal and navigate to this directory.

Adding a Layer to a Project using the Utility configure As you have seen in the Building and Customizing a Wind River Linux Platform lab, the configure utility (included with Wind River Linux) is used in the initial setup of a platform project. However, configure can also play an important part in adjusting the configuration of an existing platform project. In this section, you will add a new layer to your existing project using the configure utility provided with Wind River Linux. This is the most universal approach to modifying your layer configuration, since it works for all types of layers that you might encounter; namely:  pure Yocto layers (that is, layers that do not use constructs unique to Wind River Linux)  layers designed for Wind River Linux, which take advantage of constructs unique the product (for example, templates)

74 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Reconfiguring Projects Lab

The layer used in this exercise can be found at /Labs/LayersAndTemplates/games. This layer provides a package called vitetris, which implements an open-source clone of the popular game, Tetris.

NOTE: In this context, the term package refers to source code which implements a particular piece of software, paired with a recipe that provides bitbake with instructions on how to build the software.

Prior to starting this exercise, feel free to familiarize yourself with the structure and content of this layer, since it provides a simple example of how to include third-party sources into your projects. 1. Before you change anything, take note of your existing layer configuration by examining the file bitbake_build/conf/bblayers.conf.

cat bitbake_build/conf/bblayers.conf LCONF_VERSION = "5"

BBPATH = "${TOPDIR}" BBFILES ?= "" WRL_TOP_BUILD_DIR ?= "${TOPDIR}/.." # resolve WRL_TOP_BUILD_DIR immediately with a canonical path # to satisfy the bitbake logger WRL_TOP_BUILD_DIR := "${@os.path.realpath(d.getVar('WRL_TOP_BUILD_DIR', True))}"

BBLAYERS = " \ ${WRL_TOP_BUILD_DIR}/layers/wrlinux \ ${WRL_TOP_BUILD_DIR}/layers/wrlcompat \ ${WRL_TOP_BUILD_DIR}/layers/wr-toolchain \ ${WRL_TOP_BUILD_DIR}/layers/oe-core/meta \ ${WRL_TOP_BUILD_DIR}/oe-core-dl \ ${WRL_TOP_BUILD_DIR}/layers/wr-kernel \ ${WRL_TOP_BUILD_DIR}/layers/wr-bsps/$BSP \ ${WRL_TOP_BUILD_DIR}/layers/wr-base \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-profile \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-debug \ ${WRL_TOP_BUILD_DIR}/layers/local \ "

Wind River Education Services 75 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Notice that all of the layers are contained within the project directory tree. This is because:  all of these layers are part of the Wind River Linux product  all layers distributed with Wind River Linux are packaged in their own git repository. When Wind River Linux configures your build environment, it checks out a local copy of any of the layers it needs.

NOTE: Your BSP layer may differ from the one shown above, as this layer name is determined by the board that was selected with the --enable-board option when the project was initially configured.

2. Identify the options which were used to configure the project, as you will need to specify these again when re-running configure. These are recorded in the config.log file. The output shown below represents what you might see in a typical project:

cat config.log # Generated by wrlinux configure at Sun Jan 6 11:36:16 EST 2013 $WIND_BASE/wrlinux/configure --enable-board=$BSP \ --enable-kernel=standard \ --enable-rootfs=glibc_small \ --with-template=feature/debug

3. Copy and paste the entire configure command from the previous step (do not copy and paste the command below!), and then add the options --enable-reconfig and --with-layer=/Labs/LayersAndTemplates/games:

$WIND_BASE/wrlinux/configure … \ --enable-rootfs=glibc_small \ --with-template=feature/debug \ --enable-reconfig \ --with-layer=/Labs/LayersAndTemplates/games

By default, configure will abort if it detects that it is being run in a directory that already appears to contain a configured project. The --enable-reconfig option defeats this behavior and allows configure to be re-run. It is important that you do not modify any of the other options to avoid unintended side-effects. They should be preserved exactly from the previous step.

76 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Reconfiguring Projects Lab

4. Once the command from the previous step completes, execute the following command to examine the contents of bblayers.conf again.

cat bitbake_build/conf/bblayers.conf LCONF_VERSION = "5"

BBPATH = "${TOPDIR}" BBFILES ?= "" WRL_TOP_BUILD_DIR ?= "${TOPDIR}/.." # resolve WRL_TOP_BUILD_DIR immediately with a canonical path # to satisfy the bitbake logger WRL_TOP_BUILD_DIR := "${@os.path.realpath(d.getVar('WRL_TOP_BUILD_DIR', True))}"

BBLAYERS = " \ ${WRL_TOP_BUILD_DIR}/layers/wrlinux \ ${WRL_TOP_BUILD_DIR}/layers/wrlcompat \ ${WRL_TOP_BUILD_DIR}/layers/wr-toolchain \ ${WRL_TOP_BUILD_DIR}/layers/oe-core/meta \ ${WRL_TOP_BUILD_DIR}/oe-core-dl \ ${WRL_TOP_BUILD_DIR}/layers/wr-kernel \ ${WRL_TOP_BUILD_DIR}/layers/wr-bsps/$BSP \ ${WRL_TOP_BUILD_DIR}/layers/wr-base \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-profile \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-debug \ /Labs/LayersAndTemplates/games \ ${WRL_TOP_BUILD_DIR}/layers/local \ "

From this output, it is clear that your new layer has made it into the build. Also, notice that the absolute location of the layer is retained, since this layer is not packaged as a git repository that requires checking out into a local working copy. At this point, there has been zero net effect of having included this layer. Like many layers, the games layer merely makes content available; in this case, the content is a package called vitetris. In the remainder of this section, you will leverage the content this layer provides.

Wind River Education Services 77 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5. Execute the following command to add the vitetris package provided by the games layer to your image.

make -C build vitetris.addpkg make: Entering directory `/home/wruser/myplatform/build' ==Checking extra-addpkg.conf== ==Checking for valid package for vitetris== Setting up host-cross and links Setting up packages link Creating export directory Creating project properties … === ADDED vitetris to extra-addpkg.conf === NOTE: It is possible to generate a non-buildable configuration With the addpkg rule, in which case you can use the rmpkg rule to remove what you added and try a different configuration. make: Leaving directory `/home/wruser/myplatform/build'

The fact that this step succeeds is evidence that your layer addition is working. You would not have been able to execute this command successfully in the absence of the games layer; the build system would have issued an error indicating that the specified target is unbuildable. 6. With the addition of the vitetris package from the new layer, execute the following command to build your image.

make

78 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Reconfiguring Projects Lab

7. Once the build completes, perform a quick sanity check by verifying that the tetris executable can be found within the target file system.

ls -l export/dist/usr/bin/tetris -rwxr-xr-x. 1 wruser wruser … export/dist/usr/bin/tetris

NOTE: Although the package is referred to as vitetris, the binary executable it generates is called tetris.

A more comprehensive sanity test involves using the file utility to verify that tetris has been cross compiled properly:

file export/dist/usr/bin/tetris

The file utility will parse the binary file and display important attributes such as the format, endianness, and instruction set architecture. This will provide an immediate indicator of whether or not cross compilation was performed properly. 8. Feel free to take the time to deploy your new image to the target to test tetris. Please refer to the Building and Customizing a Wind River Linux Platform lab for more details on image deployment, if needed. 9. Once you have satisfied yourself that the tetris application is functioning as expected, close down the target and remove the package from your image, in preparation for the next exercise.

make -C build vitetris.rmpkg make: Entering directory `/home/wruser/myplatform/build' ==Checking extra-addpkg.conf== === REMOVED vitetris from extra-addpkg.conf === make: Leaving directory `/home/wruser/myplatform/build'

Adding a Template to a Project In this section, you will add a new template to your existing project. The template used comes from the layer which you added in the previous section, and is called tetris_on_start. This template automatically includes the vitetris package, and configures it to run on the console at boot time instead of the standard login program. This is a useful template if you want to build a device dedicated to running tetris.

Wind River Education Services 79 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

10. As you did in the previous section, you must re-run configure with an additional option to include the new template. Once again, use the contents of config.log to ensure that all of the options are consistent with their existing settings. Now add an additional option, --with-template=feature/tetris_on_start.

NOTE: If config.log already contains a --with-template argument, then you should append to that one, separating templates with a comma as shown below.

$WIND_BASE/wrlinux/configure … \ --enable-rootfs=glibc_small \ --with-template=feature/debug,feature/tetris_on_start \ --enable-reconfig \ --with-layer==/Labs/LayersAndTemplates/games

11. Execute the following command to rebuild your image.

make

12. Once the build completes, quickly check once again to see that the tetris binary can be found in export/dist/usr/bin directory. Also examine the contents of export/dist/etc/inittab. In particular, focus on the line beginning with S:2345:respawn. The original version of this file instructs init to run mingetty, which monitors idle terminals and manages logins. The new version instead runs tetris. With this configuration, you will not be able to log in to your device, but you will be able to play tetris as much as you want.

cat export/dist/etc/inittab # /etc/inittab: init(8) configuration. # $Id: inittab,v 1.91 2002/01/25 13:35:21 miquels Exp $

# The default runlevel. id:3:initdefault: … # Run gettys in standard runlevels S:2345:respawn:/usr/bin/tetris # /sbin/mingetty invocations for the runlevels. # …

13. Feel free to take the time to deploy your new image to the target.

80 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Reconfiguring Projects Lab

14. Take some time to consider what has happened in this section. Recall that in the previous section (adding the layer) you needed to explicitly include the vitetris package into your image, whereas in this case it was included automatically when you included the feature/tetris_on_start template. To understand the mechanism of how this happens, consult the main configuration file for the template, which is found at templates/feature/tetris_on_start/template.conf within the games layer. IMAGE_INSTALL_append += "vitetris" WRL_FS_FINAL_PATH += "${LAYERPATH_games}/templates/feature/tetris_on_start" This code enables the template to perform two important functions:  add the vitetris package to the image by manipulating the build system variable IMAGE_INSTALL_append  append the template directory to the WRL_FS_FINAL_PATH build system variable; the build system scans all the directories listed in this variable, looking for fs_final.sh scripts. An fs_final.sh (also found in this directory) is used to modify /etc/inittab as mentioned above. The key concept to realize with regard to templates is that everything they can do can be done at the layer level, or even manually. However, templates provide a few important benefits, which by now are hopefully clearer:  Templates provide a convenient way to automate a set of tasks (in this example, the template adds an application package to the image, and triggers the application on startup).  Templates provide a way to group such tasks by the feature to which they are related.  Templates provide a finer level of granularity for controlling features. A layer provides a useful construct for grouping related content (including templates). But templates provide the ability to enable or disable related features independently.

Removing Templates or Layers In this section, you will remove the template and layer which you previously added to your project. 15. As you did in previous sections, consult the config.log file to obtain the complete command capturing the current configuration, this time removing the --with-layer and --with-template options which you previously added.

NOTE: If the file config.log already contains more than one parameters in --with- template argument, delete just feature/tetris_on_start.

16. Rebuild your image using the command make.

Wind River Education Services 81 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

17. Deploy your new image to the target. You will find that tetris no longer starts on boot. In fact, you will find that tetris is no longer installed in the image at all. This change demonstrates that the tetris_on_start template has been disabled. 18. Back in your development shell on the host, attempt to manually add the vitetris package back in to your image, as you did in the first section:

make -C build vitetris.addpkg make: Entering directory `/home/wruser/myplatform/build' ==Checking extra-addpkg.conf== ==Checking for valid package for vitetris== Setting up host-cross and links Setting up packages link Creating export directory Creating project properties … NOTE: Resolving any missing task queue dependencies ERROR: Nothing RPROVIDES 'vitetris' (but /home/wruser/myplatform/layers/… NOTE: Runtime target 'vitetris' is unbuildable, removing... Missing or unbuildable dependency chain was: ['vitetris'] NOTE: Preparing runqueue ERROR: All buildable tasks have been run but the build is incomplete (--continue mode). Errors for the tasks that failed will have been printed above. ERROR: Command execution failed: Exited with 1

Summary: There were 3 ERROR messages shown, returning a non-zero exit code. ERROR: vitetris is not a valid package make: *** [vitetris.addpkg] Error 1 make: Leaving directory `/home/wruser/myplatform/build'

The operation now fails because the build system cannot find a package called vitetris. This tells us that the games layer also is now gone. You can further verify this by examining your bblayers.conf file.

Manipulating Layer Configuration via bblayers.conf Up until now, you have used the configure utility provided with Wind River Linux to manipulate your project layer configuration. You have also seen how the file bitbake_build/conf/bblayers.conf reflects the list and location of the layers feeding into your project. You can also manipulate your layer configuration in a more direct manner by manually editing bblayers.conf. In this section, you will see how.

NOTE: This approach is not well suited for layers which take advantage of features unique to Wind River Linux.

82 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Reconfiguring Projects Lab

19. Open bitbake_build/conf/bblayers.conf in a text editor of your choice. Add the entry /Labs/LayersAndTemplates/games to the definition of BBLAYERS. When done, your bblayers.conf should resemble the following: LCONF_VERSION = "5"

BBPATH = "${TOPDIR}" BBFILES ?= "" WRL_TOP_BUILD_DIR ?= "${TOPDIR}/.." # resolve WRL_TOP_BUILD_DIR immediately with a canonical path # to satisfy the bitbake logger WRL_TOP_BUILD_DIR := "${@os.path.realpath(d.getVar('WRL_TOP_BUILD_DIR', True))}"

BBLAYERS = " \ ${WRL_TOP_BUILD_DIR}/layers/wrlinux \ ${WRL_TOP_BUILD_DIR}/layers/wrlcompat \ ${WRL_TOP_BUILD_DIR}/layers/wr-toolchain \ ${WRL_TOP_BUILD_DIR}/layers/oe-core/meta \ ${WRL_TOP_BUILD_DIR}/layers/oe-core-dl \ ${WRL_TOP_BUILD_DIR}/layers/wr-kernel \ ${WRL_TOP_BUILD_DIR}/layers/wr-bsps/$BSP \ ${WRL_TOP_BUILD_DIR}/layers/wr-base \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-profile \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-debug \ ${WRL_TOP_BUILD_DIR}/layers/local \ /Labs/LayersAndTemplates/games \ "

NOTE: Your BSP layer may differ from the one shown above, as this layer name is determined by the board that was selected with the option --enable-board when the project was initially configured.

20. With your changes to bblayers.conf saved, execute the following command to add the vitetris package back in to your image.

make -C build vitetris.addpkg

Because the layer containing this package is now included in your project (by virtue of the edit made to bblayers.conf), this operation will succeed. 21. Verify that you can build and deploy your image with the tetris binary included. 22. Now attempt to enable the feature/tetris_on_start template using the technique discussed earlier; use the command found in config.log and append to that the option --with-template=feature/tetris_on_start. This time, you will be met with failure. Since templates are a feature unique to Wind River Linux, it is the responsibility of the configure utility to collect a list of

Wind River Education Services 83 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

available templates in all known layers. Because you bypassed configure in adding in the games layer, it is unable to locate the requested template. The success and failure experienced in this section thus highlights when the direct approach to modifying your layer configuration works, and when it does not.

This concludes the lab. Do not proceed.

84 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

© 2013 Wind River Systems, Inc

85 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Creating Layers Lab

Objective In this lab you will learn how to capture common project settings into a custom bitbake layer which can be reused in multiple projects.

NOTE: This lab should take approximately 60 minutes.

Lab Overview The content that makes up your Wind River Linux platform project is delivered through a collection of layers. Most of the layers included in standard projects are provided by the Wind River Linux product and common to every project. Every project also comes equipped with a built-in local layer, which can be used to develop custom content unique to your project. Platforms can be further enhanced by including additional layers. Throughout this training, you have customized your platform project in a number of different ways. In most cases, these changes have been recorded in the local layer, where these customizations can survive for the life of your project, but are only available to that particular project. Customizations can be shared with other platform projects by placing them into an external custom layer. This lab will walk you through the creation of a new layer, as well as populating it with some common customizations.

Creating the Layer Directory Structure A layer is nothing more than a directory structure populated with a collection of configuration files and other resources needed to build software. Creating a new layer is simply a matter of creating directories and files in the places the build system expects to find them. In this section, you will create the skeleton of a new layer, which will be populated with content in subsequent sections. Note that some layers contain additional elements beyond those which are discussed in this lab; these exercises only touch on the elements commonly used in custom application layers.

86 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

1. Create the top level directory for your layer.

mkdir /home/wruser/MyLayer

NOTE:  Layers can reside anywhere in your file system.  The top-level directory name (in this case, MyLayer) should match the layer name.  Layer names can be anything you like. In the Yocto Project community, it is a common practice to use the prefix meta-.

2. Execute the following command to navigate to the layer.

cd /home/wruser/MyLayer

3. Execute the following command to create the directory conf, which will contain the layer.conf file. Other configuration files can also be maintained here, as well.

mkdir conf

4. Execute the following command to create the directory downloads. If your layer provides packages, then local copies of the archives associated with the packages (if any) will be maintained here.

mkdir downloads

5. Execute the following command to create the directory recipes-custom, which will contain the following:  Recipes: provide configuration information, commonly used to provide instructions for building a particular package.  Append files: provide the ability to extend existing recipes. This capability enables your layer to add to, or modify aspects of, an existing recipe, without having to copy and modify the original recipe. Note that the naming of this directory is somewhat arbitrary; the only requirement is that the name begins with the prefix recipes-. It’s fairly common for layers to have multiple recipe directories to main logical groupings of content.

mkdir recipes-custom

Wind River Education Services 87 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

6. Lastly, execute the following command to create a templates/feature directory structure. The feature directory will contain Wind River Linux templates provided by your layer, if any.

mkdir -p templates/feature

7. Now create the layers.conf file in the conf directory. This file is a requirement for all layers; without it the bitbake system will not recognize your layer. Most layer.conf files contain many common elements. As such, when creating a new layer, it is common practice to copy an existing layer.conf file, making minor customizations needed to match the layer name. This file can be modified thereafter, as needed. For this step, copy the layer.conf from the local layer of an existing project; this can be the standard project included with the lab environment (refer to the Getting Started lab to identify where this project is located), or it can be one of the projects you’ve created in a previous lab.

cp $HOME/myplatform/layers/local/conf/layer.conf conf

8. Replace any instances of the string local within your new layer.conf with the name of your layer, MyLayer.

88 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

9. Take a moment to acquaint yourself with the contents of your layer.conf file, which should now resemble the following: # We have a conf and classes directory, add to BBPATH BBPATH := "${LAYERDIR}:${BBPATH}"

# We have a packages directory, add to BBFILES BBFILES := "${BBFILES} ${LAYERDIR}/recipes-*/*/*.bb \ ${LAYERDIR}/recipes-*/*/*.bbappend"

BBFILE_COLLECTIONS += "MyLayer" BBFILE_PATTERN_MyLayer := "^${LAYERDIR}/" BBFILE_PRIORITY_MyLayer = "10"

# Add scripts to PATH PATH := "${PATH}:${LAYERDIR}/scripts"

# Add a directory to allow local changelist.xml changes WRL_CHANGELIST_PATH += "${LAYERDIR}/conf/image_final"

# Add a directory to allow local fs_final*.sh script changes WRL_FS_FINAL_PATH += "${LAYERDIR}/conf/image_final"

# We have a pre-populated downloads directory, add to PREMIRR… PREMIRRORS_append := "\ git://.*/.* file://${LAYERDIR}/downloads/ \n \ git://.*/.* git://${LAYERDIR}/git/BASENAME;protocol=file… svn://.*/.* file://${LAYERDIR}/downloads/ \n \ ftp://.*/.* file://${LAYERDIR}/downloads/ \n \ http://.*/.* file://${LAYERDIR}/downloads/ \n \ https://.*/.* file://${LAYERDIR}/downloads/ \n" The elements of this file are interpreted as follows:  The BBPATH variable is used by bitbake to maintain a list of directories to search for crucial information (like layer.conf files). Layers augment this variable in the manner shown to make themselves known to bitbake.  The BBFILES variable is used by bitbake to maintain a list of recipes (*.bb) and append files (*.bbappend). Layers manipulate this variable as shown to publish any recipes or append files they provide. From studying this expression, you will see that this is where the requirement for the recipes- prefix, mentioned previously, comes from. Although you are free to modify this expression, you shouldn’t, because this naming scheme is a standard Yocto Project convention.  BBFILE_COLLECTIONS maintains a list of layers. Therefore, this is where you declare the name for your layer.  BBFILE_PATTERN_MyLayer is a layer-specific variable specifying a regular expression which bitbake can use to identify files (in BBFILES) belonging to your layer. In this instance, the standard expression provided matches any file beginning with the layer directory, ${LAYERDIR}.

Wind River Education Services 89 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

 BBFILE_PRIORITY_MyLayer is another layer-specific variable specifying a priority which bitbake assigns to your layer. Bitbake uses layer priorities to determine the order in which to find recipes and other resources provided by your layer. Priorities are used to resolve ambiguities when multiple layers contain overlapping resources.  The augmentation of PATH is optional, and meaningful only if your layer has a scripts directory containing utilities to be run on the host.  WRL_CHANGELIST_PATH and WRL_FS_FINAL_PATH enable fs_final.sh and changelist.xml file system finalizers to be offered by your layer. This functionality is provided by the Wind River Linux image classes, which are enabled by default when using the Wind River Linux configure script to set up your build environment.  PREMIRRORS maintains a list of directories containing source archives, which bitbake can use in lieu of downloading over the network. Layers augment this variable in the manner shown to enable such archives to be found in the downloads directory, in a variety of formats.

NOTE: Although providing a README file in your layer’s top-level directory is not a technical necessity, Yocto Project compliance requires the presence of such a file to document your layer’s purpose and usage instructions. For examples, refer to any of the standard product layers which can be found in any configured build environment; for example, /home/wruser/myplatform/layers/wr-base/README.

Your layer, although devoid of any actual content, is now technically complete, and is ready to be included into projects. In the exercises that follow, you will populate your layer with content related to some of the common layer use cases.

Using Your Layer In this section, you will add the layer you created in the previous section to a new platform project. Throughout the rest of the lab, you can use this project to incrementally verify that your layer settings are taking effect. Take the time to open a new terminal window so that you can maintain the shell from the previous section in your layer directory, and one in your new build environment. 10. In the new shell, create a directory for your new project and switch into this directory.

mkdir /home/wruser/layer_test_prj cd /home/wruser/layer_test_prj

90 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

11. Configure a new build environment. The settings for --enable-board, --enable- kernel, and --enable-rootfs should match the target included in your lab environment to improve build times; you can use the $BSP, $KERNEL, and $ROOTFS variables to specify these. In addition to these three arguments, you should include:  --with-layer=/home/wruser/MyLayer to include your custom layer  --with-sstate-dir=/Labs/sstate to speed up the build

$WIND_BASE/wrlinux/configure --enable-board=$BSP \ --enable-kernel=$KERNEL \ --enable-rootfs=glibc_small \ --with-layer=/home/wruser/MyLayer \ --with-sstate-dir=/Labs/sstate

12. Examine the contents of bitbake_build/conf/bblayers.conf and notice that a reference to your layer is contained within. Since your layer is essentially empty at this point, it will not exert any real influence over the build environment yet. In the sections that follow, you will build up your layer and observe the impact it has on projects that include it.

NOTE: This section illustrates how to add your layer to a new platform project. You can also add layers to existing projects. This is covered in the Reconfiguring Projects lab.

Adding Packages You will undoubtedly need to add packages or applications to your projects at one point or another. In the Integrating Packages lab, you learned how to integrate upstream and in-house applications into your build environment, using the project’s local layer. In this section, you will embed a package which is known to build properly into your new custom layer. The package you will add to your layer is called figlet. It contains the following parts, which you will find common to most packages. These can all be found in the /Labs/LayersAndTemplates directory.  An archive, figlet-2.2.5.tar.gz, containing the upstream source for this package. Upstream packages are commonly delivered in the form of an archive. Package source can also be delivered as a source tree, or via an SCM like git or subversion.  A recipe, figlet_2.2.5.bb, which provides the bitbake instructions for building the package. A recipe is always required in order to build a package.  A patch, makefile-integration.patch, which must be applied to the upstream source prior to building, in order for the package to build properly. Patches aren’t

Wind River Education Services 91 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

always required; some upstream source is able to build cleanly without the need for patching. In this particular case, however, a patch is required. For this package to be represented properly, all components must be included in the proper locations within your layer.

NOTE: Be sure to perform all steps in your layer directory, unless otherwise noted.

13. Because the source is delivered as an archive, the archive must be copied into your layer’s downloads directory.

cp /Labs/LayersAndTemplates/figlet-2.2.5.tar.gz downloads

14. Next, create a package-specific directory within your layer’s recipes-custom directory. Here, you will place the package recipe. Other components needed to build figlet will be rooted here, as well.

mkdir recipes-custom/figlet

NOTE: There is no technical requirement to name this directory after your package. In fact, you could have a single directory containing all of the configuration information for all of the packages provided by your layer. From a manageability standpoint, however, it makes good sense keep your recipes organized in directories named after their associated packages.

15. Execute the following command to copy the recipe into this newly created directory.

cp /Labs/LayersAndTemplates/figlet_2.2.5.bb recipes-custom/figlet

16. Execute the following command to create the subdirectory files which will be used to additional resources needed to build the package, such as:  Patches to be applied to the source prior to building, if required  Package source tree, if no archive is provided

mkdir recipes-custom/figlet/files

NOTE: The name files is a requirement in this case. Bitbake will search this subdirectory for patches and other resources related to the package.

92 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

17. Execute the following command to copy the needed patch file into the files subdirectory.

cp /Labs/LayersAndTemplates/makefile-integration.patch \ recipes-custom/figlet/files

18. Now your layer contains sufficient information to build and include figlet into your image. Verify that figlet is buildable within the project you created in the previous section. Switch to your project shell, and issue the following:

make -C build figlet

This will build the figlet package. Assuming this succeeds, this is sufficient to prove that the figlet package has been properly integrated into your layer. 19. Now, wire your layer to automatically include the figlet package into the image. Back in your layer shell, add the following line to the file conf/layer.conf: IMAGE_INSTALL_append += "figlet" 20. In your project shell, execute the following command to build the image.

make

21. When the build completes, you the figlet application is built into your target file system. Execute the following command to verify that the target file system includes the figlet binary.

find export/dist –name figlet

Modifying File System Content As you saw in the Building and Customizing a Wind River Linux Platform lab, there are a couple of mechanisms provided by Wind River Linux which allow direct manipulation of the target file system content: changelist.xml, and fs_final.sh. In this section, you will integrate both into your custom layer. This will give you some insight into the naming requirements for these files, as well as how to deal with multiple changelist.xml files. Perform this section in your layer directory.

Wind River Education Services 93 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

22. Execute the following command to create a new subdirectory called image_final within your layer’s conf directory. This is the standard place searched in layers for changelist.xml and fs_final.sh files.

mkdir conf/image_final

23. The directory /Labs/LayersAndTemplates contains two scripts (motd.sh and fifo.sh). Both scripts are designed to be run as fs_final scripts at file system finalization time. Execute the following command to copy these files into the image_final subdirectory, observing the following naming requirements:  Files must begin with the prefix fs_final.  Files must end with the suffix .sh. This naming scheme is required in order for the system to find your scripts.

cp /Labs/LayersAndTemplates/motd.sh conf/image_final/fs_final_motd.sh cp /Labs/LayersAndTemplates/fifo.sh conf/image_final/fs_final_fifo.sh

24. Test the new additions to your layer by switching to your project shell and building the project image which you are using to test your layer.

make

25. Execute the following command to verify that the /etc/motd in the target file system contains the modified text.

cat export/dist/etc/motd Welcome to your Wind River Linux 5 image

26. Also verify that a FIFO node called mypipe exists in the root directory (export/dist), with mode 0777. To verify this effectively, you will need to enter the fake root environment, as outlined in the Building and Customizing a Wind River Linux Platform lab. The procedure is quickly recapped below:

scripts/fakestart.sh ls –l export/dist/mypipe

When done, leave the fake root environment using the exit command.

94 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

27. Switch back to your layer shell and turn your attention to the changelist.xml files. In /Labs/LayersAndTemplates, you will find two files, changelist_login_msg.xml and changelist_readme.xml. Because there can be only one changelist.xml file in a layer, you must learn how to merge these files, should you ever need to. Begin by copying the first file into the conf/image_final directory.

cp /Labs/LayersAndTemplates/changelist_login_msg.xml \ conf/image_final/changelist.xml

28. Now, take a look at the second file, changelist_readme.xml. To merge this file, you will need to copy only the cl directive from this file into the main changelist.xml. When done, conf/image_final/changelist.xml should resemble the following.

NOTE: The command in a changelist.xml file should not be split across lines. It is only done in this document to fit the page.

29. Save the file and test the new additions to your layer by rebuilding the project image which you are using to test your layer. Verify that the files /root/README.txt and /root/.profile exist in the target file system.

Wind River Education Services 95 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Kernel Configuration and Patching The Configuring and Patching the Kernel lab walked you through the integration of kernel patches and configuration fragments into your build environment’s local layer. In this section, you will learn how to replicate these features in your new custom layer. The following components are required to patch and/or configure the kernel:  a feature description (.scc) file which pulls in configuration fragments and/or patches  if you are configuring the kernel, a configuration fragment which specifies kernel configurations settings  if you are patching the kernel, a patch or set of patches Perform this section in your layer directory. 30. Kernel-related configuration requires a bit of additional directory infrastructure in your layer, just like packages do. Create a kernel-specific directory within your layer, which will house the append file you’re going to create, as well as all the kernel- related configuration you want to include.

mkdir -p recipes-kernel/linux/linux-windriver-3.4

The components of this new path represent the following:  the new directory recipes-kernel, parallel to the recipes-custom used in the previous section. It’s not required to keep kernel-related configuration separated like this. In truth, you could put your kernel configuration into recipes-custom if you really wanted to. But because the kernel is so special, it is common practice to stash kernel-related configuration into a separate subdirectory called recipes- kernel.  the directory linux, which provides a container for the append file you’re going to create. As with packages, the name of this directory component is not significant as far as the build system is concerned. But from a manageability standpoint, linux is the name commonly used for kernel configuration.  the directory linux-windriver-3.4, which will contain the kernel-related material you want to include in your layer. The name of this component must be matched to the append file you’re going to create which, in turn, is matched with the recipe being used for the target kernel. 31. Now execute the following command to copy the kernel material into the linux- windriver-3.4 directory: a patch which implements a large startup banner, as well as a configuration fragment which sets a default message for the banner.

96 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Creating Layers Lab

cp /Labs/LayersAndTemplates/0001-Implemented-big-boot- banner.patch \ /Labs/LayersAndTemplates/banner.cfg \ recipes-kernel/linux/linux-windriver-3.4

32. In that same directory, create a feature description file, banner.scc, which pulls in the configuration fragment and patch. kconf non-hardware banner.cfg patch 0001-Implemented-big-boot-banner.patch 33. Finally, in the directory linux, create the append file. This file will extend the kernel recipe, adding a reference to the feature description created in the previous step. This is a name-sensitive component, and must be named linux-windriver_3.4.bbappend. Notice the following:  the naming for recipes (and append files) separates the name and version with an underscore ( _ ) character rather than a hyphen ( - )  linux-windriver is the formal package name for the Wind River Linux kernel  the version, 3.4, must match the version of the kernel being used in your product  the file must have a .bbappend suffix. If you instead use a suffix of .bb, then the contents of your file will clobber the original kernel recipe! The contents of this file should resemble the following: EXTRA_KERNEL_SRC_URI += "file://banner.scc" FILESEXTRAPATHS_append := "${THISDIR}/${PN}-${PV}:" This performs the following:  adds banner.scc to the list of components which the kernel build system will look for (as maintained by the build variable EXTRA_KERNEL_SRC_URI)  extends the search path of the kernel build system by adding to the FILESEXTRAPATHS variable. ${THISDIR} expands to the directory containing the append file, while ${PN} and ${PV} expand to the package name and version, respectively (thus evaluating to linux-windriver-3.4).

Wind River Education Services 97 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

34. Now, test the new additions to your layer by invoking the kernel configure target in your project shell.

make –C build linux-windriver.configure

Examine the kernel configuration file, found at build/linux-windriver-3.4-r0/linux- $BSP-$KERNEL-build/.config (the exact path will depend on the board and kernel selection). Within, you should find the two settings from banner.cfg. These configuration settings are not part of the standard kernel settings and will only appear if your configuration fragment was applied successfully. CONFIG_BANNER=y CONFIG_BANNER_TEXT="Wind River Linux" Also verify that the patch applied by checking for the presence of a file called banner.c in the build/linux-windriver-3.4-r0/linux/init directory. This file is not part of the standard kernel source; rather it is provided by the patch you added earlier in this section. To fully test the feature, you should:  Rebuild the kernel  Rebuild your image  Deploy the image to the target  Boot the target Do this if time permits; rebuilding the kernel can take some time.

This concludes the lab. Do not proceed.

98 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

© Copyright 2014, Wind River Systems, Inc.

99 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Getting Started with IDP

Objective

In this lab you will set up the host-target development environment used in the course. You will configure, build and run an IDP platform project.

NOTE: This lab should take approximately 30 minutes.

Overview

You will set up the host development, define environment variables, then configure and build a basic IDP platform project. You will use a USB flash drive to transfer the run- time IDP binaries to the target, then boot the target from the USB flash drive and run IDP. In addition, you will set up a serial connection between the target and the host, update the target BIOS, prepare the USB flash drive to transfer the binaries and program IDP binaries from the USB flash drive into the target micro SD card. If you are not using the hardware target you will learn how to set up the QEMU-KVM simulated target environment and run the IDP platform project.

Topics Covered

Selecting a Supported Target...... Starting a Terminal Window...... Configuring and Building an IDP Platform Project...... Preparing a Bootable USB Flash Drive...... Transferring IDP System Files to the USB Flash Drive (VFAT+ext3)...... Booting the Cross Hill Board from the USB Flash Drive...... Booting the Galileo Board from the USB Flash Drive...... Booting a Hardware Target...... Starting a QEMU-based Target...... Appendix I: Preparing a USB Flash Drive...... Appendix II: Connecting to the Target Serial Port......

100 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

Appendix III: Updating the Flash Image...... Appendix IV: Booting Hardware Target from Micro SD Card...... Appendix V: Transferring IDP System Files to the USB Flash Drive (VFAT)...... Transferring System Files to the Internal SD Card on Cross Hill Board (VFAT)......

Selecting a Supported Target

In this section you will select the supported target which will set the environment variable $TARGET_BASE. This variable points to the prebuilt IDP platform project directory. 1 From the Fedora menu, select Applications > Wind River > Select Target > Intel Quark with IDP Platform.

2 Your selected target only applies for subsequent terminal window invocations. Close all terminal windows you may have open and start a new one.

Starting a Terminal Window

You will perform this lab from a command-line interface. The lab environment includes software you can use to develop IDP platforms and applications for various target boards. In this section you will start a terminal window and initialize some standard Wind River Linux environment variables. 1 From the Fedora menu, select Applications > System Tools > Terminal

Wind River Education Services 101 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

2 Execute the following commands to increase the /tmp directory size, initialize the Wind River Linux environment variables and check the variable settings.

sudo mkdir /tmp.new sudo chmod 1777 /tmp.new sudo mount -o bind /tmp.new /tmp

/home/wruser/WindRiver/wrenv.sh -p wrlinux-5

echo $WIND_LINUX_CONFIGURE /home/wruser/WindRiver/wrlinux-5/wrlinux/configure echo $TARGET_BASE /Labs/target-quark-idp-production The following table describes the environment variables.

Macro What It Represents

$WIND_LINUX_CONFIGURE The Wind River Linux configure script

$TARGET_BASE The directory containing the prebuilt Wind River Linux platform project

Configuring and Building an IDP Platform Project

In this section you will configure and build the IDP platform project. The IDP software comes primarily in source form — you must configure, compile, link, and prepare it for the target system. The build process uses the directions created by the configure command to transform the many packages from their source state into software that the target can run.

102 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

1 Execute the following commands to create a new directory where you will store your platform project. You can build your build environment anywhere you like.

mkdir -p ~/WindRiver/workspace/my-idp-project cd ~/WindRiver/workspace/my-idp-project

2 Execute the following command to configure an IDP platform project on your host computer that is similar to the prebuilt platform project in the directory $TARGET_BASE.

$WIND_LINUX_CONFIGURE \ --enable-board=intel-quark \ --enable-kernel=standard \ --enable-rootfs=glibc-idp \ --enable-addons=wr-idp \ --enable-jobs=4 \ --enable-parallel-pkgbuilds=4 The following describes the purpose of the arguments used: • The argument --enable-board=intel-quark defines the target board. The argument is required, but you can choose a board appropriate to your needs (intel-quark or intel- atom). • The argument --enable-addons=wr-idp tells the configure command to use layers that are part of the IDP product, in addition to what is included in Wind River Linux. This is necessary to access some specific IDP components that are discussed later. • The argument --enable-kernel=standard tells the configure command to use the standard kernel configuration. • The argument --enable-roofs=glibc-idp tells the configure command to use the recipe glibc-idp to build the root file system. This is based on the glibc-std root file system, but it includes packages that are unique to IDP. • The argument --enable-parallel-pkgbuilds=4 tells the configure command to let the build system build as many as four packages in parallel, when possible. Adjust this number to the number of cores on your host computer. • The argument --enable-jobs=4 tells the configure command to allow up to four concurrent compiles within a specific job (package). Adjust this number to the number of cores on your host computer. The actual configure command take a few minutes to execute completely, during which it processes the arguments given to it to populate the project directory with the data and scripts and programs necessary to build your project.

3 Now that you have configured the platform project, execute the following command to drive the build system (BitBake) to build your target image.

make

4 The build complete build can take hours to complete and may consume a lot of disk space. Press CTRL+C to stop this build, then use the pre-built project available in the directory $TARGET_BASE.

Wind River Education Services 103 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Preparing a Bootable USB Flash Drive

Skip this section if you are using a simulator, such us QEMU-KVM. In this section you will prepare a USB flash drive that you will use later to transfer IDP system files from the host computer to the target. 1 Insert a USB flash drive into your host system and execute the command -disks. Select the USB flash drive on the left. Memorize the assigned device name e.g. /dev/sdb.

gnome-disks In the figure below 16 GB USB drive is assigned to device /dev/sdb, is formatted as ext3 and mounted on the /run/media/wruser/idp mount point.

Transferring IDP System Files to the USB Flash Drive (VFAT+ext3)

In this section you will transfer prebuilt IDP system files to the USB flash drive. 1 Execute the deploy.sh script to decompress the image of the platform project onto the formatted USB flash drive. For -d option argument use assigned device name from 1 on page 6. For -b option replace boardtype with galileo or cross-hill.

cd $TARGET_BASE sudo ./deploy.sh -f \ /Labs/IDPGettingStartedLab/prebuilt/ \ intel-quark-glibc-idp-standard-dist-srm.tar.bz2 -d /dev/sdb -b boardtype -u

104 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

Two partitions are created on the USB flash drive. First partition is VFAT formatted and contains UEFI BIOS and GRUB boot loader with configuration file. Second partition is ext3 formatted and contains target root filesystem.

2 Execute the following command to synchronize transfers to the USB flash drive.

sync

NOTE: Wait until the light on the USB flash stops blinking before you remove drive.

3 Remove the USB flash drive from the host computer.

Booting the Cross Hill Board from the USB Flash Drive

In this section you will boot the target with the prepared USB flash drive. The following figure shows the rear view of the Intel Cross Hill board.

1 Use an Ethernet cable to connect the LAN0 connector on the Intel Cross Hill board to a LAN port on the host.

2 Set up a serial connection to the target. If you need help, perform the procedure described in Appendix II: Connecting to the Target Serial Port on page 12.

3 Insert the USB flash drive into the port USB Host Port – type A on the Intel Cross Hill board.

4 Attach the proper AC adaptor plug to the external power supply.

5 Insert the 2.1 mm circular connector on the power supply into the 5V DC input port of the Intel Cross Hill board. Observe that one LED lights up on each of the LAN ports.

6 When the target console displays the following message, select USB.

GNU GRUB version 0.97 (604K lower / 899964K upper memory)

+------+

Wind River Education Services 105 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

| IDP for Intel Quark-based Platform - USB | | IDP for Intel Quark-based Platform - MMC | Boot process will start on the target. IDP system will boot from the USB stick.

7 During the target boot, on the host computer execute the following command to check if the DHCP server on the host is in service.

sudo systemctl status dhcpd.service If the DHCP server status reports active (running), continue with step 9 on page 8.

8 If the DHCP server is not active, on the host execute the following commands to start it and check the status again.

sudo systemctl start dhcpd.service sudo systemctl status dhcpd.service

9 The boot process output on the target scrolls by, and eventually indicates that the target is ready to accept input. Log in as the user root, and when prompted enter the password root.

Wind River Linux 5.0.1.9 WR-IntelligentDevice console

WR-IntelligentDevice login: root Password:

Booting the Galileo Board from the USB Flash Drive

In this section you will boot the target with the prepared USB flash drive. The following figure shows the top view of the Intel Galileo board.

106 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

1 Use an Ethernet cable to connect the LAN connector on the board to a LAN port on the host.

2 Set up a serial connection to the target. If you need help, perform the procedure described in Appendix II: Connecting to the Target Serial Port on page 12.

3 Insert the USB flash drive into the port USB host port via the adaptor cable.

4 Attach the AC adaptor plug to the external power supply.

5 Insert the power connector on the power supply into the 5V DC power port. Observe LED lights up on the LAN port.

6 When the target console displays the following message, select USB.

GNU GRUB version 0.97 (604K lower / 899964K upper memory)

+------+ | IDP for Intel Quark-based Platform - USB | | IDP for Intel Quark-based Platform - MMC | Boot process will start on the target. IDP system will boot from the ext3 formatted USB stick.

7 During the target boot, on the host execute the following commands to check if the DHCP server on the host is in service.

sudo systemctl status dhcpd.service If the DHCP server status reports active (running), continue with step 9 on page 10.

Wind River Education Services 107 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

8 If the DHCP server is not active, on the host execute the following commands to start it and check the status again.

sudo systemctl start dhcpd.service sudo systemctl status dhcpd.service

9 The boot process output on the target scrolls by, and eventually indicates that the target is ready to accept input. Log in as the user root, and when prompted enter the password root.

Wind River Linux 5.0.1.9 WR-IntelligentDevice console

WR-IntelligentDevice login: root Password:

Booting a Hardware Target

In this section you will select proper boot procedure to boot a hardware target. 1. If you are using Cross Hill board boot your target as described in the section Booting the Cross Hill Board from the USB Flash Drive on page 7.

2. If you are using Galileo board boot your target as described in the section Booting the Galileo Board from the USB Flash Drive on page 8.

Starting a QEMU-based Target

In this section you will boot a QEMU-KVM-based target. 1 On the host computer, execute the following commands to change to the directory /Labs/ IDPGettingStartedLab, set up host networking, start QEMU and run the IDP platform project.

cd /Labs/IDPGettingStartedLab ./startqemu Select the proper number to start the correct QEMU target for your lab.

2 Once the target boots, execute the following commands to log in as the user root (when prompted enter the password root), then set the target IP address.

Wind River Linux 5.0.1.9 WR-IntelligentDevice console

WR-IntelligentDevice login: root Password: root@WR-IntelligentDevice:~# ifconfig eth0 10.1.1.10/24 up root@WR-IntelligentDevice:~#

3 Wind River device is now runing in a simulator; notice that some elements and features, like SRM, willl not work. When instructed execute the command poweroff to power off the QEMU target.

108 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

Appendix I: Preparing a USB Flash Drive

This appendix describes how to format a USB flash drive to FAT32 or ext3 format. 1 Insert the USB flash drive into your Linux host machine.

2 Execute the following command to confirm the device name assigned by the . This lab environment assigns the device name sdb to the USB flash drive.

dmesg | tail -n 25 [24794.407313] sd 4:0:0:0: [sdb] Attached SCSI removable disk [...] [24967.780638] scsi 5:0:0:0: Direct-Access IT1167B USB Flash Disk 0.00 PQ: 0 ANSI: 2 [24967.781871] sd 5:0:0:0: [sdb] 31711232 512-byte logical blocks: (16.2 GB/15.1 GiB) [...] [24967.788506] sdb: sdb1 [24967.804319] sd 5:0:0:0: [sdb] Asking for cache data failed [24967.804326] sd 5:0:0:0: [sdb] Assuming drive cache: write through [24967.804331] sd 5:0:0:0: [sdb] Attached SCSI removable disk

3 If there is a partition mounted on the USB device, execute the following command to unmount it.

umount /dev/sdb1

4 Execute the following command and enter the following information when prompted.

sudo fdisk /dev/sdb Welcome to fdisk (util-linux 2.21.2).

Changes will remain in memory only, until you decide to write them. Be careful before using the write command.

Command (m for help): d Selected partition 1 Partition 1 is deleted

Command (m for help): n Partition type: p primary (0 primary, 0 extended, 4 free) e extended Select (default p): p Partition number (1-4, default 1):1

First sector (2048-31711231, default 2048): Using default value 2048 Last sector, +sectors or +size{K,M,G} (2048-31711231, default 31711231): Using default value 31711231 Partition 1 of type Linux and of size 15.1 GiB is set

Command (m for help): w The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy. The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or kpartx(8) Syncing disks.

5 Do one of the following to create a file system on the new partition with the required format:

Wind River Education Services 109 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

File System Type Command

VFAT Execute the following command to format a vfat file system on the USB flash drive.

sudo mkdosfs /dev/sdb1 -s 128 -F 32 –I –n 'idp'

ext3 Execute the following command to format an ext3 file system on the USB flash drive.

sudo mkfs.ext3 -I 128 -L idp /dev/sdb1

Appendix II: Connecting to the Target Serial Port

This appendix describes how to connect a target serial port to the host USB port using a serial connection. You must have the following hardware and software: • a 3.5 mm to DB-9 cable • a DB-9 and DB-9 to USB cable • PuTTY telnet/ssh client software 1 Connect the 3.5 mm plug of the 3.5 mm to DB-9 cable to the RS-232 port on the target board, connect the DB-9 plug of the DB-9 to USB cable to the USB port on the host system, then join the two cables.

2 On the host computer, start a new terminal, then execute the following command to start PuTTY with super user privileges.

sudo putty

3 In the PuTTY Configuration dialog, configure the following settings: • In the Category field, select Session. • Below the Connection type choices, select Serial. • In the Serial line field, enter /dev/ttyUSB0. • In the Speed field, enter 115200.

110 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

4 In the Category field, select Terminal > Keyboard.

5 Under the The function keys and keypad choices, select SCO.

6 In the Category field, select Connection > Serial , then in the Flow control field select None.

7 Click Open to connect to the target.

Appendix III: Updating the Flash Image

This appendix describes how to update the flash image. 1 Power off the board.

2 Insert the USB flash drive provided with the board into the USB Host Port.

3 Power on the board.

Wind River Education Services 111 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

4 When the target console displays the following message, press F7 to get the boot menu.

Press [Enter] to directly boot. Press [F7] to show boot menu options.

5 In the boot menu, navigate to select UEFI Internal Shell, then on the keyboard press ENTER.

6 When prompted, enter map –u.

7 Locate your USB device (typically, it is fs1).

8 Enter fs1: then press ENTER.

9 Enter cd CapsuleUpdate then press ENTER.

10 Enter CapsuleApp.efi Flash-yourboard-8M-secured.cap then press ENTER. Replace yourboard with the type of your board e.g. crosshill, galileo, etc. This process takes about three minutes to complete. Note that there is no progress indicator. When the process finishes, the response in the following figure displays.

11 Power off the board and remove the USB flash drive from the board.

Appendix IV: Booting Hardware Target from Micro SD Card

This appendix describes how to boot a hardware target from a micro SD card. If you are using a hardware target (Cross Hill or Galileo) and have a micro SD card to boot, you have a choice to boot your hardware target from USB flash drive or micro SD card.

112 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

In this appendix you will perform the following tasks: • build a bootable USB image • copy the image to a USB flash drive • boot your target from the USB flash drive and copy the bootable image to the micro SD card • boot your target from the micro SD card 1 On your host machine, open a terminal window and invoke the following command to create a bootable USB image. For -b option replace boardtype with galileo or cross- hill.

sudo $TARGET_BASE/create-usbimg \ -f /Labs/IDPGettingStartedLab/prebuilt/\ intel-quark-glibc-idp-standard-dist-srm.tar.bz2 \ -o $TARGET_BASE/export/usb.img -b boardtype

[INFO] Board name: … … … … … … … … Done!

2 Insert a USB flash drive into your host computer and execute the following command to confirm the device name assigned by the OS.

dmesg | tail -n 25 [24794.407313] sd 4:0:0:0: [sdb] Attached SCSI removable disk [...] [24967.780638] scsi 5:0:0:0: Direct-Access IT1167B USB Flash Disk 0.00 PQ: 0 ANSI: 2 [24967.781871] sd 5:0:0:0: [sdb] 31711232 512-byte logical blocks: (16.2 GB/15.1 GiB) [...] [24967.788506] sdb: sdb1 [24967.804319] sd 5:0:0:0: [sdb] Asking for cache data failed [24967.804326] sd 5:0:0:0: [sdb] Assuming drive cache: write through [24967.804331] sd 5:0:0:0: [sdb] Attached SCSI removable disk

3 To copy the bootable image (usb.img) to the USB flash drive.

sudo dd if=$TARGET_BASE/export/usb.img of=/dev/sdb bs=4M 256+0 records in 256+0 records out 1073741824 bytes (1.1 GB) copied, 70.7429 s, 15.2 MB/s

NOTE: Change sdb to match your USB flash drive’s device name on your host computer.

4 Execute the following command to synchronize transfers to the USB flash drive.

sync

NOTE: Wait until the prompt (for example, $) displays before you remove it from the host computer.

5 5. Ensure your hardware target is power off and a micro SD card is in the card slot on the hardware target.

Wind River Education Services 113 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Board SD Slot Location

Cross Hill inside of the case

Galileo

6 Remove the USB flash drive from the host computer and insert it into your hardware target.

7 Boot your hardware target from USB flash drive. Board Type Booting Instructions

Cross Hill See the section Booting the Cross Hill Board from the USB Flash Drive on page 7 in this document.

Galileo See the section Booting the Galileo Board from the USB Flash Drive on page 8 in this document.

8 When the target console displays the following message, select USB.

GNU GRUB version 0.97 (604K lower / 899964K upper memory)

+------+ | IDP for Intel Quark-based Platform - USB | | IDP for Intel Quark-based Platform - MMC |

9 On the target console, execute the following command to copy the recovery image to the micro SD card. Type y when the installer ask you to “Restore the boot media to its factory defaults?” and “Need you to update Flash image, too”.

# tgt=/dev/mmcblk0 /sbin/reset_media Restore the boot media to its factory defaults? [y/n] y Board name: … … … … Need you to update Flash image, too [y/n] y Clearing original partitions in device ... … … … … ======Need warm reboot to update the Flash Image, please don't power off. ======

Broadcast message from root@WR-IntelligentDevice (console) (Mon May 12 18:15: The system is going down for reboot NOW! … … … …

114 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Getting Started with IDP

Start to update capsule image! Updated Blocks completed: 678 of 678 Capsule image is updated done! … … … …

NOTE: This command takes about 15 minutes to complete.

10 After the hardware target completes storing boot image to the micro SD card and update its BIOS flash image, the target will be automatically rebooted.

11 When the target console displays the following message, select MMC.

GNU GRUB version 0.97 (604K lower / 899964K upper memory)

+------+ | IDP for Intel Quark-based Platform - USB | | IDP for Intel Quark-based Platform - MMC |

Appendix V: Transferring IDP System Files to the USB Flash Drive (VFAT)

In this section you will transfer prebuilt IDP system files to the VFAT formatted USB flash drive. 1 If the USB flash drive is not formatted as FAT32, perform the procedure described in Appendix I: Preparing a USB Flash Drive on page 11.

2 Execute the following command to decompress the VFAT image of the platform project onto the USB flash drive.

tar -xvf /Labs/IDPGettingStartedLab/prebuilt/\ intel-quark-idp-srm-bundle.tar.bz2 \ -C /run/media/wruser/idp ./ ./rootfs.img ./EFI/ ./EFI/BOOT/ ./EFI/BOOT/BOOTIA32.EFI.csbh ./EFI/BOOT/BOOTIA32.EFI ./boot/ ./boot/bzImage.csbh ./boot/bzImage ./boot/grub.conf.csbh ./boot/grub.conf ./boot/grub/ ./boot/grub/grub.conf.csbh ./boot/grub/grub.conf

3 Execute the following commands to create the new directory wrs-idp-target under the mount point, and decompress the VFAT image in the new directory.

mkdir -p /run/media/wruser/idp/wrs-idp-target

tar -xvf /Labs/IDPGettingStartedLab/prebuilt/\ intel-quark-idp-srm-bundle.tar.bz2 \ -C /run/media/wruser/idp/wrs-idp-target ./ ./rootfs.img ./EFI/ ./EFI/BOOT/

Wind River Education Services 115 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

./EFI/BOOT/BOOTIA32.EFI.csbh ./EFI/BOOT/BOOTIA32.EFI ./boot/ ./boot/bzImage.csbh ./boot/bzImage ./boot/grub.conf.csbh ./boot/grub.conf ./boot/grub/ ./boot/grub/grub.conf.csbh ./boot/grub/grub.conf You will use this second copy of system files as source to program the internal SD card.

4 Execute the following command to synchronize transfers to the USB flash drive.

sync

NOTE: Wait until the light on the USB flash stops blinking before you remove drive.

5 Remove the USB flash drive from the host computer.

Transferring System Files to the Internal SD Card on Cross Hill Board (VFAT)

In this section you will install the IDP system files to the Cross Hill on-board micro SD card. 1 Boot the target from the VFAT formatted USB flash drive. On the target console, execute the following commands to install IDP to the on-board micro SD card.

umount /dev/mmcblk0p1 mount /dev/mmcblk0p1 /media/card mount /dev/sda1 /media/hdd rm -rf /media/card/* cp -R /media/hdd/wrs-idp-target/* /media/card

2 When the copy completes, execute the following command to shut down the target cleanly.

poweroff

This concludes the lab. Do not proceed.

116 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Generating Keys For IDP

© Copyright 2014, Wind River Systems, Inc.

117 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Generating Keys For IDP

Objective

In this lab you will create private keys and certificates, and then use them to create signed content for devices. Key management is an important aspect of IDP. In this lab you will create and use simulated keys. In the real world, keys and certificates come from other vendors, or you may already have private keys and certificates that you are using for other purposes. You will perform the following tasks: • create private keys • create certificates • sign a boot loader • sign a kernel image • sign an RPM

NOTE: This lab should take approximately 20 minutes.

Topics Covered

Installing the SST files in a Convenient Location...... Generating a Private Key for the Owner Role...... Generating a Certificate for the Owner Role...... Generating a Private Key for the Vendor Role...... Generating a Certificate for the Vendor Role...... Signing a Boot Loader...... Signing a Kernel Image...... Signing an RPM...... Using Additional SST Tools (optional)......

Installing the SST files in a Convenient Location

You can install secure remote management signing tool (SST) files anywhere on any Linux system. In this lab you will put them in the directory /Labs/SST, then run them from there in later sections.

118 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Generating Keys for IDP

1 Execute the following command to create the destination directory /Labs/SST for the SST files.

mkdir -p /Labs/SST

2 Execute the following commands to change to the current target project (deep in the target project hierarchy), then copy the SST files from there to the new location.

cd $TARGET_BASE/layers/wr-idp/wr-srm/recipes-devtools/sst/files cp -R * /Labs/SST/

Generating a Private Key for the Owner Role

In this section you will use the Wind River SST tool that you just installed in the directory /Labs/SST to create a simulated private key and certificate for the owner role. 1 Execute the following command to navigate to the directory containing the SST tool.

cd /Labs/SST

2 Execute the following commands to create a directory to hold the results for the owner role, then generate a private key and a certificate for the owner role and put it in that directory.

mkdir OwnerDir ./SST create-key \ --role=owner \ --verbose=no \ --machine=intel_quark \ --name=OwnerName \ --output-dir=./OwnerDir ############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################ WARNING: Using default value 'owner' for [issuer]

Generating a Certificate for the Owner Role

In this section you will create a certificate for the owner role (for which you have already created a key). First you must rename the owner certificate you created previously. 1 Execute the following commands to rename the certificate you built in step 2 on page 3.

cd /Labs/SST/OwnerDir mv OwnerName-cert.pem OwnerName-cert.pem.orig

2 Execute the following commands to generate the owner certificate and put it in the same directory as the private key you generated previously.

cd /Labs/SST ./SST create-key \

Wind River Education Services 119 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

--role=owner \ --verbose=no \ --priv-key=./OwnerDir/OwnerName-private.pem \ --machine=intel_quark \ --name=OwnerName \ --output-dir=./OwnerDir ############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################ WARNING: Using default value 'owner' for [issuer]

3 Execute the following commands to compare this new key to the one generated automatically previously. They are different — why?

cd OwnerDir diff OwnerName-cert.pem.orig OwnerName-cert.pem 2c2 MIICqjCCAhOgAwIBAgIJAMxWtPnRYtTOMA0GCSqGSIb3DQEBBQUAMIGWMQswCQYD 6c6 MB4XDTE0MDEyNjE3MzQzMloXDTI0MDEyNDE3MzQzMlowgZYxCzAJBgNVBAYTAkNO 13,16c13,16 [...]

You generated the certificates at different times. Because the certificate includes a timestamp from the time when you generated it (and other things), the certificates must be different.

Generating a Private Key for the Vendor Role

In this section you will use the Wind River SST tool to create a simulated key for the vendor role and put it in the same directory as the key for the owner role. Like the owner, the vendor must generate private keys and X.509v3 certificates. A vendor certificate lets the vendor create signed images and packages for device users, who can then validate any packages they receive from the vendor before installing them. In a production environment, the device owner issues the certificate. In a development environment, the SST tool lets you create development keys and certificates yourself. The SST tool generates both private keys and certificates. These are not production- ready keys, but keys that work for the test environment in this lab. In the real world, you would use your true private key and certificate. 1 Execute the following commands to create a directory to hold the results for the vendor role, then use SST to generate a key and put it in that directory.

cd /Labs/SST

2 Execute the following commands to create a directory to hold the results for the owner role, then generate a private key and a certificate for the owner role and put it in that directory.

cd /Labs/SST

120 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Generating Keys for IDP

mkdir VendorDir ./SST create-key \ --role=vendor \ --verbose=no \ --machine=intel_quark \ --name=VendorName \ --issuer=OwnerName \ --output-dir=./VendorDir ############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################

Generating a Certificate for the Vendor Role

In this section you will create a certificate for the vendor role (for which you have already created a key). First you must rename the vendor certificate you created previously. 1 Execute the following commands to rename the vendor certificate you built in step 2 on page 4.

cd /Labs/SST/VendorDir mv VendorName-cert.pem VendorName-cert.pem.orig

2 Execute the following commands to generate the vendor certificate and put it in the same directory as the private key you generated previously.

ccd /Labs/SST ./SST create-key \ --role=vendor \ --verbose=no \ --priv-key=VendorDir/VendorName-private.pem \ --machine=intel_quark \ --name=VendorName \ --issuer=OwnerName \ --output-dir=./VendorDir ############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################

3 Execute the following commands to compare this new key with the one generated automatically previously. They are different — why?

cd /Labs/SST/VendorDir diff VendorName-cert.pem.orig VendorName-cert.pem 2c2 MIICejCCAeOgAwIBAgIJAMxWtPnRYtTQMA0GCSqGSIb3DQEBBQUAMIGWMQswCQYD 6,16c6,15 MB4XDTE0MDEyNjE3NDI1OFoXDTE1MDEyNjE3NDI1OFowZzELMAkGA1UEBhMCQ04x >EDAOBgNVBAgMB0JlaWppbmcxEDAOBgNVBAcMB0JlaWppbmcxGjAYBgNVBAoMEVdp

Wind River Education Services 121 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

[...] >xsNftuTj9Jdf6b+6f98+tp9JCTDzbiWnsQVqcz4t+Qt+vbKeGOfLtXmdgvGkBS5o > hvoC981D8bFpEAJGjYM=

You generated the certificates at different times. Because the certificate includes a timestamp from the time when you generated it (and other things), the certificates must be different.

Signing a Boot Loader

In this section you will use the default keys in your platform project to sign the grub.efi and grub.conf files of the GRUB EFI boot loader from your target image. You can sign the boot loader that the system uses to load your kernel image to ensure a more secure system. You can check a signed boot loader to determine if the boot loader has been changed. If the check fails (that is, the boot loader was changed), you can assume it was compromised, and you can choose not to load the kernel. 1 Execute the following commands to copy the default key files at $TARGET_BASE/ layers/wr-idp/wr-srm/files/keys to the directory /Labs/SST.

$TARGET_BASE/layers/wr-idp/wr-srm/files/keys to the directory /Labs/SST .

2 Execute the following commands to copy the grub.efi and grub.conf files from your prebuilt target image.

cd /Labs/SST cp -v $TARGET_BASE/export/images/grub/grub.efi . `/Labs/target/export/images/grub/grub.efi' -> `./grub.efi' cp -v $TARGET_BASE/export/images/grub/grub-crosshill.conf grub.conf `/Labs/target/export/images/grub/grub-crosshill.conf' -> `grub.conf' cp -v grub.efi grub.efi.org `grub.efi' -> `grub.efi.org' cp -v grub.conf grub.conf.org `grub.conf' -> `grub.conf.org'

3 Execute the following commands to sign your boot loader image.

./SST sign-bootloader \ --machine=intel_quark \ --verbose=no \ --owner-cert=./keys/owner-cert.pem \ --romkey-dir=./keys/quark-romkey \ ./grub.efi

############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################ WARNING: Using default value './vendor-cert.pem' for [vendor-cert] WARNING: Using default value './vendor-private.pem' for [priv-key]

./SST sign-bootloader \ --machine=intel_quark \ --verbose=no \ --owner-cert=./keys/owner-cert.pem \ --romkey-dir=./keys/quark-romkey \ ./grub.conf

############################################################

122 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Generating Keys for IDP

## ## ## This is SRM Signing Tool! ## ## ## ############################################################ WARNING: Using default value './vendor-cert.pem' for [vendor-cert] WARNING: Using default value './vendor-private.pem' for [priv-key]

4 Execute the following commands to check what changes the signing process made to the file grub.efi.

ls /Labs/SST/grub.efi* /Labs/SST/grub.efi /Labs/SST/grub.efi.csbh /Labs/SST/grub.efi.org cmp -b /Labs/SST/grub.efi /Labs/SST/grub.efi.org /Labs/SST/grub.efi /Labs/SST/grub.efi.org differ: byte 178598, line 525 is 102 B 105 The responses indicate that the signing process created the new file grub.efi.csbh for the hardware secure ROM, and modified the file grub.efi for verified booting.

5 Execute the following commands to check what changes the signing process made to the file grub.conf.

ls /Labs/SST/grub.conf* /Labs/SST/grub.conf /Labs/SST/grub.conf.csbh /Labs/SST/grub.conf.org cmp -b /Labs/SST/grub.conf /Labs/SST/grub.conf.org

The responses indicate that the signing process generated the file grub.conf.csbh for secure ROM and did not modify the file grub.conf.

Signing a Kernel Image

In this section you will use the default keys in your platform project to sign a kernel image. You can sign the kernel image that your system boots to ensure that signature on the image booting matches your previous signature. You can configure your system so it cannot boot images that you did not sign. 1 Execute the following commands to copy the kernel image from your prebuilt target to the current directory, then use the SST command sign-kernel to sign it.

NOTE: The name of the binary file includes a date stamp — your file name may differ from the name in the following example.

cd /Labs/SST cp -v $TARGET_BASE/export/images/bzImage-intel-quark.bin \ bzImage-intel-quark.bin

`/Labs/target/export/images/bzImage-intel-quark.bin' -> `bzImage-intel-quark.bin' file bzImage-intel-quark.bin bzImage-intel-quark.bin: Linux kernel x86 boot executable bzImage, version 3.4.43- WR5.0.1.13_standard (wruser@localhost) #1 Thu Jun 26 16:, RO-rootFS, swap_dev 0x2, Normal VGA

cp -v bzImage-intel-quark.bin bzImage-intel-quark.bin.orig `bzImage-intel-quark.bin' -> `bzImage-intel-quark.bin.orig' ./SST sign-kernel --machine=intel_quark \ --verbose=no \ --romkey-dir=./keys/quark-romkey \

Wind River Education Services 123 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

--priv-key=./keys/vendor-private.pem \ --vendor-cert=./keys/vendor-cert.pem \ ./bzImage-intel-quark.bin

############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################

ls -l bzImage* -rw-rw-r-- 1 wruser wruser 1024 Feb 12 15:59 bzImage.csbh -rw-r--r-- 1 wruser wruser 2738085 Feb 12 15:59 bzImage-intel-quark.bin -rw-r--r-- 1 wruser wruser 2736960 Feb 12 15:59 bzImage-intel-quark.bin.orig

2 Execute the command cmp -b to compare the two kernel images and see how the signing process changed the kernel image. Observe that the signed image is larger.

Signing an RPM

In this section you will use the default keys in your platform project to sign an RPM file. As a vendor, each software update you deliver for your device will require a signed RPM file. If your release process uses the other IDP signing tools, you will likely do this often. 1 Execute the following commands to copy a small RPM file, then use the SST command sign-rpm to sign it.

cd /Labs/SST cp -v $TARGET_BASE/export/RPMS/all/update-rc.d-0.7-r4.all.rpm .

`/Labs/target/export/RPMS/all/update-rc.d-0.7-r4.all.rpm' -> `./update-rc.d-0.7- r4.all.rpm' cp -v update-rc.d-0.7-r4.all.rpm update-rc.d-0.7-r4.all.rpm.orig ` update-rc.d-0.7-r4.all.rpm' -> `update-rc.d-0.7-r4.all.rpm.orig' ./SST sign-rpm --mode=rpm \ --verbose=no \ --priv-key=VendorDir/VendorName-private.pem \ ./update-rc.d-0.7-r4.all.rpm

############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################

2 Execute the command cmp -b to compare the signed RPM file (with the extension.rpm) to the original version (with the extension .orig). Observe that the new PPM file is larger than the original file.

Using Additional SST Tools (optional)

The SST tool provides other options you can use — you can try some of them now if you have the time.

124 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Generating Keys for IDP

• Copy the files into the directory /Labs/SST and make a backup (similar to the way you used the format name.orig for backups in this lab), then change these copies — then you can compare the file before and after the signing process.

This concludes the lab. Do not proceed.

Wind River Education Services 125 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

126 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Tamper-proof File System

© Copyright 2014, Wind River Systems, Inc.

127 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Tamper-proof File System

Objective

In this lab you will work with a target system using the tamper-proof file system option provided with IDP. This lab demonstrates some features of the integrity measurement architecture of the secure remote management aspect of IDP. You will perform the following tasks: • demonstrate that unauthorized scripts will not run on an IDP target • contrast controlled invocation and uncontrolled invocation of programs on an IDP target • demonstrate that unauthorized/unsigned programs will not run on an IDP target

NOTE: This lab should take approximately 30 minutes.

Before You Begin

You will perform this lab on a target with secure remote management (SRM) capability. Boot the hardware target as instructed in Getting Started with IDP Lab, in the section Booting a Hardware Target. You cannot perform this lab on the QEMU-KVM simulated target.

Topics Covered

Running Authorized and Unauthorized Scripts...... Contrasting Controlled and Uncontrolled Script Invocation...... Running Authorized Programs......

Running Authorized and Unauthorized Scripts

In this section, you will run controlled invocations that compare authorized scripts (that is, with rootfs content provided by the vendor) and unauthorized scripts (that is, modified). You will use the imtools tool that is part of the IDP SRM system to demonstrate the point. A controlled invocation occurs when the system controls what runs (for example, when you run a script from the command line with just the name of the command). An uncontrolled invocation occurs when you run a script as an argument to a different

128 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Tamper-proof File System

command — in this case, the system checks the command invoked on the command line, not the arguments to it. 1 Execute the following commands to turn on the environment variable IMTOOL_SWITCH and run the program imtools from the directory /root.

# export IMTOOL_SWITCH=ON # imtools Usage:imtool --verifycert --listcert --removecert --get-rpm-imasign --verifyrpm --addimasign

2 Execute the following command to make a copy of the command imtools in the local directory.

# cp `which imtools` imtools2

3 Execute the new local command imtools2.

# ./imtools2 [ 1969.032693] IMA_Measurement: ERROR: /root/imtools2 failed appraisement -sh: ./imtools2: /bin/sh: bad interpreter: Permission denied

4 An error displays. Execute the following command to see the actual error code. Do not run any other commands before this, or you will see the return code from the last command!

# echo $? 126 Error 126 translates into ENOKEY, required key is not available. The Linux header file errno.h describes a complete list of error codes.

Contrasting Controlled and Uncontrolled Script Invocation

In this section you will run an uncontrolled invocation to observe how an uncontrolled invocation differs from a controlled invocation. 1 In another shell, execute the following command to run the program imtools as an uncontrolled invocation.

# sh imtools –h Usage:imtool --verifycert --listcert --removecert --get-rpm-imasign --verifyrpm --addimasign The uncontrolled invocation produces the same result as the previous controlled invocation.

Wind River Education Services 129 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

2 Execute the following command to run an uncontrolled invocation of your unauthorized imtools2 program.

# sh ./imtools2 –h Usage:imtool --verifycert --listcert --removecert --get-rpm-imasign --verifyrpm --addimasign The unauthorized command runs successfully as an uncontrolled invocation, but it failed as a controlled invocation. This shows why you should use controlled invocation for all commands — uncontrolled invocations can bypass security checks. While this might be useful for debugging, it is a security issue.

Running Authorized Programs

In this section, you will use a standard Linux command to compare authorized programs (that is, with vendor-provided rootfs content) and modified (or unauthorized) programs. 1 Execute the following command to run the standard, authorized command ls.

# ls examples imtools2

2 Execute the following command to make a copy of the ls command named ls-copy.

# cp `which ls` ls-copy # ls examples imtools2 ls-copy

3 Execute the following command to run the new, unauthorized command.

# ./ls-copy [ 1973.351620] IMA_Measurement: ERROR: /root/ls-copy failed appraisement -sh: ./ls-copy: Permission denied An error displays. You can repeat step 4 on page 3 to get the error from the shell.

4 Use an editor to create the new command newcmd (a simple shell script that executes the commands pwd and ls) with the following content.

#!/bin/bash pwd ls exit 0

5 Execute the following commands to verify the script content, then change and verify the script permissions.

# cat newcmd #!/bin/bash pwd ls exit 0

130 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Tamper-proof File System

# chmod +x newcmd # ls -l newcmd -rwxr-xr-x 1 root root 30 Oct 18 17:53 newcmd

6 Execute the following command to run the new, unauthorized command.

# ./newcmd [ 1978.072667] IMA_Measurement: ERROR: /root/newcmd failed appraisement -sh: ./newcmd: /bin/bash: bad interpreter: Permission denied The integrity measurement architecture (IMA) caught the attempt to run an unauthorized command (newcmd). This demonstrates that you cannot add content to the system then execute it.

This concludes the lab. Do not proceed.

Wind River Education Services 131 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

132 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Deploying Signed RPMs

© Copyright 2014, Wind River Systems, Inc.

133 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Deploying Signed RPMs

Objective

In this lab you will use a remote server to deploy signed RPMs to your target. This lab demonstrates some features of the integrity measurement architecture of the secure remote management (SRM) aspect of IDP. You will perform the following tasks: • create an RPM repository server • add a remote server to your target repository list • install software onto the target • remove a software package from the target

NOTE: This lab should take approximately 30 minutes.

Before You Begin

You will perform this lab on a target with secure remote management (SRM) capability. Boot the hardware target as instructed in Getting Started with IDP Lab, in the section Booting a Hardware Target. You cannot perform this lab on the QEMU-KVM simulated target. The Wind River IDP software installed on your target can install software from repositories, both local and remote, but you must configure it with the IP addresses of the servers that you will use. You must determine the following information before you start the lab: • the IP address of your host computer . Use the ifconfig command on the terminal window on your host computer to find this. • the IP address of your RPM server (referred to in this lab as $SERVER_IP). Use the ifconfig command on the terminal window on your RPM server to find this. • the IP address of your target that connects to the network on which the server resides. Your target has several network connections and you must determine the IP address of the connection that connects to your RPM server and host computer. Use the ifconfig command to find this. In a trivial network, the RPM server and host computer may be the same computer, with the same IP address and a different IP address for the target. In this configuration you could connect the target directly to the host computer and manually assign the IP addresses.

134 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Deploying Signed RPMS

Topics Covered

Creating an RPM Repository Server...... Adding a Remote Server to the Target Server List...... Installing Software from a Remote Repository...... Removing a Software Package from the Target......

Creating an RPM Repository Server

In this section you will configure an Apache web server that you will use to serve the RPM files. The configuration is similar to the default Apache configuration. You must add a directory to the default Apache search path and tell Apache what to do when a user requests content from those directories. When you configure your Apache web server, you must have the vendor private key used to create your target file system available on the server, so you can sign the contents of the server. If you do not sign the contents, the security features of spm_repo will not let you install new RPM files on your target. This lab uses the default key provided with IDP — do not use this key in a production environment. This lab uses the same directory structure as previous labs — in a production environment you will likely use a different directory structure. 1 Execute the following command to determine the current document root directory from the configuration file.

cat /etc/httpd/conf/httpd.conf | grep DocumentRoot # DocumentRoot: The directory out of which you will serve your DocumentRoot "/var/www/html" # This should be changed to whatever you set DocumentRoot to. # DocumentRoot /www/docs/dummy-host.example.com

2 Execute the following command to create the sub-directory rpm under the document root directory to hold the RPM files.

sudo mkdir -p /var/www/html/rpm/

3 Execute the following command to copy the RPM files created during the platform build process into the sub-directory you just created.

cd $TARGET_BASE/export/RPMS sudo cp -R * /var/www/html/rpm/

4 Execute the following command to edit the file /etc/httpd/conf/httpd.conf as the user root.

sudo vi /etc/httpd/conf/httpd.conf

Wind River Education Services 135 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5 Add following lines at the end of the file /etc/httpd/conf/httpd.conf, then save and close the file.

Options +Indexes You may also optionally hard code your server name or IP address in the Apache configuration file, as shown in the following example code snippets. Original line:

#ServerName www.example.com:80 Example modified line:

ServerName 192.168.2.250

6 Execute the following commands to sign the contents of your RPM server. You can sign all the contents of a directory with a single command. Signing the RPM files takes some time — the more RPM files, the more time this operation requires. In this case, the SST tool must sign approximately 3000 RPM files — this command may need a few minutes to complete.

cp $TARGET_BASE/layers/wr-idp/wr-srm/files/keys/\ vendor-private.pem /Labs/SST/VendorDir/ cd /Labs/SST sudo ./SST sign-rpm --mode=dir \ --priv-key=./VendorDir/vendor-private.pem \ /var/www/html/rpm/i586

############################################################ ## ## ## This is SRM Signing Tool! ## ## ## ############################################################ * DEBUG: regex=--\(mode\|priv-key\)=

% sign_rpms "/var/www/html/rpm/i586" ./VendorDir/vendor-private.pem

7 Execute the following commands to create the RPM infrastructure in the directories you created earlier.

cd /var/www/html/rpm/i586 sudo createrepo .

Spawning worker 0 with 2892 pkgs Workers Finished Gathering worker results

Saving Primary metadata Saving file lists metadata Saving other metadata Generating sqlite DBs Sqlite DBs complete

8 Execute the following commands to start the web server.

sudo apachectl restart httpd not running, trying to start

136 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Deploying Signed RPMS

9 Execute the following commands to verify that the Apache server is now running. Your output will be similar, though different from that shown below.

ps ax | grep httpd 29996 ? Ss 0:00 /usr/sbin/httpd -k restart 29997 ? S 0:00 /usr/sbin/httpd -k restart 29998 ? S 0:00 /usr/sbin/httpd -k restart 29999 ? S 0:00 /usr/sbin/httpd -k restart 30000 ? S 0:00 /usr/sbin/httpd -k restart 30001 ? S 0:00 /usr/sbin/httpd -k restart 30002 ? S 0:00 /usr/sbin/httpd -k restart 30003 ? S 0:00 /usr/sbin/httpd -k restart 30004 ? S 0:00 /usr/sbin/httpd -k restart 30006 pts/4 S+ 0:00 grep --color=auto httpd

Adding a Remote Server to the Target Server List

In this section you will 1 On your target, execute the following command to display the online help for the spm_repo command.

# spm_repo Usage:spm_repo --addremote --deleterepo --addlocal --listrepo --installrpm --deleterpm --listrpm (--verbose)

2 Execute the following command to display a list of the current repositories known to the target system.

# spm_repo --listrepo Below is all repositories on the target: rpmsys The default repository is rpmsys. It contains the software that was originally provided with the system.

3 Execute the following command to add the repository you created in the section Creating an RPM Repository Server to those currently known by the target.

NOTE: Replace the placeholder $SERVER_IP with the IP address for your host computer.

# spm_repo --addremote myrepo http://$SERVER_IP/rpm/i586 Adding remote repository myrepo successfully

4 Execute the following command to verify that your new repository is present.

# spm_repo --listrepo Below is all repositories on the target: rpmsys myrepo

Wind River Education Services 137 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Installing Software from a Remote Repository

In this section you will install documentation packages from a remote repository (your host computer) on the target. A typical IDP build creates these documentation packages, but does not install them on the target, as they are not typically used and not installing them saves valuable storage space. 1 Execute the following commands to verify that the documentation package (unzip-doc) is not currently installed, then install it.

# man unzip No manual entry for unzip # spm_repo --installrpm unzip-doc install unzip-doc successfully

2 Now execute the following command to verify that you have installed the unzip documentation.

# man unzip The unzip manual page displays.

3 On the keyboard, press q to exit from the manual viewer.

Removing a Software Package from the Target

In this section you will remove the unnecessary documentation packages you just installed on the target. 1 Execute the following command to delete the unnecessary documentation package from the target.

# spm_repo --deleterpm unzip-doc delete package unzip-doc successfully

2 Execute the following command to verify that you have removed the documentation package (unzip).

# man unzip No manual entry for unzip

This concludes the lab. Do not proceed.

138 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

© Copyright 2014, Wind River Systems, Inc.

139 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Using McAfee Embedded Control

Objective

In this lab you will integrate McAfee Embedded Control (MEC) into a Wind River Linux environment and use MEC to manage the inventory of executables, its configurations, operation modes, and log. You will also explore the core MEC features, including code and application protection, write and read protection, and dynamic whitelisting.

NOTE: This lab should take approximately 30 minutes.

Lab Overview

IDP provides a McAfee layer that lets you configure McAfee embedded products for the Wind River Linux target platform. McAfee embedded control (MEC) provides the following capabilities in Wind River Linux target platforms: • code and application protection, which only lets whitelisted programs (binary, executables, scripts) run. Any program that does not appear in the whitelist cannot run. This stops malicious programs from installing and functioning on the system. • tamper proofing for whitelisted programs so the files cannot be modified on the disk • write and read protection for all types of files, including data files, configuration files, directories, or volumes • dynamic whitelisting, which eliminates the need to manually maintain the inventory list of authorized applications. This feature lets you manage and update whitelisted files. In this lab you will perform the following tasks: • integrate MEC into your Wind River Linux environment • explore how MEC manages the inventory of executables, configurations, operation modes, and logging • enable McAfee embedded control • observe how the MEC code and application protection feature works • use the MEC updater component • verify the MEC write/read protection feature • use MEC update mode

Topics Covered

Integrating McAfee Embedded Control into Your Target...... Exploring McAfee Embedded Control......

140 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

Enabling McAfee Embedded Control...... Verifying MEC Code and Application Protection...... Using MEC Updaters...... Verifying MEC Write/Read Protection...... Using MEC Update Mode...... Disabling Application Control...... Appendix: Managing the ima-digsig Service......

Integrating McAfee Embedded Control into Your Target

In this section you will configure and build the IDP platform project with McAfee embedded control features. 1 On the host computer, execute the following commands to create a new directory where you will store your platform project. You can locate your build environment anywhere you like.

mkdir -p ~/WindRiver/workspace/my-mcafee-project cd ~/WindRiver/workspace/my-mcafee-project

2 Execute the following command to configure the platform project with the configuration parameter --with-layer=wr-mcafee (to use the McAfee embedded control layer).

$WIND_LINUX_CONFIGURE \ --enable-board=intel-quark \ --enable-kernel=standard \ --enable-rootfs=glibc-idp \ --enable-addons=wr-idp \ --with-layer=wr-mcafee \ --enable-jobs=3 \ --enable-parallel-pkgbuilds=3

The actual configuration will take a few minutes.

3 Execute the following command to build your target image.

make

4 The build takes some time to complete. Press CTRL+C to stop this build, then use a prebuilt kernel image and root file system for the rest of the lab. • Boot the target. Follow the instructions in the Getting Started with IDP Lab to boot the hardware target or to start a simulated target.

NOTE: A target console displays when the target boot completes. You will use this target console (where you logged in as the user root) as the administration terminal to manage MEC. In this lab, if an instruction says “as the MEC administrator”, execute the commands on this console.

Wind River Education Services 141 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5 Execute the command ifconfig on both the target console and the terminal window on your host computer to determine the following information that you will need to know for the lab: • The IP address of your target: ______.______.______.______Through this lab, this is referred to as $TARGET_IP. • The IP address of your host computer: ______.______.______.______Through this lab, this is referred to as $HOST_IP.

Exploring McAfee Embedded Control

In this section you will explore how McAfee embedded control (MEC) integrates into Wind River Linux and how MEC manages the inventory of executables, configurations, operation modes, and logging. When you build an IDP platform project with the McAfee layer, the platform project has an MEC RPM, and implements the MEC features on the image. The MEC RPM location is project-dir/bitbake_build/tmp/work/intel_quark-wrs-linux/ solidcores3-6.1.0_40028-r0/deploy-rpms/intel_quark/. The MEC location in the file system is project-dir/export/dist/usr/local/mcafee/solidcore/. 1 On the host computer, open a terminal window and execute the following command to confirm that your pre-built platform project has the MEC RPM.

$ ls -l $TARGET_BASE/bitbake_build/tmp/work/\ intel_quark-wrs-linux/solidcores3-6.1.0_40028-r0/\ deploy-rpms/intel_quark/ total 2188 -rw-r--r-- 1 wruser wruser 2229046 Apr 10 04:42 solidcores3-6.1.0_40028- r0.intel_quark.rpm -rw-r--r-- 1 wruser wruser 2973 Apr 10 04:42 solidcores3-dbg-6.1.0_40028- r0.intel_quark.rpm -rw-r--r-- 1 wruser wruser 3008 Apr 10 04:42 solidcores3-dev-6.1.0_40028- r0.intel_quark.rpm

2 Execute the following command to confirm that your pre-built platform project has MEC as a part of the image.

$ ls -l $TARGET_BASE/export/dist/usr/local/mcafee/solidcore total 96 drwx------2 wruser wruser 4096 Apr 10 04:54 bin -rw-r--r-- 1 wruser wruser 23676 Apr 10 04:30 EULA.txt drwx------3 wruser wruser 4096 Apr 10 04:54 kmod drwx------2 wruser wruser 4096 Apr 10 04:30 lib -rw-r--r-- 1 wruser wruser 10255 Apr 10 04:30 LICENSE_apache.txt -rw-r--r-- 1 wruser wruser 1723 Apr 10 04:30 LICENSE_BSDthreeclause.txt -rw-r--r-- 1 wruser wruser 1265 Apr 10 04:30 LICENSE_BSDtwoclause.txt -rw-r--r-- 1 wruser wruser 4179 Apr 10 04:30 LICENSE_DOC_ACE_TAO.txt -rw-r--r-- 1 wruser wruser 6279 Apr 10 04:30 LICENSE_openssl.txt -rw-r--r-- 1 wruser wruser 848 Apr 10 04:30 LICENSE_tinyxml.txt drwx------2 wruser wruser 4096 Apr 10 04:54 locale drwx------2 wruser wruser 4096 Apr 10 04:54 run drwx------2 wruser wruser 4096 Apr 10 04:54 scripts -rw-r--r-- 1 wruser wruser 12 Apr 10 04:30 solidcore.version drwx------4 wruser wruser 4096 Apr 10 04:54 tools

142 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

3 On the target console, as the MEC administrator, execute the following command to confirm that the MEC RPM is in the image running on the target.

# rpm -qa | grep solidcore solidcores3-6.1.0_40028-r0.intel_quark

4 Execute the following command to confirm that the MEC application control service (scsrvc) is running.

# ps -aef | grep scsrvc root 4140 1 0 14:59 ? 00:00:00 /usr/local/mcafee/solidcore/bin/scsrvc root 4143 4140 1 14:59 ? 00:02:10 /usr/local/mcafee/solidcore/bin/scsrvc root 31693 5281 0 17:44 ttyS1 00:00:00 grep scsrvc

5 Execute the following command to display the help menu.

# sadmin help Copyright 2008-2014 McAfee, Inc. All Rights Reserved. Usage: sadmin [options] [arguments]

Sadmin is the command line interface to administer McAfee Solidifier.

aef Modify or display advanced exclude filter rules. begin-update (bu) Begin update window to allow updates to the system disable Disable McAfee Solidifier control on next reboot enable Enable McAfee Solidifier control on next reboot end-update (eu) End update window help Display help for basic commands help-advanced Display help for advanced commands license Configure McAfee Solidifier licenses monitor (mon) Modify or display the monitoring rules passwd Set or unset a password for the actionable commands solidify (so) Solidify the system status Display status of McAfee Solidifier trusted Modify or display the rules for trusted paths unsolidify (unso) Unsolidify the specified file, directory or volume updaters Add, list or remove authorized updaters version Display version of McAfee Solidifier

Type 'sadmin help ' for detailed help on a specific command.

6 Execute the following command to review the list of all application control features and their status (enabled or disabled).

# sadmin features -d

checksum Enabled deny-exec Enabled deny-read Disabled deny-write Enabled integrity Enabled [...] script-auth Enabled Note the following aspects of the MEC features: • The feature deny-exec prevents unauthorized or unknown binaries from executing. It is based on whitelisting technology, which only lets binaries on the whitelist execute. • The feature script-auth is like deny-exec, but for scripts — only whitelisted script files can execute. • The feature deny-write provides tamper-proofing to protect data files (for example, configuration files). Unlike the deny-exec and script-auth features (which rely

Wind River Education Services 143 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

on a whitelist), the deny-write feature is rules-based. The MEC configuration file (solidcore.conf) records the rules. • The feature deny-read provides tamper-proofing to prevent reading of critical files. The feature deny-read is also rule based (like deny-write) — the MEC configuration file (solidcore.conf) records the rules. This feature is disabled by default. • The feature integrity protects MEC data and files from modification, renaming, or deletion.

7 As the MEC administrator, execute the following command to check the status of McAfee embedded control on your target.

# sadmin status McAfee Solidifier: Disabled McAfee Solidifier on reboot: Disabled

ePO Managed: No Local CLI access: Recovered

[fstype] [status] [driver status] [volume] * ext3 Unsolidified Unattached / Observe that the status is Unsolidified. The following table describes the fields and their meaning.

Field Description

McAfee Solidifier specifies the operational mode of application control

McAfee Solidifier on reboot specifies the operational mode of application control after a system restart

ePO Managed displays the connectivity status of application control with McAfee ePO. In a standalone configuration, this status is No.

Local CLI access displays the status (lockdown or recovered) of the local CLI. In standalone configuration, this status is Recovered.

[fstype] displays the supported file systems for a volume

[status] displays the current whitelist status for all the supported volumes on a system. If a volume name is specified, only the whitelist status for that volume displays.

144 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

Field Description

[driver status] displays whether the application control driver is loaded on a volume. If the driver is loaded, the status is attached; otherwise the status is unattached.

[volume] displays the volume names

8 Execute the following command to display the log file /usr/local/mcafee/solidcore/log/ solidcore.log.

# cat /usr/local/mcafee/solidcore/log/solidcore.log U.4140.4140: Apr 10 2014:14:48:04.900: SYSTEM: svci_unix_watcher.c: 252: Not starting userver as both rte mode and rte mode on reboot are set as Disabled. U.4143.4143: Apr 10 2014:14:48:04.931: SYSTEM: svci_unix_watcher.c: 477: Starting child scsrvc with pid: 4143. U.4143.4143: Apr 10 2014:14:48:05.064: SYSTEM: svc_init.c: 1415: Executing command: lsmod | grep scdrv [...] U.4143.4171: Apr 10 2014:15:56:57.859: SYSTEM: cmdi_process.c: 777: Command 'sadmin features' returned 0: No error U.4143.4171: Apr 10 2014:15:57:02.361: SYSTEM: cmdi_process.c: 777: Command 'sadmin features list' returned 0: No error U.4143.4170: Apr 10 2014:15:58:38.713: SYSTEM: cmdi_process.c: 777: Command 'sadmin status' returned 0: No error

9 Execute the following command to display the product configuration file /etc/mcafee/ solidcore/solidcore.conf.

# cat /etc/mcafee/solidcore/solidcore.conf | more ################################################################# # Solidifier Configuration File # # NOTE: Parts of this file are AUTOMATICALLY GENERATED. Please DO NOT edit # by hand. # # Copyright 2008 McAfee, Inc. All Rights Reserved. ################################################################# # # Runtime mode # RTEMode = 0

# # Runtime mode on next reboot # RTEModeOnReboot = 0

# # Lockdown status # LockdownStatus = 0x0

[...] Observe that the file includes following rules and configurations: • the run-time mode • the run-time mode on next reboot • the license • the features installed

Wind River Education Services 145 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

• the features enabled • write protect, read protect, and monitoring rules • the installation directory • the log file directory

10 On your host computer, open a new terminal window and start an SSH session to your target as the user wruser. When prompted, enter the password wruser.

# ssh wruser@$TARGET_IP The authenticity of host '$TARGET_IP($TARGET_IP)' can't be established. RSA key fingerprint is 35:ee:15:54:8c:28:61:aa:c9:df:85:80:df:a0:54:73. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added $TARGET_IP' (RSA) to the list of known hosts. wruser@$TARGET_IP's password: $

NOTE: You will use this new terminal window (where you logged in as the user wruser) as the user terminal to perform general user tasks (like running scripts). In this lab, if an instruction says “as the user”, execute the commands on this console.

11 As the user, execute the following command.

$ /usr/sbin/sadmin status Failed to connect to the McAfee Solidifier Service: Insufficient privileges. On MEC, only the administrator (the user root) can execute McAfee application control commands.

12 As the MEC administrator, execute the following command and set the password to admin.

# sadmin passwd New Password: Retype Password: Password changed. The administrator (the user root) can enable password protection to restrict execution of critical sadmin commands. When password protection is enabled, application control lets critical sadmin commands run only when the user enters in the correct password.

13 As the MEC administrator, execute the following command and enter a wrong password twice, then enter the correct password (admin).

# sadmin features list Password: Password: Password:

checksum Enabled deny-read Disabled deny-write Enabled integrity Enabled script-auth Enabled Application control only executes the command when you enter the correct password.

146 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

14 In the rest of this lab you will not use password protection. As the MEC administrator, execute the following command to remove the password protection.

# sadmin passwd -d Password: Password deleted.

Enabling McAfee Embedded Control

In this section you will generate an initial whitelist, enable MEC, and restart the McAfee solidifier service. Dynamic whitelisting is a core feature of MEC. The whitelist (or inventory) enumerates the set of programs (called authorized or solidified program code) that are allowed to run on the host computer. Any programs not in the whitelist are considered unauthorized — they cannot execute, and MEC logs their failed attempt to execute. Whitelisting does not change the files listed in the inventory. The command sadmin solidify creates the whitelist. This command takes an initial snapshot of the software implementation on the system and creates a whitelist of all binary executables (ELF format files) and scripts (that is, files on the local file system containing the characters #!, including ext2, ext3, and ext4 format files). 1 As the MEC administrator, execute the following command to create the initial whitelist.

# sadmin solidify /bin /boot /etc /lib /opt /root /sbin /usr /www 00:04:16: Total files scanned 18075, solidified 2237 This command may take 5 to 10 minutes to complete.

2 As the MEC administrator, execute the following command to confirm that MEC created the initial whitelist. The application control component stores a whitelist for each volume at volume/.solidcore/scinv.

# ls -l /.solidcore/scinv -rw-rw---- 1 root root 274113 Apr 10 17:18 /.solidcore/scinv

3 As the MEC administrator, execute the following command to check the status of McAfee embedded control.

# sadmin status McAfee Solidifier: Disabled McAfee Solidifier on reboot: Disabled

ePO Managed: No Local CLI access: Recovered

[fstype] [status] [driver status] [volume] * ext3 Solidified Unattached / Observe that the status changed to Solidified.

4 As the MEC administrator, execute the following command to enable MEC.

# sadmin enable McAfee Solidifier will be enabled on service restart.

Wind River Education Services 147 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5 As the MEC administrator, execute the following command to restart the McAfee solidifier service.

# service scsrvc restart McAfee Solidifier service stopped successfully. [ 1673.438853] Solidcore log buf: f8541460, f852d460 [ 1684.956911] scdrv: major no is: 247 [ 1684.975039] McAfee Solidifier module is loaded McAfee Solidifier service started successfully. If the system responses show Permission denied messages, perform the procedure in Appendix: Managing the ima-digsig Service on page 15 before you continue with step 6 on page 10.

[...] setfattr: /etc/extra-files/wifi/iwlwifi.sh: Permission denied setfattr: /etc/extra-files/wifi/rt2x00.sh: Permission denied setfattr: /etc/rc.local: Permission denied setfattr: /etc/cron.daily/logrotate: Permission denied setfattr: /etc/functions.sh: Permission denied setfattr: /opt/testsuite/tsstests.sh: Permission denied [...]

6 As the MEC administrator, execute the following command to verify that MEC is enabled.

# sadmin status McAfee Solidifier: Enabled McAfee Solidifier on reboot: Enabled

ePO Managed: No Local CLI access: Recovered

[fstype] [status] [driver status] [volume] * ext3 Solidified Attached / Observe that the status of the McAfee Solidifier and McAfee Solidifier on reboot parameters changed to Enabled, and the driver status changed to Attached.

Verifying MEC Code and Application Protection

In this section you will use the scripts /mcafee_lab/script1.sh and /mcafee_lab/script2.sh to observe how MEC code and application protection works. MEC only lets whitelisted programs (binaries, executables, or scripts) run — any program not in the whitelist cannot run. 1 Review the contents of the simple scripts /mcafee_lab/script1.sh and / mcafee_lab/script2.sh to understand what they do. The script /mcafee_lab/script1.sh the following contents.

#!/bin/bash

echo "Test script1" ./script2.sh The script /mcafee_lab/script2.sh has the following contents.

#!/bin/bash

148 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

echo "Test script2 executed from script1"

2 As the user, execute the following commands to move to the directory /mcafee_lab, then execute script1.sh.

$ cd /mcafee_lab $ ./script1.sh -sh: ./script1.sh: /bin/bash: bad interpreter: Permission denied Note the response Permission denied— MEC did not allow the script to run.

3 As the MEC administrator, execute the following command to review the messages in the log file solidcore.log so you can determine the reason for the Permission denied error.

# cat /usr/local/mcafee/solidcore/log/solidcore.log | tail -n 1 U.0793.0827: Apr 14 2014:06:00:30.614: ERROR: evt.c: 1240: McAfee Solidifier prevented unauthorized execution of '/mcafee_lab/script1.sh' by process sh (Process Id: 1021, User: wruser). The response indicates that MEC prevented script1.sh executed by the user wruser from running.

4 As the MEC administrator, execute the following commands to check if script1.sh is on the whitelist.

# sadmin list-solidified | grep /mcafee_lab/script1.sh No output displays — this confirms that script1.sh is not on the whitelist.

5 As the MEC administrator, execute the following commands to add script1.sh on the whitelist.

# sadmin so /mcafee_lab/script1.sh 00:00:00: Total files scanned 1, solidified 1

6 As the user, execute the following command to run script1.sh again.

$ ./script1.sh Test script1 ./script1.sh: ./script2.sh: /bin/bash: bad interpreter: Permission denied

The response Test script1 displays (indicating that script1.sh ran successfully), followed by the error message Permission denied against script2.sh.

Using MEC Updaters

In this section you will use MEC updaters to maintain a whitelist. Some MEC-authorized programs may frequently update software components on your system automatically. You can add such programs as updaters, so MEC authorizes them to update the software components. Updaters bypass the MEC deny-edev, script-auth, deny-write, and deny-read components to reconcile the changes in the whitelist.

Wind River Education Services 149 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

1 As the MEC administrator, execute the following commands to add script1.sh to the updater then verify that script1.sh is added to updater.

# sadmin updaters add /mcafee_lab/script1.sh # sadmin updaters list -t AUTO_1 /mcafee_lab/script1.sh

2 As the user, execute the following commands to run script1.sh again.

$ ./script1.sh Test script1 Test script2 executed from script1 This time the response indicates that script1.sh executed without error.

Verifying MEC Write/Read Protection

In this section you will implement write and read protection to the file /mcafee_lab/ data_file. MEC not only protects executable files, but also data files (including configuration files). The MEC write/read protection feature provides tamper-proofing for all kinds of files. Unlike the code and application protection feature (which relies on the whitelist), the write/read protection feature is rule-based (with rules recorded in the MEC configuration file). 1 As the MEC administrator, execute the following command to set write protection for the file /mcafee_lab/data_file.

# sadmin wp –i /mcafee_lab/data_file

2 As the MEC administrator, execute the following command to review the MEC configuration file and confirm that you added a rule to write-protect /mcafee_lab/ data_file.

# cat /etc/mcafee/solidcore/solidcore.conf | more [...] # # Write protect rules # WriteProtectionRules = { "+ /mcafee_lab/data_file" } [...]

3 As the user, execute the following commands to review the contents of /mcafee_lab/ data_file, then add the string some more data to the file.

$ cat data_file # This data file should not be changed .... some data

$ echo "some more data" >> data_file -sh: data_file: Permission denied

150 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

4 As the MEC administrator, execute the following command to review the messages in the log file solidcore.log so you can determine the reason for the Permission denied error.

# cat /usr/local/mcafee/solidcore/log/solidcore.log | tail -n 1 U.0793.0827: Apr 14 2014:07:14:02.383: ERROR: evt.c: 1240: McAfee Solidifier prevented an attempt to modify file '/mcafee_lab/data_file' by process sh (Process Id: 6673, User: wruser). The response indicates that MEC prevented the user wruser from changing the file / mcafee_lab/data_file.

5 As the MEC administrator, execute the following command to review the status of the MEC features.

# sadmin features checksum Enabled deny-read Disabled deny-write Enabled integrity Enabled script-auth Enabled The response indicates that the deny-read feature is disabled (the default setting).

6 Now, as the MEC administrator, execute the following command to enable the deny- read feature then verify the new status of the MEC features.

# sadmin features enable deny-read # sadmin features root@WR-IntelligentDevice:/# sadmin features

checksum Enabled deny-read Enabled deny-write Enabled integrity Enabled script-auth Enabled

The response indicates that you successfully enabled the deny-read feature.

7 As the MEC administrator, execute the following command to set read protection for the file /mcafee_lab/data_file.

# sadmin rp –i /mcafee_lab/data_file

8 As the MEC administrator, execute the following command to review the MEC configuration file and confirm that you added read protection for the file /mcafee_lab/ data_file.

# cat /etc/mcafee/solidcore/solidcore.conf | more [...] # # Read protect rules # ReadProtectionRules = { "+ /mcafee_lab/data_file" } [...]

Wind River Education Services 151 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

9 Now as the user, execute the following command to display the contents of /mcafee_lab/ data_file.

$ cat data_file cat: data_file: Permission denied

10 As the MEC administrator, execute the following command to review the messages in the log file solidcore.log so you can determine the reason for the Permission denied error.

# cat /usr/local/mcafee/solidcore/log/solidcore.log | tail -n 1 U.0793.0827: Apr 14 2014:07:34:29.219: ERROR: evt.c: 1240: McAfee Solidifier prevented an attempt to read file '/mcafee_lab/data_file' by process /bin/ cat.coreutils (Process Id: 5111, User: wruser). The response indicates that MEC prevented the user wruser from reading the file / mcafee_lab/data_file.

Using MEC Update Mode

In this section you will use MEC update mode to update the file /mcafee_lab/data_file, which is write and read protected. When MEC is in update mode it allows all changes on a protected system. You can use update mode to complete maintenance tasks, such as installing patches or upgrading software and data files. 1 As the MEC administrator, execute the following commands to check the current MEC status, change the MEC operational mode to update, then verify the new status.

# sadmin status McAfee Solidifier: Enabled McAfee Solidifier on reboot: Enabled

ePO Managed: No Local CLI access: Recovered

[fstype] [status] [driver status] [volume] * ext3 Solidified Attached /

# sadmin bu McAfee Solidifier is entering update mode. # sadmin status McAfee Solidifier: Update McAfee Solidifier on reboot: Update

ePO Managed: No Local CLI access: Recovered

[fstype] [status] [driver status] [volume] * ext3 Solidified Attached

2 As the user, execute the following commands to display then update the contents of the file /mcafee_lab/data_file.

$ cat /mcafee_lab/data_file # This data file should not be changed .... some data

$ echo "some more data" >> data_file # This data file should not be changed ....

152 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using McAfee Embedded Control

some data some more data

3 Now that you have modified /mcafee_lab/data_file, as the MEC administrator, execute the following commands to change the MEC operational mode from update to enable and verify the new status.

# sadmin eu McAfee Solidifier is exiting update mode. # sadmin status McAfee Solidifier: Enabled McAfee Solidifier on reboot: Enabled

ePO Managed: No Local CLI access: Recovered

[fstype] [status] [driver status] [volume] * ext3 Solidified Attached /

4 As the MEC administrator, execute the following commands to test that update mode is closed and write/read protection is working.

# cat /mcafee_lab/data_file cat: /mcafee_lab/data_file: Permission denied # echo "some more data" >> data_file -sh: /mcafee_lab/data_file: Permission denied The Permission denied responses confirm that you cannot read or change the file, and that MEC protection is working.

Disabling Application Control

In this section, you will disable the MEC feature to return your target to the standard configuration. 1 As the MEC administrator, execute the following command to switch MEC to disabled mode to deactivate the features of MEC application control.

sadmin disable

2 As the MEC administrator, execute the following command to reboot the target.

reboot

Appendix: Managing the ima-digsig Service

Sometimes when you start the McAfee solidifier service, MEC may display Permission denied messages that indicate MEC prevented the process /usr/bin/setfattr from modifying the applications. This results from operation of the ima-digsig service which IMA appraisal uses on an SRM enabled image. This section describes how to avoid these Permission denied messages. The ima-digsig service uses the command setattr to flush the signatures in the extended attribute of all files in the file system. The ima-digsig service starts after the target comes

Wind River Education Services 153 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

up and executes every three seconds to access files and flush the signatures. If the files are on the MEC whitelist, MEC sees this activity as unauthorized modifications and prevents it (and displays Permission denied messages). 1 As the MEC administrator, execute the following command to disable MEC — this stops the Permission denied error.

# sadmin disable

2 Execute the following command to stop the ima-digsig service.

# service ima-digsig stop

3 The service ima-digsig stop command does not kill the service completely — execute the following commands to determine the ID for the process /usr/bin/ ima_digsig_daemon.sh, then kill the process.

# ps -ef | grep ima* root 1167 1 0 15:51 ? 00:00:04 /bin/sh /usr/bin/ima_digsig_daemon.sh root 5139 3693 0 16:16 ttyS1 00:00:00 grep ima*

# kill -9 1167 # ps -ef | grep ima* root 5139 3693 0 16:16 ttyS1 00:00:00 grep ima*

4 Execute the following command to enable MEC and restart the McAfee solidifier service.

# sadmin enable McAfee Solidifier will be enabled on service restart.

5 Execute the following command to add ima_digsig_daemon.sh as an updater, then verify that it is on the list of authorized updaters.

# sadmin updaters add ima_digsig_daemon.sh # sadmin updaters list -t AUTO_1 ima_digsig_daemon.sh

6 Execute the following command to start the mia-digsig service.

# service ima-digsig restart

Now the system does not display Permission Denied error messages.

This concludes the lab. Do not proceed.

154 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

© Copyright 2014, Wind River Systems, Inc.

155 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Configuring Encrypted Storage

Objective

In this lab you will learn how to configure an encrypted storage.

NOTE: This lab should take approximately 20 minutes.

Overview

IDP XT’s encrypted storage feature provides protection on a block device by encrypting it. To access the device’s decrypted contents, a user must provide a key for authentication. In this lab, you will perform the following tasks: • Create an encryption key and configure the dm-crypt block device with the encryption key.

- /dev/urandam is a character device and provides an interface to the kernel's random number generator. File /dev/urandom has major device number 1 and minor device number 9. When read, /dev/urandom device will return as many bytes as requested. In this lab, you will use /dev/urandom to create a key. - Device-mapper is a Linux kernel infrastructure and provides a generic way to create virtual layers of block devices that can do different things on top of real block devices. Device-mapper is used by LVM2 tools. - dm-crypt is one of the device-mapper targets and provides transparent encryption of block devices. dm-crypt device mapper resides in the kernel space and is only responsible for handling encryption and decryption of the block device’s data.

156 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

- cryptsetup is a user space front-end and is used to create and activate encrypted volumes based on dm-crypt kernel module and also manages authentication. - Linux Unified Key Setup (LUKS) is a specification for block device encryption and it establishes an on-disk format for the data as well as establishing key management policy. LUKS is based on dm-crypt and cryptsetup command line interface provides commands to deal with LUKS. • Create a dummy key and verify the encrypted storage feature by attempting to mount the LUKS-encrypted device with the dummy key with the result being failure.

• Verify the encrypted storage feature by attempting to mount the LUKS-encrypted device with the encryption key to ensure success.

If you are using QEMU-KVM simulated target, or if you are using a hardware target but you don’t have a micro SD card to boot, you will configure and verify encrypted storage with a loop device. If you are using a hardware target, have a micro SD card to boot, and have a blank or unused USB flash drive, you have a choice to configure and validate encrypted storage with a USB flash drive or a loop device.

Wind River Education Services 157 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Topics Covered

Enabling Encrypted Storage...... Configuring Encrypted Storage with a Loop Device...... Mounting the LUKS-Encrypted Loop Device Using a Dummy Key...... Mounting the LUKS-Encrypted Loop Device Using the Encryption Key...... Configuring Encrypted Storage with a USB Flash Drive...... Mounting the LUKS-Encrypted USB Flash Drive Using a Dummy Key...... Mounting the LUKS-Encrypted USB Flash Drive Using the Encryption Key......

Enabling Encrypted Storage

In this section you will confirm that the pre-built target platform project satisfies the prerequisites to use IDP XT’s encrypted storage feature. • wr-srm layer includes dm-crypt kernel capability and cryptsetup front end tool which you use to implement secure storage. To use encrypted storage feature, configure your platform project with --enable-rootfs=glibc-idp. • Using encrypted storage requires that the following Linux kernel configuration options enabled. - CONFIG_BLK_DEV_MD (Device mapper support) - CONFIG_DM_CRYPT (Crypt target support) You can confirm the settings of the above Linux Kernel configuration options by using Linux kernel menuconfig tool. • Additionally, the following software packages are required. - lvm2-2.02.95: This is Logical Volume Manager administration tools which supports handling read/write operations on physical volumes (hard disks, RAID- Systems …), creating volume groups (virtual disks) from one or more physical volumes and creating one or more logical volumes (logical partitions) in volume groups. - cryptsetup-1.6.1: This is user space setup tool for transparent encryption of block devices using dm-crypt kernel module. - trousers-0.30.10: Trousers is an implementation of trusted computing group's software stack (TSS) specification. . 1 On your host machine, open a terminal window and invoke the following command to confirm that the platform project has been built with --enable-rootfs=glibc-idp.

cat $TARGET_BASE/config.log … … … … /wrlinux-5/wrlinux/configure --enable-board=intel-quark --enable- kernel=standard --enable-rootfs=glibc-idp … … … …

158 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

2 Execute the following command to open the menuconfig window.

make -C $TARGET_BASE/build linux-windriver.menuconfig It will take about a minute to open the menuconfig window, which will look similar to the following figure.

3 To check the setting of CONFIG_BLK_DEV_MD, select Device Drivers > Multiple device driver support (RAID and LVM) and confirm that Device mapper support is enabled.

4 To check the setting of CONFIG_DM_CRYPT, select Device Drivers > Multiple device driver support (RAID and LVM) > Device mapper support and confirm that Crypt target support is enabled.

5 You can confirm if the required software packages are on the device by executing the following command.

$ rpm --root=$TARGET_FS -qa | grep 'lvm2\|cryptsetup\|trousers' lvm2-2.02.95-r0.1.i586 trousers-0.3.10-r0.i586 cryptsetup-1.6.1-r0.i586

6 Do one of the following, depending on your target environment:

Wind River Education Services 159 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Target Type Configuration Process

If you are using QEMU-KVM 1. Boot your target. simulated target, or using a 2. Perform the following sections. hardware target but you don’t have a micro SD card to boot, • Configuring Encrypted Storage with a Loop or if you decide to use a loop Device device to configure encrypted • Mounting the LUKS-Encrypted Loop Device storage: Using a Dummy Key • Mounting the LUKS-Encrypted Loop Device Using the Encryption Key

If you are using a hardware 1. Boot your target from a micro SD card. target, have a micro SD card to 2. Perform the following sections. boot, have a blank or unused USB flash drive, and you • Configuring Encrypted Storage with a USB decided to use a USB flash drive Flash Drive to configure encrypted storage: • Mounting the LUKS-Encrypted USB Flash Drive Using a Dummy Key • Mounting the LUKS-Encrypted USB Flash Drive Using the Encryption Key

Configuring Encrypted Storage with a Loop Device

In this section you will perform the following tasks: • create an encryption key • create a loop device • format the loop device as a LUKS partition and mount to a mapper device • format the mapped device as normal ext3 and create a mount point to access the mapped device In this section, you will execute all commands in the target console. 1 In /home directory create a new file called mykey, size = 32 Bytes, filled with random numbers

dd if=/dev/urandom of=/home/mykey bs=1 count=32 32+0 records in 32+0 records out 32 bytes (32 B) copied, 0.00781993 s, 4.1 kB/s You are using this file as an encryption key.

2 Unlock the memory block limit by executing the following commands.

ulimit -Hl unlimited ulimit -Sl unlimited

160 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

3 Loop device is a pseudo-device that makes a file accessible as a block device. Before you setup loop device, check the first unused loop device name by executing the following commands.

dev=`losetup -f` echo $dev

/dev/loop1 This stores the first unused loop device name to $dev. throughout this section, this loop device name is referred to as $dev.

4 In /home directory create a new file called secret_dir, this file contains 10Mbytes of random numbers.

dd if=/dev/urandom of=/home/secret_dir bs=1M count=10 10 10+0 records in 10+0 records out 10485760 bytes (10 MB) copied, 38.6149 s, 272 kB/s]

5 Setup $dev loop device with /home/secret_dir file by executing the following command.

losetup $dev /home/secret_dir

6 In this step, you will format the loop device as a LUKS partition. The following shows an example of the usage of cryptsetup to format a device as a LUKS partition.

cryptsetup luksFormat \ --key-file= --debug • --key-file= reads the key from a file. • is the encrypted device • -debug shows debug messages Execute the following command to format the $dev loop device as a LUKS partition with the /home/mykey encryption key which you created in the previous step.

cat /home/mykey | cryptsetup luksFormat \ --key-file=- $dev --debug # cryptsetup 1.6.1 processing "cryptsetup luksFormat … … … … # Running command luksFormat. # Locking memory. … … … … # Unlocking memory. Command successful. • Observe that the pipe “|”connects the standard output file descriptor of “cat /home/ mykey” as the standard input file descriptor of “--key-file=-”

7 In this step, you will mount the LUKS partition to a mapper device. The following shows an example of the usage of cryptsetup to mount the LUKS partition to a mapper device.

cryptsetup luksOpen \ --key-file= --debug • --key-file= reads the key from a file.

Wind River Education Services 161 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

is the encrypted device • is the device to create under /dev/mapper • -debug shows debug messages Mount the $dev LUKS-encrypted device to secret mapper device with /home/mykey encryption key by executing the following command.

cat /home/mykey | cryptsetup luksOpen \ --key-file=- $dev secret --debug # cryptsetup 1.6.1 processing "cryptsetup luksOpen … … … … # Running command open. # Locking memory. … … … … # Unlocking memory. Command successful.

8 Execute the following command to confirm that the mapper device secret was created.

ls -l /dev/mapper/ total 0 crw------1 root root 10, 236 Apr 23 19:03 control brw------1 root root 253, 0 Apr 23 19:19 secret

9 Format the mapped device /dev/mapper/secret as a normal ext3 block device by executing the following command.

mkfs.ext3 -I 128 /dev/mapper/secret 1.42.1 (17-Feb-2012) Filesystem label= OS type: Linux … … … … Writing superblocks and filesystem accounting information: done

10 To access the mapped device /dev/mapper/secret, you need a mount point on the target’s root file system. Execute the following commands to create a directory named /home/ mysecretdir, and mount the mapped device /dev/mapper/secret.

mkdir /home/mysecretdir mount -t ext3 /dev/mapper/secret /home/mysecretdir

[ 913.697447] kjournald starting. Commit interval 5 seconds [ 913.706204] EXT3-fs (dm-0): using internal journal [ 913.711412] EXT3-fs (dm-0): mounted filesystem with … … …

Mounting the LUKS-Encrypted Loop Device Using a Dummy Key

In this section you will perform the following tasks: • create a file in the encrypted device • create a dummy key • Attempt to mount the LUKS-encrypted loop device with the dummy key and confirm that it fails In this section, you will execute all commands in the target console.

162 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

1 Execute the following command to create a file named secret_text_file.txt in the encrypted device which you mounted to /home/mysecretdir in the previous step.

echo "This is a secret text." > \ /home/mysecretdir/secret_text_file.txt

2 Read the contents of /home/mysecretdir/secret_text_file.txt by executing the following command.

cat /home/mysecretdir/secret_text_file.txt This is a secret text.

3 Reboot the target.

reboot

4 In /home directory create a file named otherkey, size = 32 Bytes, filled with random numbers

dd if=/dev/urandom of=/home/otherkey bs=1 count=32 32+0 records in 32+0 records out 32 bytes (32 B) copied, 0.00781993 s, 4.1 kB/s You are using this file as a dummy key.

5 Perform the following tasks as shown in Configuring Encrypted Storage with a Loop Device on page 6 section. a) Unlock the memory block limit. b) Check the first unused loop device name and store to a variable named dev. throughout this section, this loop device name is referred to as $dev. c) Setup $dev loop device with /home/secret_dir file.

6 Now, attempt to mount $dev LUKS-encrypted device to secret mapper device with the dummy key, /home/otherkey, by executing the following command.

cat /home/otherkey | cryptsetup luksOpen \ --key-file=- $dev secret --debug # cryptsetup 1.6.1 processing "cryptsetup luksOpen … … … … # Running command open. # Locking memory. … … … … # Unlocking memory. Command failed with code 1: No key available with this passphrase. The failure is expected because the key, /home/otherkey, does not match the encryption key, /home/mykey, which you used to generate the encrypted device.

Mounting the LUKS-Encrypted Loop Device Using the Encryption Key

In this section you will attempt to mount the LUKS-encrypted loop device with the encryption key and confirm that is a success.

Wind River Education Services 163 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

In this section, you will execute all commands in the target console. 1 Reboot the target.

2 Perform the following tasks as shown in Configuring Encrypted Storage with a Loop Device on page 6 section. a) Unlock the memory block limit. b) Check the first unused loop device name and store to a variable named dev. throughout this section, this loop device name is referred to as $dev. c) Setup $dev loop device with /home/secret_dir file.

3 Now, attempt to mount $dev LUKS-encrypted device to secret mapper device with the encryption key, /home/mykey, by executing the following command.

cat /home/mykey | cryptsetup luksOpen \ --key-file=- $dev secret --debug # cryptsetup 1.6.1 processing "cryptsetup luksOpen … … … … # Running command open. # Locking memory. … … … … # Unlocking memory. Command successful. This time the device mounts successfully.

4 Now, you can access and read the contents of LUKS-encrypted device. Execute the following commands to mount secret mapped device to /home/mysecretdir and read the contents of secret_text_file.txt file.

mount -t ext3 /dev/mapper/secret /home/mysecretdir [ 913.697447] kjournald starting. Commit interval 5 seconds [ 913.706204] EXT3-fs (dm-0): using internal journal [ 913.711412] EXT3-fs (dm-0): mounted filesystem with … … …

cat /home/mysecretdir/secret_text_file.txt This is a secret text. This is the end of this lab.

Configuring Encrypted Storage with a USB Flash Drive

NOTE: • You cannot perform this section on the QEMU-KVM simulated target. • To perform this section you need to be able to boot your hardware target from a Micro SD card on the target, and you need a blank or unused USB flash drive.

In this section you will perform the following tasks: • create an encryption key • format a USB flash drive as a LUKS partition and mount to a mapper device • format the mapped device as normal ext3 and create a mount point to access the mapped device

164 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

In this section, you will execute all commands in the target console. 1 Make sure the USB flash drive is NOT connected to your hardware target, and then boot the target from the micro SD card.

2 In /home directory create a file named mykey-usb, size = 32 Bytes, filled with random numbers

dd if=/dev/urandom of=/home/mykey-usb bs=1 count=32 32+0 records in 32+0 records out 32 bytes (32 B) copied, 0.00781993 s, 4.1 kB/s

3 Unlock the memory block limit by executing the following commands.

ulimit -Hl unlimited ulimit -Sl unlimited

4 Connect a USB flash drive to your target.

5 Find the device name of the USB flash drive partition on your target.

fdisk -l … … … … Device Boot Start End Blocks Id System /dev/sda1 2048 31711231 15854592 b W95 FAT32 In this section /dev/sda1 is referred to as the device name of USB flash drive on the target.

6 In this step, you will format the USB flash drive as a LUKS partition. The following shows an example of the usage of cryptsetup to format a device as a LUKS partition.

cryptsetup luksFormat \ --key-file= --debug • --key-file= reads the key from a file. • is the encrypted device • -debug shows debug messages Execute the following command to format the USB flash drive as a LUKS partition with the /home/mykey encryption key which you created in the previous step.

cat /home/mykey | cryptsetup luksFormat \ --key-file=- $dev --debug # cryptsetup 1.6.1 processing "cryptsetup luksFormat … … … … # Running command luksFormat. # Locking memory. … … … … # Unlocking memory. Command successful. • Observe that the pipe “|”connects the standard output file descriptor of “cat /home/ mykey” as the standard input file descriptor of “--key-file=-”

7 In this step, you will mount the LUKS partition to a mapper device. The following shows an example of the usage of cryptsetup to mount the LUKS partition to a mapper device.

Wind River Education Services 165 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

cryptsetup luksOpen \ --key-file= --debug • --key-file= reads the key from a file. • is the encrypted device • is the device to create under /dev/mapper • -debug shows debug messages Mount the LUKS-encrypted device (USB flash derive) to secret-usb mapper device with /home/mykey encryption key by executing the following command.

cat /home/mykey | cryptsetup luksOpen \ --key-file=- /dev/sda1 secret-usb --debug # cryptsetup 1.6.1 processing "cryptsetup luksOpen … … … … # Running command open. # Locking memory. … … … … # Unlocking memory. Command successful.

8 Execute the following command to confirm that the mapper device secret was created.

ls -l /dev/mapper/ crw------1 root root 10, 236 Apr 23 19:03 control brw------1 root root 253, 0 Apr 23 19:19 secret-usb

9 Format the mapped device /dev/mapper/secret as a normal ext3 block device by executing the following command.

mkfs.ext3 -I 128 /dev/mapper/secret 1.42.1 (17-Feb-2012) Filesystem label= OS type: Linux … … … … Writing superblocks and filesystem accounting information: done

10 To make the access to the mapped device /dev/mapper/secret, you need a mount point in the target’s root file system. Execute the following commands to create a directory named /home/mysecretdir, and mount the mapped device /dev/mapper/secret.

mkdir /home/mysecretdir mount -t ext3 /dev/mapper/secret-usb /home/mysecretdir

[ 913.697447] kjournald starting. Commit interval 5 seconds [ 913.706204] EXT3-fs (dm-0): using internal journal [ 913.711412] EXT3-fs (dm-0): mounted filesystem with … … …

Mounting the LUKS-Encrypted USB Flash Drive Using a Dummy Key

166 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

NOTE: • You cannot perform this section on the QEMU-KVM simulated target. • To perform this section you need to be able to boot your hardware target from a Micro SD card on the target, and you need a blank or unused USB flash drive.

In this section you will perform the following tasks: • create a file in the encrypted device • create a dummy key • Attempt to mount the LUKS-encrypted USB flash drive with the dummy key and confirm that it fails In this section, you will execute all commands in the target console. 1 Execute the following command to create a file named secret_text_file.txt in the encrypted device which you mounted to /home/mysecretdir in the previous step.

echo "This is a secret text." > \ /home/mysecretdir/secret_text_file.txt

2 Read the contents of /home/mysecretdir/secret_text_file.txt by executing the following command.

cat /home/mysecretdir/secret_text_file.txt This is a secret text.

3 Remove the USB flash drive from the target.

4 Reboot the target.

reboot

5 In /home directory create a file named otherkey, size = 32 Bytes, filled with random numbers

dd if=/dev/urandom of=/home/otherkey bs=1 count=32 32+0 records in 32+0 records out 32 bytes (32 B) copied, 0.00781993 s, 4.1 kB/s You are using this file as a dummy key.

6 Unlock the memory block limit by executing the following commands.

ulimit -Hl unlimited ulimit -Sl unlimited

7 Connect a USB flash drive to your target.

Wind River Education Services 167 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

8 Now, attempt to mountLUKS-encrypted USB flash drive to secret-usb mapper device with the dummy key, /home/otherkey, by executing the following command.

cat /home/otherkey | cryptsetup luksOpen \ --key-file=- /dev/sda1 secret-usb --debug # cryptsetup 1.6.1 processing "cryptsetup luksOpen … … … … # Running command open. # Locking memory. … … … … # Unlocking memory. Command failed with code 1: No key available with this passphrase. The failure is expected because the key, /home/otherkey, does not match the encryption key, /home/mykey, which you used to generate the encrypted device.

Mounting the LUKS-Encrypted USB Flash Drive Using the Encryption Key

In this section you will attempt to mount the LUKS-encrypted USB flash drive with the encryption key and confirm that it is successful.

NOTE: • You cannot perform this section on the QEMU-KVM simulated target. • To perform this section you need to be able to boot your hardware target from a Micro SD card on the target, and you need a blank or unused USB flash drive.

In this section, you will execute all commands in the target console. 1 Remove the USB flash drive from the target.

2 Reboot the target.

3 Unlock the memory block limit by executing the following commands.

ulimit -Hl unlimited ulimit -Sl unlimited

4 Connect a USB flash drive to your target.

5 Now, attempt to mountLUKS-encrypted USB flash drive to secret mapper device with the encryption key, /home/otherkey, by executing the following command.

cat /home/otherkey | cryptsetup luksOpen \ --key-file=- /dev/sda1 secret-usb --debug # cryptsetup 1.6.1 processing "cryptsetup luksOpen … … … … # Running command open. # Locking memory. … … … … # Unlocking memory. Command successful. This time the device mounts successfully.

168 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Configuring Encrypted Storage

6 Now, you can access and read the contents of LUKS-encrypted device. Execute the following commands to mount secret mapped device to /home/mysecretdir and read the contents of secret_text_file.txt file.

mount -t ext3 /dev/mapper/secret /home/mysecretdir [ 913.697447] kjournald starting. Commit interval 5 seconds [ 913.706204] EXT3-fs (dm-0): using internal journal [ 913.711412] EXT3-fs (dm-0): mounted filesystem with … … …

cat /home/mysecretdir/secret_text_file.txt This is a secret text.

7 Remove the USB flash drive from the target.

8 Reboot the target.

This concludes the lab. Do not proceed.

Wind River Education Services 169 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

170 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

© Copyright 2014, Wind River Systems, Inc.

171 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Exploring Webif

Objective

Webif provides. In this lab you will use Webif (a web browser interface for managing targets) to review and alter the operation of you target. During this lab, you will perform the following tasks: • connect to the target using Webif • view the CPU utilization of the targe • review syslog events • add Webif users and give them different views into the target • use the ping command to verify that the target can connect to various systems • alter the boot operation of the target system

NOTE: This lab should take approximately 45 minutes.

Topics Covered

Before You Begin...... Launching and Accessing the Webif Interface...... Working with the Info Page...... Working with the Graphs Page...... Working with the Status Page...... Working with the Log Page...... Working with the System Page...... Logout Page......

Before You Begin

In this lab, you will use a host computer to connect to the target. Your configuration may use either a hardware target or a simulated QEMU target. The following figure shows the lab topology.

172 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

1 Follow the instructions in the Getting Started with IDP Lab to boot the hardware target or to start a simulated target.

2 Once the target boots, execute the following commands to log in as the user root (when prompted enter the password root), then set the target IP address.

Wind River Linux 5.0.1.12 WR-IntelligentDevice console

WR-IntelligentDevice login:root Password: root@WR-IntelligentDevice:~# ifconfig eth0 10.1.1.10/24 up root@WR-IntelligentDevice:~#

3 Execute the ifconfig command on both the target console and the terminal window for your host computer to determine the following information that you will need to know for the lab: • The IP address of your target: ______.______.______.______Through this lab, this is referred to as $TARGET_IP. • The IP address of your host computer (tap0 interface): ______.______.______.______Through this lab, this is referred to as $HOST_IP.

Launching and Accessing the Webif Interface

1 From a terminal window on your host computer, execute the following command to start a Firefox web browser session running in the background (so you can use this terminal and shell later in the lab).

$ firefox & [1] 27128

2 Use the https - secure http protocol. Set the browser to the address of your target ($TARGET_IP). Click on "I Understand the Risks", then click on "Add Exception", and on "Confirm security exception".

Wind River Education Services 173 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

3 Log in to the Webif interface with the default user name (admin), and when prompted enter the default password admin.

Firefox displays the System – Wind River Intelligent Device Platform Administrative Console page at the Info tab.

174 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

Working with the Info Page

The Info page is the default landing page for Webif. There are three tabs here, System (the default), Notes, and About. The Notes page lets you store notes about this particular system (you can write anything you want). These notes remain available each time you log in. 1 Click the Notes tab, then enter a note about this system.

2 Experiment with the Save Changes and Revert buttons. Click Save Changes to save changes to your notes. Click Revert to remove any changes you have made but have not yet saved. Try deleting text after you have saved it — does the previous version of the notes display when you click Revert? How many changes can you revert?

NOTE: You must click Save Changes to save changes to this page. Webif does not save changes to this page when you click Apply Changes, Clear Changes, or Review Changes.

3 Click the About tab. The Webif2 credits scroll automatically after a few seconds.

Wind River Education Services 175 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Working with the Graphs Page

1 Click the Graphs tab. The page has two sub-tabs, CPU (default) and Interfaces. It takes few seconds before the page displays data. The CPU usage varies depending on the processes and tasks running on your target. If you navigate away from this page then return, the graph displays new data beginning from the left margin.

176 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

2 Click the Interfaces tab. This is a tall page that displays a graph for each network interface. Scroll to see the other interfaces. Observe that there is not much traffic on most of the interfaces. Why is that?

3 On the target console, execute the following command to generate some network traffic.

# ping -c 5 $HOST_IP -s 64000

4 On the Webif page on your host computer, on the Graphs > Interface tab, watch the Traffic of Interface eth0 graph change.

Wind River Education Services 177 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

5 You can change the scale of each graph on the Graphs > Interface tab. Click Switch to bytes/s to change the scale from Kbps (kilobits per second) to KB/s (kilobytes per second). You can switch back and forth as you like.

Working with the Status Page

1 Click the Status tab. The System sub-tab displays the total space and available space on each mount point, as well as the memory usage and tracked connections. Under the Tracked Connections section, click View Conntrack Table to display additional information about your tracked connections (on the Status > Conntrack tab).

178 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

2 Click the Processes tab to display a current list of processes running on the target. The page refreshes every 20 seconds, unless you click Stop Refreshing. Click see the legend to display a legend that describes processes states. Which command output does this page display?

Wind River Education Services 179 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

3 Click the Conntrack sub-tab to display the currently tracked connections. You can filter out data to focus on the issue you want to resolve. In the Text to Filter field, enter ESTABLISHED | TIME_WAIT and in the Filter Mode field select Exclude, then click Filter Records to filter these connections out of the display. A subset of the records displays. Verify if the pattern match is case-sensitive.

180 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

4 Click the Diagnostics sub-tab to run the ping and traceroute commands for network diagnosis. In the field to the left of the Ping or TraceRoute button, enter $HOST_IP (The IP address of your host computer), then click the button.

Note: you can ping and traceroute any domain if Internet access is avalaible. Internent access is not avaliable if you are in a Live-Remote class.

Working with the Log Page

1 Click the Log tab. The initial view is the Syslog sub-tab, which displays the syslog file. You can use the Text Filter section to filter in or out content that you do or do not want to see in the log.

2 In the Text to Filter field, enter usb | USB, in the Filter Mode field select Include, then click Filter Messages to find all messages in syslog related to USB. Did you get any messages that you did not expect?

Wind River Education Services 181 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

3 Click the Kernel sub-tab and notice that the messages are similar to those in the Syslog sub-tab, with the same filtering ability. Filter for IMA | ima and observe that TPM is not supported.

182 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

Working with the System Page

1 Click the System tab. The default Access Control sub-tab lets you add, modify, and remove Webif users to control who can use different pages and tabs within the Webif program. Note that Webif users are not system user log in names.

Wind River Education Services 183 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

NOTE: Do not change the Webif Enable field from Enable. If you disable this field, you will lose the Webif connection to the target, and you must restart Webif from the target.

2 In the Username field, enter Testuser, in the Password field enter Testpass and reenter that password in the Confirm Password field, then click Add User to add that user to the Webif user database.

3 Give the user Testuser access to some of the Webif pages. Scroll down the Access Control sub-tab to configure the following settings, then scroll to the bottom of the page and click Save Changes. After the screen refreshes, scroll to the bottom again and click Apply Changes. • In the Info section, in the System field, select Enabled. • In the Logout section, in the Logout field, select Enabled.

184 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Exploring Webif

NOTE: You must click on both Save Changes and Apply Changes for your changes to take effect.

4 Close the browser.

5 Start another browser session then connect to the target, but log in in as the user Testuser. Could you log in? How does the display differ from before?

6 Close the browser.

Logout Page

1 Start a browser session and log in as the user admin.

2 Click the Logout tab, then close the browser. This is the recommended procedure to disconnect from the target system.

Wind River Education Services 185 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

This concludes the lab. Do not proceed.

186 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using IDP MultiWAN

© Copyright 2014, Wind River Systems, Inc.

187 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Using IDP MultiWAN

Objective

In this lab you will enable and use the IDP multiWAN functionality and failover capability.

NOTE: This lab should take approximately 20 minutes.

Overview

The IDP multiWAN functionality lets you configure multiple wide area networks (WANs) in your system. It also monitors the status of the networking interfaces, so if the primary interface goes down, a daemon automatically connects to the secondary interface. The multiWAN functionality is part of the wridp-devkit layer and is included on your IDP XT target. In this lab the target is an Intel Cross Hill board that supports Ethernet and 3G wireless WAN. In this lab you will perform the following tasks: • enable a 3G wireless WAN (WWAN) connection on your target • enable the multiWAN functionality • change the primary WAN from WAN to WWAN • verify the multiWAN failover capability

Before you begin

In this lab, you must deploy the kernel image and root file by using deploy.sh script with “-b cross-hill” option. For help, see the section Transferring IDP System Files to the USB Flash Drive (ext3) in the Getting Started with IDP Lab guide.

Topics Covered

Placing a SIM Card on the Target...... Enabling the 3G WWAN Connection...... Enabling the MultiWAN Functionality...... Changing the Primary WAN...... Verifying Failover Capability......

188 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using IDP MultiWAN

Placing a SIM Card on the Target

In this section you will place a SIM card on your target (the Intel Cross Hill board). 1 Disconnect all cables, including Ethernet, serial, and power cables from the Cross Hill board, then open the case of the Cross Hill board.

2 Verify that the antennas are connected correctly to the Telit HE910 modem.

3 Remove the Telit HE910 modem from the socket.

4 Insert your SIM card into the slot on the modem.

5 Replace the Telit HE910 modem in the socket and secure it in place.

6 Close the case of Cross Hill board.

7 Reconnect the Ethernet and serial cables.

8 Boot your target. For help, see the section Booting Cross Hill board from the USB flash drive in the Getting Started With IDP Lab guide.

Wind River Education Services 189 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Enabling the 3G WWAN Connection

In this section you will enable the 3G WWAN connection on the Intel Cross Hill board.. 1 On the target, execute the following command to verify that you have following settings for the interface wwan, and the devices modem_cell and sim_card.

cat /etc/config/network [...] config interface 'wwan' option ifname '3g-wwan' option proto '3g' option device '/dev/ttyACM0' option ppp_redial 'demand' option defaultroute '1' option peerdns '1' option service 'umts_first' option sconnservice 'UMTS' option dialnumber '*99***1#'

config device 'modem_cell' option name 'modem_cell' option present 'Yes' option protoall '3g' option pppddev '/dev/ttyACM0' option statedev '/dev/ttyACM3' option Manufacturer 'Telit' option Product 'HE910' option Vendor '1bc7' option ProdID '0021' option SerialNumber '357164040778055' option Rev '12.00.003'

config device 'sim_card' option name 'sim_card' option present 'Yes' option IMSI '302720406815819

2 On your target, execute the following command to verify the IP address of the eth0 interface.

ifconfig eth0 eth0 Link encap:Ethernet HWaddr 00:08:a2:09:06:04 inet addr:128.224.140.238 Bcast:128.224.141.255 Mask:255.255.254.0 inet6 addr: fe80::208:a2ff:fe09:604/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:18621 errors:0 dropped:7 overruns:0 frame:0 TX packets:4743 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1955834 (1.8 MiB) TX bytes:988903 (965.7 KiB) Interrupt:40 Base address:0xc000

3 Launch Webif. For help, see the section Launching and Accessing the Webif Interface in Exploring Webif Lab.

4 From the Webif menu, select Network > Networks.

190 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using IDP MultiWAN

5 In the wan Configuration panel, in the DHCP Connection Type field select DHCP, and in the Interface field select eth0.

6 In the wwan Configuration panel, configure the following settings: • In the Connection Type field, select WWAN. • In the Interface field, select 3g-wwwan. • In the Device field, select /dev/ttyAMC0. • In the APN Name field, select the correct APN name for your SIM card. • Select Default Route and Peer DNS.

7 Click Save Changes, then click Apply Changes.

Wind River Education Services 191 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

The network service on your target restarts — allow about one minute for the restart to complete.

8 On your target, execute the following command to verify the IP address of the interface 3g-wwan.

ifconfig 3g-wwan 3g-wwan Link encap:Point-to-Point Protocol inet addr:25.48.75.88 P-t-P:25.48.75.88 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1 RX packets:8 errors:0 dropped:0 overruns:0 frame:0 TX packets:9 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:3 RX bytes:122 (122.0 B) TX bytes:164 (164.0 B)

Enabling the MultiWAN Functionality

In this section you will enable the multiWAN functionality for Internet communication from your target. 1 From the Webif menu, select Network > MultiWAN.

2 In the Multi WAN Monitor Configuration panel, in the Multi WAN Monitor Enable field, select Enable.

3 In the Monitor Configuration For wan panel, in the Failover To field select wwan, and select Auto Up.

192 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using IDP MultiWAN

4 In the Monitor Configuration For wwan panel, in the Failover To is wan field select, and select Auto Up.

5 Click Save Changes then click Apply Changes and wait until the MultiWAN page refreshes.

Changing the Primary WAN

The multiWAN functionality lets you to select the primary WAN. In this section you will use Webif to configure the primary WAN. 1 From the Webif menu, select Network > Multiwan.

2 In the Multi WAN Monitor Configuration panel, in the Priority Interface field, select wan.

Wind River Education Services 193 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

3 Click Save Changes then click Apply Changes and wait until the MultiWAN page refreshes.

4 On the target, execute the following command to confirm that the target can connect to the Internet.

ping –c 3 www.google.ca PING www.google.ca (74.125.131.94) 56(84) bytes of data. 64 bytes from vc-in-f94.1e100.net (74.125.131.94): icmp_req=1 ttl=44 time=44.0 ms 64 bytes from vc-in-f94.1e100.net (74.125.131.94): icmp_req=2 ttl=44 time=45.5 ms 64 bytes from vc-in-f94.1e100.net (74.125.131.94): icmp_req=3 ttl=44 time=43.6 ms

--- www.google.ca ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2002ms rtt min/avg/max/mdev = 43.652/44.412/45.576/0.870 ms

5 Execute the following commands to check the default gateway and network path.

route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 128.224.140.1 0.0.0.0 UG 0 0 0 eth0 128.224.140.0 * 255.255.254.0 U 0 0 0 eth0 172.31.255.0 * 255.255.255.0 U 0 0 0 eth0 192.168.1.0 * 255.255.255.0 U 0 0 0 br-lan

tracepath www.google.ca 1: 128.224.140.238 2.174ms pmtu 1500 1: 128.224.140.1 2.253ms 1: 128.224.140.1 12.002ms 2: 128.224.244.42 2.916ms 3: 128.224.252.1 3.797ms 4: unallocated-static.rogers.com 4.625ms 5: 69.63.253.134 5.585ms 6: so-5-0-0.gw02.bloor.phub.net.cable.rogers.com12.543ms 7: 24.156.144.182 21.253ms 8: no reply [...] The response indicates that the default gateway uses the eth0 interface as the primary connection.

6 In the Multi WAN Monitor Configuration panel, in the Priority Interface field, select wwan.

194 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using IDP MultiWAN

7 Click Save Changes then click Apply Changes and wait until the MultiWAN page refreshes.

8 On the target, execute the following command to confirm that the target can connect to the Internet.

ping –c 3 www.google.ca PING www.google.ca (74.125.131.94) 56(84) bytes of data. 64 bytes from vc-in-f94.1e100.net (74.125.131.94): icmp_req=1 ttl=44 time=43.8 ms 64 bytes from vc-in-f94.1e100.net (74.125.131.94): icmp_req=2 ttl=44 time=43.9 ms 64 bytes from vc-in-f94.1e100.net (74.125.131.94): icmp_req=3 ttl=44 time=43.5 ms

--- www.google.ca ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2003ms rtt min/avg/max/mdev = 43.540/43.794/43.952/0.249 ms

9 Execute the following commands to check the default gateway and network path.

route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 25.48.75.88 0.0.0.0 UG 0 0 0 3g-wwan 128.224.140.0 * 255.255.254.0 U 0 0 0 eth0 172.31.255.0 * 255.255.255.0 U 0 0 0 eth0 192.168.1.0 * 255.255.255.0 U 0 0 0 br-lan

tracepath www.google.ca 1: 25.48.75.88 2.738ms pmtu 1500 1: 10.118.23.206 199.195ms asymm 2 1: 10.118.23.206 147.853ms asymm 2 2: 10.118.23.209 135.844ms 3: 10.118.20.10 105.917ms 4: 10.118.20.77 103.828ms 5: 192.168.1.75 105.988ms 6: 192.168.1.21 140.003ms asymm 4 7: 24.156.157.153 107.695ms asymm 4 8: 24.156.146.38 108.085ms asymm 9 9: 24.156.157.129 114.168ms asymm 10 10: 24.156.146.153 144.041ms asymm 11 11: 24.156.144.182 148.105ms asymm 12 12: no reply [...] The response indicates that the default gateway uses the 3g-wwan interface as the primary connection.

Verifying Failover Capability

The multiWAN functionality monitors the status of the network interfaces. When the primary interface goes down, the multiWAN functionality switches over to the secondary interface. In this section you will verify that when the Ethernet interface fails, the system switches to the 3G WWAN interface. 1 From the Webif menu, select Network > Multiwan.

Wind River Education Services 195 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

2 In the Multi WAN Monitor Configuration panel, in the Priority Interface field, select wan.

3 Click Save Changes then click Apply Changes and wait until the MultiWAN page refreshes.

4 On the target, execute the following command to confirm that the target can connect to the Internet.

ping –c 3 www.google.ca PING www.google.ca (173.194.46.56) 56(84) bytes of data. 64 bytes from ord08s10-in-f24.1e100.net (173.194.46.56): icmp_req=1 ttl=49 time=119 ms 64 bytes from ord08s10-in-f24.1e100.net (173.194.46.56): icmp_req=2 ttl=49 time=120 ms 64 bytes from ord08s10-in-f24.1e100.net (173.194.46.56): icmp_req=3 ttl=49 time=177 ms

--- www.google.ca ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2003ms rtt min/avg/max/mdev = 119.827/139.270/177.239/26.853 ms

5 Execute the following commands to check the default gateway and network path.

route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 128.224.140.1 0.0.0.0 UG 0 0 0 eth0 128.224.140.0 * 255.255.254.0 U 0 0 0 eth0 172.31.255.0 * 255.255.255.0 U 0 0 0 eth0 192.168.1.0 * 255.255.255.0 U 0 0 0 br-lan

tracepath -n www.google.ca 1: 128.224.140.238 2.163ms pmtu 1500 1: 128.224.140.1 2.215ms 1: 128.224.140.1 2.470ms 2: 128.224.244.42 2.980ms 3: 128.224.252.1 3.884ms 4: 69.17.142.113 4.901ms 5: 69.63.253.134 7.857ms 6: 66.185.81.77 10.656ms 7: 24.156.144.182 21.345ms 8: no reply [...] The response indicates that the default gateway of the Cross Hill board connects to the Internet through the eth0 interface, which is the primary connection at this moment.

6 Disconnect the Ethernet cable from the Cross Hill board and wait about one minute.

7 On the target, execute the following command to confirm that the target can connect to the Internet.

ping –c 3 www.google.ca PING www.google.ca (74.125.225.120) 56(84) bytes of data. 64 bytes from ord08s08-in-f24.1e100.net (74.125.225.120): icmp_req=1 ttl=49 time=162 ms 64 bytes from ord08s08-in-f24.1e100.net (74.125.225.120): icmp_req=2 ttl=49 time=121 ms 64 bytes from ord08s08-in-f24.1e100.net (74.125.225.120): icmp_req=3 ttl=49 time=127 ms

--- www.google.ca ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2003ms

196 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using IDP MultiWAN

rtt min/avg/max/mdev = 121.528/137.298/162.739/18.160 ms

8 Execute the following commands to check the default gateway and network path.

route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 25.48.75.88 0.0.0.0 UG 0 0 0 3g-wwan 128.224.140.0 * 255.255.254.0 U 0 0 0 eth0 172.31.255.0 * 255.255.255.0 U 0 0 0 eth0 192.168.1.0 * 255.255.255.0 U 0 0 0 br-lan

tracepath -n www.google.ca 1: 25.48.75.88 2.944ms pmtu 1500 1: 10.118.23.206 1870.575ms asymm 2 1: 10.118.23.206 888.114ms asymm 2 2: 10.118.23.209 129.629ms 3: 10.118.23.22 139.424ms asymm 4 4: 10.118.20.77 129.332ms 5: 192.168.1.75 119.304ms 6: 192.168.1.21 109.287ms asymm 4 7: 24.156.157.153 111.551ms asymm 4 8: 24.156.146.38 109.364ms asymm 9 9: 24.156.157.129 111.450ms asymm 10 10: 24.156.146.153 149.412ms asymm 11 11: 24.156.144.182 145.304ms asymm 12 13: no reply The response indicates that the default gateway now uses the 3g-wwan interface — the IDP multiWAN functionality switched the primary connection from eth0 to 3g-wwan after you disconnected the eth0 interface.

9 Connect the Ethernet cable to the Cross Hill board, and wait about one minute.

10 On the target, execute the following command to confirm that the target can connect to the Internet.

ping –c 3 www.google.ca PING www.google.ca (173.194.46.56) 56(84) bytes of data. 64 bytes from ord08s10-in-f24.1e100.net (173.194.46.56): icmp_req=1 ttl=49 time=119 ms 64 bytes from ord08s10-in-f24.1e100.net (173.194.46.56): icmp_req=2 ttl=49 time=120 ms 64 bytes from ord08s10-in-f24.1e100.net (173.194.46.56): icmp_req=3 ttl=49 time=177 ms

--- www.google.ca ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2003ms rtt min/avg/max/mdev = 119.827/139.270/177.239/26.853 ms

11 Execute the following commands to check the default gateway and network path.

route Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 128.224.140.1 0.0.0.0 UG 0 0 0 eth0 128.224.140.0 * 255.255.254.0 U 0 0 0 eth0 172.31.255.0 * 255.255.255.0 U 0 0 0 eth0 192.168.1.0 * 255.255.255.0 U 0 0 0 br-lan

tracepath -n www.google.ca 1: 128.224.140.238 2.163ms pmtu 1500 1: 128.224.140.1 2.215ms 1: 128.224.140.1 2.470ms 2: 128.224.244.42 2.980ms 3: 128.224.252.1 3.884ms 4: 69.17.142.113 4.901ms 5: 69.63.253.134 7.857ms 6: 66.185.81.77 10.656ms 7: 24.156.144.182 21.345ms 8: no reply

Wind River Education Services 197 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

[...] The response indicates that now the default gateway uses the eth0 interface — the IDP multiWAN functionality switched the primary connection from 3g-wwan back to eth0 after you reconnected the eth0 interface.

This concludes the lab. Do not proceed.

198 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Working with Lua and MQTT Software

© Copyright 2014, Wind River Systems, Inc.

199 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Working with Lua and MQTT Software

Objective

In this lab, you will work with the Lua and MQ Telemetry Transport (MQTT) software contained within an IDP image. You will perform these main objectives: • work with example Lua code on the target • work with MQTT example code on the target

NOTE: This lab should take approximately 30 minutes.

Topics Covered

Before You Begin...... Working with Example Lua Code on the Target...... Working with an MQTT Server on the Target......

Before You Begin

In this lab, you will use a host computer to connect to the target. Your configuration may use either a hardware target or a simulated QEMU target. The following figure shows the lab topology.

1 Follow the instructions in the Getting Started with IDP Lab to boot the hardware target or to start a simulated target.

2 Execute the ifconfig command on both the target console and the terminal window for your host computer to determine the following information that you will need to know for the lab: • The IP address of your target: ______.______.______.______

200 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Working with Lua and MQTT Software

Through this lab, this is referred to as $TARGET_IP. • The IP address of your host computer: ______.______.______.______Through this lab, this is referred to as $HOST_IP.

Working with Example Lua Code on the Target

Wind River Intelligent Device Platform target images include the Lua language. In this section, you will run some example Lua code on the target. The target platform project for this lab contains the Lua source package. For this section, you will do the following: • expand the Lua source package • run some of the examples on the target 1 On the target change directory to /root and execute the following command to expand the Lua source tarball. The tarball is part of the IDP platform project on the host and it has been copied to the target root file system during the platform build.

# cd # tar -xvf lua-5.1.5.tar.gz

2 Change directory to Lua example sources.

# cd lua-5.1.5/test

3 On the target console, execute the following commands to run the Lua hello world example program.

# lua hello.lua Hello world, from Lua 5.1!

4 You can also compile Lua code (the default target image Lua includes the compiler). Execute the following commands to compile the Lua hello program, then run it.

# luac hello.lua # lua luac.out Hello world, from Lua 5.1!

5 The Lua source package contains several other programs that you can try. For example, execute the following command to run the application life.lua (an implementation of John Conway’s cellular automaton that simulates life).

# lua life.lua ------OO------O------OO------O-O------O------O------

Wind River Education Services 201 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

------O------O-O------O-O------O------OO------OO------Life - generation 2000 Did you see the gliders?

Working with an MQTT Server on the Target.

The Wind River Intelligent Device Platform target image includes an MQTT server. In this section, you will run some example programs on a target that uses the MQTT server. MQTT is a machine-to-machine (M2M) and Internet of Things (IoT) connectivity protocol. It was designed to provide an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations that require a small code footprint or where network bandwidth is at a premium. 1 In addition to existing serial console window, open two additional terminal windows on your host computer via Applications > System Tools > Terminal menu.

2 In first terminal window on your host computer, execute the following commands to establish an SSH link to the target and change to the sub-directory that contains the examples.

ssh root@$TARGET_IP root@targetIP's password: Last login: Mon Oct 14 01:30:41 2013 from hostIP

# cd examples # ls mqtt-client

3 On a second terminal on your host computer, repeat the previous step to establish an SSH link to the target and change to the example sub-directory.

ssh root@$TARGET_IP root@targetIP's password: Last login: Mon Oct 14 01:30:41 2013 from hostIP

# cd examples # ls mqtt-client

4 On your target serial console, execute the following command to change to the mqtt- client subdirectory and add mqtt-client directory in your search path.

# cd /root/examples/mqtt-client # export PATH=$PATH:/root/examples/mqtt-client

202 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Working with Lua and MQTT Software

5 On your target serial console, execute the following command to run the mqtt_test example Lua program. It will run as a daemon, but the output displays to your target console while the program runs.

# ./mqtt_test.lua -d localhost [mqtt_test v0.2 2012-06-01] MQTT.client:connect(): mqtt_test MQTT.client:publish(): test/1 MQTT.client:subscribe(): test/2 MQTT.client:handler() MQTT.client:parse_message_conack() MQTT.client:publish(): test/1 MQTT.client:handler() MQTT.client:parse_message_suback() MQTT.client:publish(): test/1 MQTT.client:handler() MQTT.client:publish(): test/1 MQTT.client:handler() MQTT.client:publish(): test/1 : :

6 On the first host terminal with an SSH session on the target, execute the following commands to run the mqtt_subscribe.lua example.

# cd mqtt-client # ./mqtt_subscribe.lua -d -t test/1 [mqtt_subscribe v0.2 2012-06-01] MQTT.client:connect(): mqtt_sub MQTT.client:subscribe(): test/1 MQTT.client:handler() MQTT.client:parse_message_conack() MQTT.client:parse_message_suback() MQTT.client:handler() MQTT.client:parse_message_publish() Topic: test/1, message: '*** Lua test message ***' MQTT.client:handler() MQTT.client:parse_message_publish() Topic: test/1, message: '*** Lua test message ***' : : The program mqtt_subscribe.lua (running on the target) listens to and prints everything published on the topic test/1. The program mqtt_test.lua publishes the message *** Lua test message *** every second. That is why the mqtt_subscribe.lua program displays that message — it simply attaches to the topic test/1 and prints anything that is placed there.

7 Now on the second host terminal, execute the following command to run the program mqtt_publish.lua to publish a different message on topic test/1. This program publishes the message given to it (defined by the argument –m and the string that follows within quotation marks) on the topic it is told to use. You must put the message onto topic test/1 so the mqtt_subscribe.lua program (currently running) displays it.

# cd mqtt-client # ./mqtt_publish.lua -d -t test/1 -m "****************" [mqtt_publish v0.2 2012-06-01] MQTT.client:connect(): mqtt_pub MQTT.client:publish(): test/1 MQTT.client:destroy() MQTT.client:disconnect()

8 Switch to the first host terminal (which is running mqtt_subscribe.lua) and confirm that the output changes to the new message (****************).

Wind River Education Services 203 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

9 On the same host terminal (where the mqtt_subscribe.lua program is running), press CTRL+C to kill the program, then execute the command exit to exit the shell and this SSH session.

MQTT.client:handler() MQTT.client:parse_message_publish() Topic: test/1, message: '*** Lua test message ***' MQTT.client:handler() MQTT.client:parse_message_publish() Topic: test/1, message: 'Test message' MQTT.client:handler() MQTT.client:parse_message_publish() Topic: test/1, message: '*** Lua test message ***' ^C/usr/bin/lua: ./mqtt_subscribe.lua:87: interrupted! stack traceback: [C]: in function 'sleep' ./mqtt_subscribe.lua:87: in main chunk [C]: ?

# exit logout Connection to targetIP closed.

10 On the target console, execute the following command to send the message quit on topic test/2 to the mqtt_test.lua program.

# ./mqtt_publish.lua -d -t test/2 -m "quit" [mqtt_publish v0.2 2012-06-01] MQTT.client:connect(): mqtt_pub MQTT.client:publish(): test/2 MQTT.client:destroy() MQTT.client:disconnect() The target output stops when the program mqtt_test.lua publishes to topic test/2.

11 On the second host terminal, execute the following commands to exit from the SSH session then exit from the terminal window.

# exit logout Connection to targetIP closed.

exit

This concludes the lab. Do not proceed.

204 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using OpenJDK

© Copyright 2014, Wind River Systems, Inc.

205 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Using OpenJDK

Objective

In this lab you will create and add a Wind River Linux package that uses OpenJDK components on your IDP target.

NOTE: This lab should take approximately 30 minutes.

Overview

In this lab you will build a trivial Java program, package it, include it into your target filesystem and finally run the program on your IDP target. You will complete the following tasks: • create a Java program • use the Wind River Linux build system to create a package for this program • rebuild your target file system, incorporating this package • boot your target with the new file system • run the program on the target

Topics Covered

Creating the Java Program...... Creating the HelloWorld Package...... Incorporating the Package into the File System...... Building Your New Package...... Rebuilding Your Target File System...... Booting Your Target with the New File System...... Running the Program on Your Target......

Creating the Java Program

In this section you will create the simple Java program HelloWorld, which you will later package, build, and run on your target.

206 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using OpenJDK

NOTE: You must perform extensive typing in this lab. A complete solution is available in the directory /Labs/OpenJDK/Answers — at any point you can review or copy completed files provided in this directory.

1 On the host computer, create a directory in which to create your Java project.

mkdir -p /Labs/HelloWorld

2 Execute the following commands to create the directory src as a sub-directory of the directory /Labs/HelloWorld. (This is the default location for Java source used by standard build systems.)

mkdir -p /Labs/HelloWorld/src cd /Labs/HelloWorld/src

3 Create the source file /Labs/HelloWorld/src/HelloWorld.java for a simple Java HelloWorld program, with the following content.

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } }

4 Change directory one level up to the directory /Labs/HelloWorld and create the file / Labs/HelloWorld/build.xml with the following content, to provide build instructions for your Java program.

5 Execute the following commands to create a tarball of the source named HelloWorld.tar.gz. You must be one level higher in the directory structure to create the file.

cd /Labs tar czvf HelloWorld.tar.gz HelloWorld HelloWorld/ HelloWorld/build.xml HelloWorld/src/ HelloWorld/src/HelloWorld.java

Wind River Education Services 207 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

6 Execute the following commands to verify that your files are in the correct locations.

pwd /Labs ls -R HelloWorld HelloWorld: build.xml src

HelloWorld/src: HelloWorld.java

ls *.gz HelloWorld.tar.gz

Creating the HelloWorld Package

You must create or modify a layer to package the program. In this section you will create a new layer in your home directory (/home/wruser). 1 On the host computer, execute the following commands to create the directory structure layers/myJavaLayer in your home directory, then change to the new directory.

mkdir -p /home/wruser/layers/myJavaLayer cd /home/wruser/layers/myJavaLayer

2 In the directory myJavaLayer, execute the following command to create the additional subdirectories conf, downloads, recipes-core, and templates.

mkdir {conf,downloads,recipes-core,templates}

3 In the directory /home/wruser/layers/myJavaLayer/conf, create the file layer.conf with the following content. This is the configuration file for the layer. BitBake defines the name of the file and the format of the content allowed in it. Alternatively, you can use the file $TARGET_BASE/layers/local/conf/layer.conf provided with the lab.

# We have a conf and classes directory, add to BBPATH BBPATH := "${LAYERDIR}:${BBPATH}" # We have a packages directory, add to BBFILES BBFILES := "${BBFILES} ${LAYERDIR}/recipes-*/*/*.bb \ ${LAYERDIR}/recipes-*/*/*.bbappend \ ${LAYERDIR}/classes/*.bbclass" BBFILE_COLLECTIONS += "myjavalayer" BBFILE_PATTERN_myjavalayer := "^${LAYERDIR}/" BBFILE_PRIORITY_myjavalayer = "10" # We have a pre-populated downloads directory, add to PREMIRRORS PREMIRRORS_append := " \ git://.*/.* file://${LAYERDIR}/downloads/ \n \ svn://.*/.* file://${LAYERDIR}/downloads/ \n \ ftp://.*/.* file://${LAYERDIR}/downloads/ \n \ http://.*/.* file://${LAYERDIR}/downloads/ \n \ https://.*/.* file://${LAYERDIR}/downloads/ \n"

4 Execute the following command to copy the file /Labs/HelloWorld.tar.gz that you created to the directory /home/wruser/layers/myJavaLayer/downloads.

cp /Labs/HelloWorld.tar.gz /home/wruser/layers/myJavaLayer/downloads

208 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using OpenJDK

5 Execute the following commands to create the directory helloworld under /home/ wruser/layers/myJavaLayer/recipes-core.

mkdir -p /home/wruser/layers/myJavaLayer/recipes-core/helloworld cd /home/wruser/layers/myJavaLayer/recipes-core/helloworld

6 Create the BitBake recipe file /home/wruser/layers/myJavaLayer /recipes-core/ helloworld/helloworld.bb with the following content. This file contains the instructions for tasks that the build system must for your program: unpack it, patch it (if necessary — in this lab there are no patches,) compile it, and package it into RPMs. This recipe has some special steps to replace the default content.

NOTE: You can copy the file $TARGET_BASE/layers/local/recipes-sample / hello/hello_1.0.bb to /home/wruser/layers/myJavaLayer/recipes-core/ helloworld, then edit it to match the following code snippet — this will reduce your coding work.

DESCRIPTION = "This package contains Hello World sample program for openjdk and ant" LICENSE = "GPL-2.0" LIC_FILES_CHKSUM = "file://src/HelloWorld.java;md5= 52de74ec20ab6a08ed9fd9651e1fe71f" SRC_URI = "file:///home/wruser/layers/myJavaLayer/downloads/HelloWorld.tar.gz"

S = "${WORKDIR}/HelloWorld" DEPENDS +="ant-native"

PACKAGES = "${PN}"

FILES_${PN} += "/usr/share/java" RDEPENDS_${PN} = "openjdk-bin"

do_compile() { ant clean ant compile ant jar ant run }

JARFILENAME="HelloWorld.jar"

do_install() { install -d ${D}/usr/share/java install -m 0755 ${S}/build/jar/HelloWorld.jar ${D}/usr/share/java }

SRC_URI[md5sum] = "b7db6487984c47b5498707344febe83c" SRC_URI[sha256sum] = "4e1c6fd9049c494b4606a8de02031a4a 94542484ad63f9f02d8b9f82ff74c359"

NOTE: Ensure that the lines containing the following strings are single lines, with no breaks even if they extend beyond the margins. DESCRIPTION LIC_FILES_CHKSUM SRC_URI install SRC_URI[sha256sum]

Wind River Education Services 209 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

7 You must create your own values for the lines containing the strings SRC_URI md5sum and SRC_URI sha256sums , based on the files you created. The values shown above are for the content as originally developed. If you alter the white spaces in the file, the checksums will be different. Execute the following commands to find the correct values, then edit your file if necessary.

md5sum /Labs/HelloWorld/src/HelloWorld.java 52de74ec20ab6a08ed9fd9651e1fe71f /Labs/HelloWorld/src/HelloWorld.java md5sum /home/wruser/layers/myJavaLayer/downloads/HelloWorld.tar.gz b7db6487984c47b5498707344febe83c /home/wruser/layers/myJavaLayer/downloads/ HelloWorld.tar.gz sha256sum /home/wruser/layers/myJavaLayer/downloads/HelloWorld.tar.gz 4e1c6fd9049c494b4606a8de02031a4a94542484ad63f9f02d8b9f82ff74c359 /home/wruser/layers/ myJavaLayer/downloads/HelloWorld.tar.gz

8 Execute the following commands to create the template configuration file (template.conf) in the directory templates/feature/helloworld.

cd /home/wruser/layers/myJavaLayer/templates mkdir -p feature/helloworld cd feature/helloworld echo IMAGE_INSTALL_append += \"helloworld\" > template.conf cat template.conf IMAGE_INSTALL_append += “helloworld”

9 Execute the following commands to change to the directory layers and verify that you have all of the files and directories in the correct locations.

cd $HOME ls -R layers layers: myJavaLayer

layers/myJavaLayer: conf downloads recipes-core templates

layers/myJavaLayer/conf: layer.conf

layers/myJavaLayer/downloads: HelloWorld.tar.gz

layers/myJavaLayer/recipes-core: helloworld

layers/myJavaLayer/recipes-core/helloworld: helloworld.bb

layers/myJavaLayer/templates: feature

layers/myJavaLayer/templates/feature: helloworld

layers/myJavaLayer/templates/feature/helloworld: template.conf

Incorporating the Package into the File System

In this section you will update the file bblayers.conf so the build system implements the changes you did in the previous section when it builds the project.

210 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using OpenJDK

1 Modify the file $TARGET_BASE/bitbake_build/conf/bblayers.conf. This configuration file tells the build system where to look for content when it builds the project. Before the line that reads ${WRL_TOP_BUILD_DIR}/layers/local \, add the line /home/wruser/ layers/myJavaLayer \.

LCONF_VERSION = "5"

BBPATH = "${TOPDIR}" BBFILES ?= "" WRL_TOP_BUILD_DIR ?= "${TOPDIR}/.." # resolve WRL_TOP_BUILD_DIR immediately with a canonical path # to satisfy the bitbake logger WRL_TOP_BUILD_DIR := "${@os.path.realpath(d.getVar('WRL_TOP_BUILD_DIR', True))}"

BBLAYERS = " \ ${WRL_TOP_BUILD_DIR}/layers/wrlinux \ ${WRL_TOP_BUILD_DIR}/layers/wrlcompat \ ${WRL_TOP_BUILD_DIR}/layers/wr-toolchain \ ${WRL_TOP_BUILD_DIR}/layers/oe-core/meta \ ${WRL_TOP_BUILD_DIR}/layers/oe-core-dl \ ${WRL_TOP_BUILD_DIR}/layers/meta-downloads \ ${WRL_TOP_BUILD_DIR}/layers/wr-kernel \ ${WRL_TOP_BUILD_DIR}/layers/wr-bsps/intel-quark \ ${WRL_TOP_BUILD_DIR}/layers/wr-base \ ${WRL_TOP_BUILD_DIR}/layers/wr-features \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-profile \ ${WRL_TOP_BUILD_DIR}/layers/wr-tools-debug \ ${WRL_TOP_BUILD_DIR}/layers/meta-networking \ ${WRL_TOP_BUILD_DIR}/layers/meta-webserver \ ${WRL_TOP_BUILD_DIR}/layers/wr-prebuilts \ ${WRL_TOP_BUILD_DIR}/layers/meta-java \ ${WRL_TOP_BUILD_DIR}/layers/wr-idp/meta-java-dl \ ${WRL_TOP_BUILD_DIR}/layers/wr-idp/wr-idp-devkit \ ${WRL_TOP_BUILD_DIR}/layers/wr-idp/wr-srm \ ${WRL_TOP_BUILD_DIR}/layers/wr-idp/wr-exegin-zigbee-ia \ /home/wruser/layers/myJavaLayer \ ${WRL_TOP_BUILD_DIR}/layers/local \ "

Building Your New Package

In this section you will build the package to include in your root file system. Build this separate from building the whole file system, as it is easier to see errors. 1 Change to the platform project directory, then execute the following command to build the specific package.

make -C $TARGET_BASE/build helloworld make: Entering directory `/Labs/target/build' [...] make: Leaving directory `/Labs/target/build'

NOTE: You must resolve any errors before you continue.

2 Execute the following command to add this new package into the build for your file system.

make -C $TARGET_BASE/build helloworld.addpkg

make: Entering directory `/Labs/target/build' ...

Wind River Education Services 211 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Loading cache: 100% |#######################################################| ETA: 00:00:00 Loaded 1627 entries from dependency cache. Parsing recipes: 100% |#####################################################| Time: 00:00:01 Parsing of 1262 .bb files complete (1259 cached, 3 parsed). 1629 targets, 51 skipped, 6 masked, 0 errors. NOTE: Resolving any missing task queue dependencies NOTE: Preparing runqueue NOTE: PN build list saved to 'pn-buildlist' NOTE: PN dependencies saved to 'pn-depends.dot' NOTE: Package dependencies saved to 'package-depends.dot' NOTE: Task dependencies saved to 'task-depends.dot' === ADDED helloworld to ../layers/local/recipes-img/images/wrlinux-image-glibc-idp.bb === NOTE: It is possible to generate a non-buildable configuration with the addpkg rule, in which case you can use the rmpkg rule to remove what you added and try a different configuration. make: Leaving directory `/Labs/target/build'

Rebuilding Your Target File System

In this section you will rebuild the target file system. This step is simple, though it takes quite some time compared to the previous steps. 1 Execute the following command to rebuild the file system so it incorporates the changes you made in the previous sections. This step simply collects all of the relevant packages and creates the root file system from them, but it can take up to about 10 minutes depending on the system you use.

make -C $TARGET_BASE ... make: Leaving directory `/Labs/target/build'

Booting Your Target with the New File System

In this section you will put the file system in place so your target can use it. 1 Follow the instructions in the Getting Started with IDP Lab to boot the hardware target or to start a simulated target..

Running the Program on Your Target

1 Log on to the target, then execute the following command to run the Java program on the target.

$ java –jar /usr/share/java/HelloWorld.jar

This concludes the lab. Do not proceed.

212 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications

© Copyright 2014, Wind River Systems, Inc.

213 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Integrating Python Applications

Objective

In this lab you will integrate third-party software components written in Python into Wind River Intelligent Device Platform.

NOTE: This lab should take approximately 45 minutes.

Overview

Wind River Intelligent Device Platform comes with hundreds of validated software packages that are ready to use. If you need a software package that is not included, or if you must integrate an application being developed in-house, you must integrate the package into the Wind River Intelligent Device Platform build system and cross-compile it along with the rest of your platform software. A properly integrated package makes it easy to include the package into other projects as well. This lab uses a simple Python application as a way to introduce the concepts behind integrating a Python application. The application is a phone book that is listed from a Telnet session. The application supports multiple simultaneous Telnet sessions.

The Packaging Workflow

Packaging a Python application for the Wind River Intelligent Device Platform is not similar to the basic Wind River Linux packaging workflow. In this lab you will execute the following workflow (which includes a few Python-specific steps): • Add the file setup.py to the application. This lets the Python setuptools utilities manage the application. You must ensure that setup.py works properly and that you can install your Python application on a development workstation. The setuptools utilities are Python libraries that are not connected with your Wind River Intelligent Device Platform installation. You can use them to package native Python applications for your Wind River Intelligent Device Platform project. • Select a name for the application. In this lab you will use the name phonebook. • Select the build layer where you will maintain the new package. In this lab you will maintain the phonebook application in the local layer. • Define the license to associate with the application. In this lab you will use the GPLv3 license. • Make the application source code and support files available to the build system. In this lab you will use a URI pointing to an archive file in the directory /Labs/python • Build the directory infrastructure inside the layer to tell BitBake about the new package, and add all the support files.

214 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications

• Ensure the application recipe file tells BitBake that it can manage the application with the setuptools utilities. • Test the build and fix any problems. Repeat this workflow until your new package works as expected.

About the Application Archive

The archive file for the application is /Labs/python/phonebook 1.0.tar.gz. The following figure shows the content of the tar file.

phonebook-1.0 |-- COPYING |-- phonebook |-- README |-- setup.py |-- tslib |-- __init__.py |-- db.py `-- server.py

About Setup.py

The following is the sample file setup.py provided in the tar file:

from setuptools import setup

setup(name='phonebook', version='1.0', description='Python Phonebook Application', long_description=open('README').read(), author='Wind River Systems', author_email='[email protected]', url='http://education.windriver.com', classifiers=[ 'Development Status :: Production', 'Environment :: Console', 'License :: OSI Approved :: GPLv3', ], packages=['tslib'], scripts=['phonebook'], data_files = [ ('/usr/share/doc/phonebook', ['README'])] ) It is beyond the scope of this lab to go into the details of this file, but most of its content is self-explanatory. However, it is worth adding a few words about the three last parameters passed to the setup( ) function. • packages — This parameter identifies the Python packages included in the application. A Python package is a directory populated with a special file named __init__.py and zero or more Python modules (files with the extension .py). In the application phonebook, the directory tslib is the only Python package. BitBake installs the Python packages in the standard Python library for your target platform. In this lab this library is in /usr/lib/python2.7/site-packages. • scripts — This parameter identifies standalone executable Python files that you want to be installed as commands in the target. These scripts usually import the Python

Wind River Education Services 215 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

packages defined by the application. In this lab the only script is the Python program phonebook. BitBake installs the scripts in the directory /usr/bin in the target. • data_files — This parameter lists all auxiliary files bundled with the application and specifies their location in the target system. In this lab the only auxiliary file is the README file which is installed in the directory /usr/share/doc/phonebook in the target. The sample file setup.py provided in this lab is minimal but it can become as complex as needed to address the specific needs of your application. Please refer to the standard Python documentation resources for further details.

Topics Covered

Creating the Package Structure...... Building the Package...... Running the Phonebook Application......

Creating the Package Structure

1 Open a command-line terminal and navigate to the directory containing the prebuilt Wind River Intelligent Device Platform project.

cd $TARGET_BASE

2 Execute the following command to add the directory structure to your platform project. Note that the local layer already has several other directories and files on it — do not touch them.

mkdir -p layers/local/recipes-applications/phonebook The directory recipes-applications will contain your application packages. You can use any name you like, but it must follow the pattern recipes-* in order to be recognized as a directory containing recipes. The subdirectory phonebook is where you will maintain the application. It will host the recipe and other support files that you may need in the future.

3 In the layers/local/recipes-applications/phonebook directory, create the recipe file phonebook_1.0.bb with the following content. This file is also available in the directory / Labs/python so you can copy it.

cp /Labs/python/phonebook_1.0.bb layers/local/recipes-applications/phonebook

SUMMARY = "Phone Book Application" DESCRIPTION = "Sample Python code for a phone book" HOMEPAGE = "http://education.windriver.com" LICENSE = "GPLv3" LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

216 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications

PR = "r1"

RDEPENDS_${PN} = "python-core python-io python-misc \ python-fcntl python-sqlite3 \ python-textutils netcat"

inherit setuptools

SRC_URI = "file:///Labs/python/phonebook-1.0.tar.gz" SRC_URI[md5sum] = "6ab56a2ec66f9839daeead13702308d5" Understanding the Recipe • SUMMARY, DESCRIPTION, HOMEPAGE — These are descriptive variables that you can safely omit. They provide information about the recipe, and some tools may use them — you should always define these variables. • LICENSE — This variable defines the license to apply to the package. Most well- known open source licenses (such as GPLv2, LGPLv2.1, BSD, MIT, and others) are predefined. • LIC_FILES_CHKSUM — This variable identifies the file containing the license text, as well as a checksum value to validate that the license text is exactly as expected. This enable the build system to verify that the license text has not changed since the recipe was written, which may possibly invalidate the license. • PR — This represents the recipe version. The default value is r0 — for clarity, make this variable explicit in the recipe. • RDEPENDS_{PN} — This variable expands to RDEPENDS_phonebook. The expanded expression tells BitBake about the run-time dependencies associated with the application phonebook. BitBake installs run-time dependencies into the target image, but not necessarily at build time. In this case, the run-time dependencies are a few Python modules and netcat. • inherit setuptools — This instruction tells BitBake to use the Python setuptools class to determine how the application phonebook is organized and how to install it on the target root file system. • SRC_URI — This variable lists the source files that make up the package. This lab uses the URL prefix file:// but you can use other values such us http://, git://, and ftp://. • SRC_URI[md5sum] and SRC_URI[sha256sum] — These variables provide the checksum values of the source file. BitBake uses these values to verify the integrity of the source archive.

Building the Package

1 Execute the following command to build the package. Note that BitBake automatically builds other packages needed to run the application. In particular, you may see that BitBake builds the Python interpreter.

make -C build phonebook

Wind River Education Services 217 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

2 The previous step built the phonebook package, but merely building a package does not automatically include it into your target image. Execute the following command to add the package to the target image.

make -C build phonebook.addpkg

3 Execute the following command to build the project.

make

4 After the build finishes, the directory export/dist contains a copy of the target root file system. Execute the following command to verify that the Python script phonebook is part of the new target image.

ls export/dist/usr/bin/phonebook export/dist/usr/bin/phonebook

5 Execute the following command to verify that the phonebook libraries are part of the new target image.

ls export/dist/usr/lib/python2.7/site-packages/tslib db.py __init__.py server.py ...

Running the Phonebook Application

1 Before you run the application you should understand how it works. Execute the following command to enter a development shell in the directory containing the package source, then examine the README file accompanying the phonebook application. In summary, the file says that you must run two programs: the phonebook server (which provides the phonebook entries) and a client program to query the server.

make -C build phonebook.devshell After you examine the README file, execute the command exit to return to the command-line shell.

2 Follow the instructions in the Getting Started with IDP Lab to boot the hardware target or to start a simulated target.

3 On the target, execute the following command to start the phonebook server.

phonebook & Listening on ('127.0.0.1', 41215) The character & runs the server in the background. Wait until the response tells you the IP address and port number on which the server is listening (in this case, the IP address 127.0.0.1 and port 41215).

218 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating Python Applications

4 Execute the following command to start the netcat client. Use the port number shown in step 3 on page 6. Remember that the BitBake recipe includes the package netcat as a run-time dependency for the application.

nc 127.0.0.1 41215

5 Now you can interact directly with the phonebook server. Explore options 1 and 2. When done, selection option 3 to exit the client.

6 Execute the following command to bring the server to the foreground.

fg %1 phonebook

7 Press CTRL+C to exit the server.

This concludes the lab. Do not proceed.

Wind River Education Services 219 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

220 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating SQLite3 Applications

© Copyright 2014, Wind River Systems, Inc.

221 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Integrating SQLite3 Applications

Objective

In this lab you will integrate an SQLite3 database into Wind River Intelligent Device Platform and use Python scripts to access it.

NOTE: This lab should take approximately 45 minutes.

Overview

In this lab you will develop a simple Python application that imports an SQLite3 library. IDP includes the SQLite3 library, cross complied on the host and installed on the target. You will create a Python- and SQLite3-based application package, then use a BitBake recipe to the build application package on the host and include it in the IDP target file system. You will run the application on the target and execute several SQLite operations (like create, insert, select, and delete).

The Packaging Workflow

Packaging an SQLite3 application for the Wind River Intelligent Device Platform is similar to the basic Wind River Linux packaging workflow. in this lab you will execute the following workflow (which includes a few Python-specific steps): • Add the file setup.py to the application. This lets the Python setuptools utilities manage the application. You must ensure that setup.py works properly, and that you can install your Python application on a development workstation. The setuptools utilities are Python libraries that are not connected with your Wind River Intelligent Device Platform installation that you can use to package native Python applications for your Wind River Intelligent Device Platform project. • Select a name for the application. In this lab you will use the name sqlite3app. • Select the build layer where you will maintain the new package. In this lab you will maintain the sqlite3app application in the local layer. • Define the license to associate with the application. In this lab you will use the GPLv3 license. • Make the application source code and support files available to the build system. In this lab you will use a URI pointing to an archive file in the directory /Labs/sqlite3 • Build the directory infrastructure inside the layer to tell BitBake about the new package, and add all the support files.

222 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating SQLite3 Applications

• Ensure the application recipe file tells BitBake that it can manage the application with the setuptools utilities. • Test the build and fix any problems. Repeat this workflow until your new package works as expected.

About the Application Archive

The archive file for the application is /Labs/sqlite3/sqlite3app 1.0.tar.gz. The following figure shows the content of the tar file.

sqlite3app-1.0 |-- COPYING |-- sqlite3app |-- README |-- setup.py |-- tslib |-- __init__.py `-- sqlcommands.py

About Setup.py

The following is the sample file setup.py provided in the tar file:

from setuptools import setup

setup(name='sqlite3app', version='1.0', description='SQLite3 Python Application', long_description=open('README').read(), author='Wind River Systems', author_email='[email protected]', url='http://education.windriver.com', classifiers=[ 'Development Status :: Production', 'Environment :: Console', 'License :: OSI Approved :: GPLv3', ], packages=['tslib'], scripts=['sqlite3app'], data_files = [ ('/usr/share/doc/sqlite3app', ['README'])] ) It is beyond the scope of this lab to go into the details of this file, but most of its content is self-explanatory. However, it is worth adding a few words about the three last parameters passed to the setup( ) function. • packages — This parameter identifies the Python packages included in the application. A Python package is a directory populated with a special file named __init__.py and zero or more Python modules (files with the extension .py). In the application sqlite3app, the directory tslib is the only Python package. BitBake installs the Python packages in the standard Python library for your target platform. In this lab this library is in /usr/lib/python2.7/site-packages. • scripts — This parameter identifies standalone executable Python files that you want to be installed as commands in the target. These scripts usually import the Python packages defined by the application. In this lab the only script is the Python program sqlite3app.

Wind River Education Services 223 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

BitBake installs the scripts in the directory /usr/bin in the target. • data_files — This parameter lists all auxiliary files bundled with the application and specifies their location in the target system. In this lab the only auxiliary file is the README file which is installed in the directory /usr/share/doc/sqlite3app in the target. The sample file setup.py provided in this lab is minimal but it can become as complex as needed to address the specific needs of your application. Please refer to the standard Python documentation resources for further details.

Topics Covered

Creating the Package Structure...... Building the Package...... Running the SQLite3 Application......

Creating the Package Structure

1 Open a command-line terminal and navigate to the directory containing the prebuilt Wind River Intelligent Device Platform project.

cd $TARGET_BASE

2 Execute the following command to add the directory structure to your platform project. Note that the local layer already has several other directories and files on it — do not touch them.

mkdir -p layers/local/recipes-applications/sqlite3app The directory recipes-applications will contain your application packages. You can use any name you like, but it must follow the pattern recipes-* in order to be recognized as a directory containing recipes. The subdirectory sqlite3app is where you will maintain the application. It will host the recipe and other support files that you may need in the future.

3 In the layers/local/recipes-applications/sqlite3app directory, create the recipe file sqlite3app_1.0.bb with the following content.

SUMMARY = "SQLite Application" DESCRIPTION = "Sample SQLite3 Python code" HOMEPAGE = "http://education.windriver.com" LICENSE = "GPLv3" LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

PR = "r1"

RDEPENDS_${PN} = "python-core python-io python-misc \ python-fcntl python-sqlite3 \ python-textutils"

inherit setuptools

224 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating SQLite3 Applications

SRC_URI = "file:///Labs/sqlite3/sqlite3app-1.0.tar.gz" SRC_URI[md5sum] = "57797abc9d201e9f795b8b9d0b6d0dc9" This file is also available in the directory /Labs/sqlite3 — execute the following command if you wish to copy it.

cp /Labs/sqlite3/sqlite3app_1.0.bb layers/local/recipes-applications/sqlite3app Understanding the Recipe The following provides short descriptions of the variables in the recipe file that you just created: • SUMMARY, DESCRIPTION, HOMEPAGE — These are descriptive variables that you can safely omit. They provide information about the recipe, and some tools may use them — you should always define these variables. • LICENSE — This variable defines the license to apply to the package. Most well- known open source licenses (such as GPLv2, LGPLv2.1, BSD, MIT, and others) are predefined. • LIC_FILES_CHKSUM — This variable identifies the file containing the license text, as well as a checksum value to validate that the license text is exactly as expected. This enable the build system to verify that the license text has not changed since the recipe was written, which may possibly invalidate the license. • PR — This represents the recipe version. The default value is r0 — for clarity, make this variable explicit in the recipe. • RDEPENDS_{PN} — This variable expands to RDEPENDS_sqlite3app. The expanded expression tells BitBake about the run-time dependencies associated with the application sqlite3app. BitBake installs run-time dependencies into the target image, but not necessarily at build time. • inherit setuptools — This instruction tells BitBake to use the Python setuptools class to determine how the application sqlite3app is organized and how to install it on the target root file system. • SRC_URI — This variable lists the source files that make up the package. This lab uses the URL prefix file:// but you can use other values such us http://, git://, and ftp://. • SRC_URI[md5sum] and SRC_URI[sha256sum] — These variables provide the checksum values of the source file. BitBake uses these values to verify the integrity of the source archive. Understanding the Source Package This section describes source code added for this lab. The lab source is self-explanatory — you can extract the source and inspect the code. BitBake copies the ASCII, executable, Python file sqlite3app to the directory /usr/ bin when it builds the target file system. This provides the user interface to perform SQL operations. The source code imports the SQL command library defined in tslib/ sqlcommands.py, and displays the options when you run the application sqlite3app.

MENU=””

======Select an option

Wind River Education Services 225 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

1- Create table 2- Insert data 3- Delete data 4- Display data 5- Exit The library tlib/sqlcommands.py defines the set of functions to execute SQL commands described below: • The function sqlite3.connect(“Athletes.db”) defines the Creating Athletes database. • The function iterator.execute("CREATE TABLE %s (Name, Sports, Championship, year)" % (table) ) creates the user-defined table Athletes with the data triple Name, Sports, and Championship, Year (for example, “Tom Brady, NFL, Super Bowl, 2003”). • The function iterator.execute("SELECT * from %s" %(tableName)), executes a command to read all the data from the data table.

Building the Package

1 Execute the following command to build the package. Note that BitBake automatically builds other packages needed to run the application. In particular, you may see that BitBake builds the Python interpreter. This may take some time.

make -C build sqlite3app

2 The previous step built the sqlite3app package, but merely building a package does not automatically include it into your target image. Execute the following command to add the package to the target image.

make -C build sqlite3app.addpkg

3 Execute the following command to build the project.

make

4 After the build finishes, the directory export/dist contains a copy of the target root file system. Execute the following command to verify that the Python script sqlite3app is part of the new target image.

ls export/dist/usr/bin/sqlite3app export/dist/usr/bin/sqlite3app

5 Execute the following command to verify that the sqlite3app libraries are part of the new target image.

ls export/dist/usr/lib/python2.7/site-packages/tslib db.py __init__.py server.py sqlcommands.py ...

Running the SQLite3 Application

226 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Integrating SQLite3 Applications

1 Before you run the application you should understand how it works.Execute the following command to enter a development shell in the directory containing the package source, then examine the README file accompanying the sqlite3app application.

make -C build sqlite3app.devshell After you examine the README file, execute the command exit to return to the command-line shell.

2 Follow the instructions in the Getting Started with IDP Lab to boot the hardware target or to start a simulated target.

3 On the target, execute the following command to start the sqlite3app application.

sqlite3app Select an option: 1- Create table 2- Insert data 3- Delete data 4- Modify data 5-Exit

option:

4 Enter 5 to exit the application, or on the keyboard press CTRL+C to exit the server.

This concludes the lab. Do not proceed.

Wind River Education Services 227 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

228 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using grsecurity

© Copyright 2014, Wind River Systems, Inc.

229 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Using grsecurity

Objective

In this lab you will use various grsecurity features provided with Wind River Linux.

NOTE: This lab should take approximately 20 minutes.

NOTE: This lab runs only on QEMU simulated target.

Overview

The grsecurity components included in the Wind River Linux platform are a set of open source patches applied on the Linux kernel. It uses the PaX component to randomize memory addresses and provide execution control on the stack and the heap, and can also implement role-based access control (RBAC). In this lab, you will perform the following tasks: • enable and disable grsecurity • enable learning mode • define role-based access control (RBAC) for the ssh and dmesg commands • use PaX to control various flags for the application data segments

Topics Covered

Before You Begin...... Enabling the grsecurity Administration Tool...... Enabling RBAC...... Writing an RBAC Rule for the “Service Denied” Command...... Writing an RBAC Rule for SSH...... Working with PaX......

Before You Begin

In this lab, you will use a host computer to connect to the target by using the network TAP. The following figure shows the network configuration with QEMU-KVM target.

230 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using grsecurity

1 To start QEMU-KVM target, execute the following commands.

cd /Labs/IDPGettingStartedLab ./startqemu Select the proper number to start the grsecurity enabled QEMU target

2 Once the target boots, execute the following commands to log in as the user root (when prompted enter the password root), then set the target IP address.

Wind River Linux 5.0.1.12 WR-IntelligentDevice console

WR-IntelligentDevice login:root Password: root@WR-IntelligentDevice:~# ifconfig eth0 10.1.1.10/24 up root@WR-IntelligentDevice:~#

3 Verify IP assigments. Execute the ifconfig command on both the target console and the terminal window on your host computer to determine the following information that you will need to know for the lab: • The IP address of your target: ______.______.______.______Through this lab, this is referred to as $TARGET_IP. • The Network TAP0 address of your host computer: ______.______.______.______Through this lab, this is referred to as $HOST_TAP_IP.

Wind River Education Services 231 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

Enabling the grsecurity Administration Tool

In this section you will configure the grsecurity administration tool (gradm), then use it to construct default rules and create a simple rule. 1 The first time you boot the system, you must set a password for the grsecurity gradm user role shutdown. Execute the following command to set the password to enable and disable grsecurity. When prompted for a password, use windriver for this lab.

gradm -P shutdown password:

2 Execute the following commands to verify that RBAC is disabled (required during learning mode), then enable learning mode and create a new log file called learning.logs.

NOTE: Do not interrupt the gradm command while grsecurity is learning policy. Ensure that each command executes completely and that the prompt displays before you execute another gradm command.

gradm -S The RBAC is currently disabled

gradm -F -L /etc/grsec/learning.logs [ 282.951351] grsec: (default:D:/sbin/gradm) grsecurity 2.9.1 RBAC system loaded by /sbin/gradm[gradm:5194] uid/euid:0/0 gid/egid:0/0, parent /bin/bash[sh:1615] uid/ euid:0/0 gid/egid:0/0

3 Execute the following commands to learn the policy.

ls bin examples lua-5.1.5.tar.gz

pwd /root

4 Execute the following commands to disable RBAC and store the newly learned policy in the file learning.roles. Use grSecurty password (‘windriver’).

gradm -D password: [ 173.194582] grsec: shutdown auth success for /sbin/gradm[gradm:5117] uid/euid:0/0 gid/egid:0/0, parent /bin/bash[sh:1549] uid/euid:0/0 gid/egid:0/0

gradm -F -L /etc/grsec/learning.logs -O /etc/grsec/learning.roles

learning.roles Beginning full learning 1st pass...done. Beginning full learning role reduction...done. Beginning full learning 2nd pass...done. Beginning full learning subject reduction for user root...done. Beginning full learning object reduction for subject /...done. Beginning full learning object reduction for subject /bin/sed.sed...done. Beginning full learning object reduction for subject /sbin/ifconfig.net-tools...done. Beginning full learning object reduction for subject /usr/bin/setfattr...done. Full learning complete.

232 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using grsecurity

5 Execute the following commands to back up the default policy file (to restore later if you encounter problems), then replace the default policy file (/etc/grsec/policy) with the new file learning.roles (which includes the roles and policy files for your system).

cp /etc/grsec/policy /etc/grsec/policy.bak cp /etc/grsec/learning.roles /etc/grsec/policy

Enabling RBAC

In this section you will enable role-based access control (RBAC) in grsecurity and verify a standard message that displays when grsecurity denies a user access to a command. 1 Execute the following command to enable RBAC.

gradm -E [82997.897283] grsec: (root:U:/sbin/gradm) grsecurity 2.9.1 RBAC system loaded by / sbin/gradm[gradm:13814] uid/euid:0/0 gid/egid:0/0, parent /bin/bash[sh:9030] uid/ euid:0/0 gid/egid:0/0

2 Execute the following command to display the kernel message buffer.

dmesg 2596.394951] grsec: (root:U:/) use of CAP_SYSLOG denied for /bin/dmesg.util- linux[dmesg:7805] uid/euid:0/0 gid/egid:0/0, parent /bin/bash[sh:9030] uid/euid:0/0 gid/egid:0/0 The response indicates that grsecurity enforced a policy to prevent the dmesg command from executing.

Writing an RBAC Rule for the “Service Denied” Command

In this section you will define rules for the role root to provide access to the dmesg command. 1 Execute the following command to disable grsecurity before you edit the policy file. Enter windriver when prompted for the password.

gradm -D password:

2 Execute the following command to display the differences between the default grsecurity policy file (/etc/grsec/policy_lab) and a preconfigured file (/etc/grsec/ policy_dmesg) that allows user access to the dmesg command. Note the lines that start with a + sign — they represent added code that implements dmesg access.

diff -uNar /etc/grsec/policy_lab /etc/grsec/policy_dmesg --- /etc/grsec/policy_lab 2014-04-11 10:27:42.329273569 -0400 +++ /etc/grsec/policy_dmesg 2014-04-11 10:29:05.773271478 -0400 @@ -63,10 +63,25 @@ /sbin h /sbin/gradm x /usr h + /bin/bash x + /bin/dmesg.util-linux x /usr/share/zoneinfo

Wind River Education Services 233 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

-CAP_ALL bind disabled connect disabled }

+# Role: root +subject /bin/dmesg.util-linux o { + / h + /bin/dmesg.util-linux x + /etc/ld.so.cache r + /lib/ld-2.15.so x + /lib/libc-2.15.so rx + -CAP_ALL + +CAP_SYSLOG + bind disabled + connect disabled +} +

3 On your target, execute the following command to replace the default policy file with the new policy file policy_dmesg which allows user access to the dmesg command.

cp /etc/grsec/policy_dmesg /etc/grsec/policy

4 Execute the following commands to enable grsecurity RBAC, verify the current status, then run the dmesg command again.

gradm –E [82997.897283] grsec: (root:U:/sbin/gradm) grsecurity 2.9.1 RBAC system loaded by / sbin/gradm[gradm:13814] uid/euid:0/0 gid/egid:0/0, parent /bin/bash[sh:9030] uid/ euid:0/0 gid/egid:0/0

gradm –S The RBAC is currently enabled.

dmesg The dmesg command now successfully displays the kernel log message instead of the service denied message.

Writing an RBAC Rule for SSH

In this section you will create a policy rule to allow remote access to the target. 1 From the host shell, execute the following command to start an SSH session to the target.

ssh root@TARGET_IP ssh: connect to host 10.1.1.10 port 22: Connection timed out The response indicates that grsecurity running on the target refuses the connection.

2 Execute the following commands to disable grsecurity. When prompted, enter the password windriver.

gradm -D Password:

234 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using grsecurity

3 On your target, execute the following commands to copy the preconfigured file /etc/ grsec/policy_sshd to /etc/grsec/policy. Again policy_sshd has already been added to the target root file system for your convenience.

cp /etc/grsec/policy_sshd /etc/grsec/policy

4 Open the policy file /etc/grsec/policy in an editor, and then in the line containing the string role_allow_ip change the placeholder HOST_IP to the IP address of your host computer. If you are using QEMU-KVM target, the host computer connects to the target by using network TAP; therefore change the placeholder HOST_IP with $HOST_TAP_IP (identified in step 3 on page 3).

vi /etc/grsec/policy

5 Execute the following command to show the differences between the original policy file and the new file that enables SSH access.

diff -uNar /etc/grsec/policy_dmesg /etc/grsec/policy_sshd --- /etc/grsec/policy_dmesg 2014-04-11 10:29:05.773271478 -0400 +++ /etc/grsec/policy_sshd 2014-04-11 10:33:25.167264977 -0400 @@ -48,6 +48,8 @@ role root uG role_transitions admin shutdown role_allow_ip 0.0.0.0/32 +role_allow_ip HOST_IP/32 + # Role: root subject / { / h @@ -84,4 +86,65 @@ connect disabled }

+# Role: root

+subject /usr/sbin/sshd o { +user_transition_allow sshd root +group_transition_allow sshd root + + / + /bin h + /bin/bash x + /boot h + /dev h + /dev/log rw + /dev/null rw + /dev/ptmx rw + /dev/pts rw + /dev/tty rw + /dev/urandom r + /etc r + /etc/grsec h + /etc/gshadow h + /etc/gshadow- h + /etc/ppp h + /etc/samba/smbpasswd h + /etc/shadow- h + /lib rx + /lib/modules h + /lib64/modules h + /proc w + /proc/bus h + /proc/kallsyms h + /proc/kcore h + /proc/modules h

Wind River Education Services 235 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

+ /proc/slabinfo h + /proc/sys/kernel/ngroups_max r + /sys h + /usr h + /usr/lib + /usr/sbin/sshd x + /usr/share/zoneinfo r + /var h + /var/volatile/log/lastlog rw + /var/volatile/log/wtmp w + /var/volatile/run/sshd + /var/volatile/run/utmp rw + -CAP_ALL + +CAP_SETGID + +CAP_SETUID + +CAP_SYS_CHROOT + +CAP_SYS_TTY_CONFIG + bind 0.0.0.0/32:22 stream dgram ip tcp + bind 0.0.0.0/32:0 stream dgram ip tcp + connect 127.0.0.1/32:53 dgram udp + sock_allow_family ipv6 netlink +subject /usr/sbin/tcf-agent o { + / h + -CAP_ALL + bind disabled + connect 172.31.255.1/32:1534 dgram udp + connect 172.31.255.255/32:1534 dgram udp + connect 10.1.1.10/32:1534 dgram udp + connect 10.1.1.255/32:1534 dgram udp} +# Role: nobody +subject /usr/bin/dnsmasq o { + / h + /var/volatile/tmp/resolv.conf.auto + -CAP_ALL + bind disabled + connect 127.0.0.1/32:43259 dgram udp +}

6 Execute the following command to enable grsecurity.

gradm -E

7 From the host shell, execute the following command to create an SSH connection from the host machine to the target.

ssh root@TARGET_IP password: This time the connection succeeds.

8 Execute the following commands to disable grsecurity. When prompted, enter the password windriver.

gradm -D Password:

Working with PaX

In this section you will create default PaX flags on an ELF binary file, then disable the stack flag MPROTECT to let grsecurity access memory pages.

236 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Using grsecurity

PaX prevents an application that does not have explicit permission from accessing memory pages. You can disable PaX flags in the ELF file so the application can access memory pages. The following table describes some common arguments to the paxctl command to enable or disable PaX flags.

PaX Flag Argument to Disable Argument to Enable

PAGEEXEC -p -P

EMUTRAMP -e -E

MPROTECT -m -M

RANDMMAP -r -R

RANDEXEC -x -X

SEGMEXEC -s -S

This lab uses a simple application that implements the system call mmap( ) and generates a binary file (grsecurity) from it. The application enables code execution in the data segment acquired by the system call mmap( ). The code was compiled with the option -DBAD, which enables the flag PROT_EXEC to allow memory pages to execute. The following code snippet shows the source code for this application.

/* * Contrast compiling with: * gcc -UBAD -o grsec mmap-rwx.c * gcc -DBAD -o grsecurity mmap-rwx.c */

#include #include #include #include #include

int main() { size_t *m;

#ifdef BAD m = mmap( NULL, 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); #else m = mmap( NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ); #endif

if( m == MAP_FAILED ) printf("mmap failed: %s\n", strerror(errno)); else printf("mmap succeeded: %p\n", m);

return 0; 1 Execute the following commands and note that the kernel prevents it from executing.

cd /root/bin ./grsecurity

Wind River Education Services 237 Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

Wind River Linux 5.x and Intel Gateway Solutions for IoT

[ 7732.813848] grsec: denied RWX mmap of by /root/ grsecurity[grsecurity:16546] uid/euid:0/0 gid/egid:0/0, parent /bin/bash[sh:3116] uid/ euid:0/0 gid/egid:0/0 mmap failed: Operation not permitted

2 Execute the following commands to create and verify PaX flags for the grsecurity binary.

paxctl -c grsecurity file grsecurity had a PT_GNU_STACK program header, converted

paxctl -v grsecurity PaX control v0.7 Copyright 2004,2005,2006,2007,2009,2010,2011,2012 PaX Team

- PaX flags: ------x-e-- [grsecurity] RANDEXEC is disabled EMUTRAMP is disabled

3 Execute the following commands to disable the MPROTECT flag on the grsecurity binary, verify which flags are disabled, then run grsecurity again.

paxctl -m grsecurity file grsecurity had a PT_GNU_STACK program header, converted paxctl -v grsecurity

PaX control v0.7 Copyright 2004,2005,2006,2007,2009,2010,2011,2012 PaX Team

- PaX flags: -----m-x-e-- [grsecurity] MPROTECT is disabled RANDEXEC is disabled EMUTRAMP is disabled

./grsecurity mmap succeeded: 0x559bf000 This time the grsecurity command executes successfully. Grsecurity protected the system from applications that used mmap to get a data segment flagged as executable. You changed that by using the paxctl command to disable the stack flag MPROTECT in the ELF file.

This concludes the lab. Do not proceed.

238 Wind River Education Services Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute Subject to Wind River Terms of Use - Do Not Copy – Do Not Distribute

http://education.windriver.com [email protected]