12 Working with the operating system

 

This chapter covers

  • Enforcing filesystem-level authorization with the os module
  • Creating temp files with the tempfile module
  • Invoking external executables with the subprocess module
  • Resisting shell injection and command injection

The last few chapters were a lot about authorization. You learned about users, groups, and permissions. I start this chapter by applying these concepts to filesystem access. Afterward, I show you how to safely invoke external executables from within Python. Along the way, you’ll learn how to identify and resist two types of injection attacks. This sets the tone for the rest of the book, which focuses exclusively on attack resistance.

12.1 Filesystem-level authorization

Like most programming languages Python natively supports filesystem access; third-party libraries are not necessary. Filesystem-level authorization involves less work than application-level authorization because you don’t need to enforce anything; your operating system already does this. In this section, I’ll show you how to do the following:

  • Open a file securely
  • Safely create temporary files
  • Read and modify file permissions

12.1.1 Asking for permission

Over the past few decades, many acronyms have become popular within the Python community. One represents a coding style known as easier to ask for forgiveness than permission (EAFP). EAFP style assumes preconditions are true, then catches exceptions when they are false.

12.1.2 Working with temp files

12.1.3 Working with filesystem permissions

12.2 Invoking external executables

12.2.1 Bypassing the shell with internal APIs

12.2.2 Using the subprocess module