Essential php security by chris shiflett pdf download






















Here's how they look: Italic Used for citations to books and articles, commands, email addresses, URIs, filenames, emphasized text, and first references to terms. Constant width Used for literals, constant values, code listings, and XML markup. Constant width italic Used for replaceable parameter and variable names.

Constant width bold Used to highlight the portion of a code listing being discussed. This icon signifies a tip, suggestion, or general note. This icon indicates a warning or caution. Please let us know about any errors you find, as well as your suggestions for future editions, by writing to: O'Reilly Media, Inc.

Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top technology books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information.

Written during one of the busiest years of my life, this book would not have been possible without the unwavering support of my family and friends, and the endless patience of my editors. Writing a book infringes upon your personal time, and this affects those closest to you. Christina, thanks so much for your sacrifices and for understanding, and even encouraging, my passions. The people at O'Reilly have been wonderful to work with.

From the very beginning, they've gone out of their way to make the entire process fit around my writing style and busy schedule. Nat Torkington, thanks for your early editorial guidance and for initiating this project. I never thought I would write another book, but when you came to me with the idea for this one, I couldn't refuse. Allison Randal, thanks for your expert guidance, and more importantly, for your friendly encouragement and understanding throughout the writing process.

Tatiana Apandi, thanks for your enduring patience and for becoming such a great friend. I would like to extend a very special thanks to the best technical review team ever assembled. Thanks to each of you for lending both your expertise and time to help ensure the technical accuracy of this book. While errata is always undesirable, it is especially so when dealing with an important topic like security.

This book is closer to perfect as a result of your aid. Lastly, I want to thank the PHP community. Without your gracious support and appreciation for my work over the years, I would never have written this book. Introduction PHP has grown from a set of tools for personal home page development to the world's most popular web programming language, and it now powers many of the Web's most frequented destinations.

Along with such a transition comes new concerns, such as performance, maintainability, scalability, reliability, and most importantly security. Unlike language features such as conditional expressions and looping constructs, security is abstract. In fact, security is not a characteristic of a language as much as it is a characteristic of a developer.

No language can prevent insecure code, although there are language features that can aid or hinder a security-conscious developer. The concepts in this book, however, are applicable to any web development platform.

Web application security is a young and evolving discipline. This book teaches best practices that are theoretically sound, so that you can sleep at night instead of worrying about the new attacks and techniques that are constantly being developed by those with malicious intentions. It focuses on teaching you the principles and practices that are prerequisities for the lessons that follow. Common tasks that are cumbersome in other languages are a cinch in PHP, and this has both advantages and disadvantages.

Register Globals If you remember writing CGI applications in C in your early days of web application development, you know how tedious form processing can be. This makes writing PHP applications very easy and convenient, but it also poses a security risk. Alone, it does not create a security vulnerabilitya developer must make a mistake. Error Reporting Every developer makes mistakes, and PHP's error reporting features can help you identify and locate these mistakes. However, the detailed information that PHP provides can be displayed to a malicious attacker, and this is undesirable.

It is important to make sure that this information is never shown to the general public. All error-reporting behavior can be modified at any level, so if you are on a shared host or are otherwise unable to make changes to files such as php.

Principles You can adopt many principles to develop more secure applications. I have chosen a small, focused list of the principles that I consider to be most important to a PHP developer. These principles are intentionally abstract and theoretical in nature. Their purpose is to provide a broad perspective that can guide you as you focus on the details.

Consider them your road map. Defense in Depth Defense in Depth is a well-known principle among security professionals. It describes the fact that there is value in redundant safeguards, and history supports this. The principle of Defense in Depth extends beyond programming. A skydiver who has ever needed to use a reserve canopy can attest to the value in having a redundant safeguard. After all, the main canopy is never meant to fail. A redundant safeguard can potentially save the day when the primary safeguard fails.

In the context of programming, adhering to Defense in Depth requires that you always have a backup plan. If a particular safeguard fails, there should be another to offer some protection. For example, it is a good practice to prompt a user to reauthenticate before performing some important action, even if there are no known flaws in your authentication logic. If an unauthenticated user is somehow impersonating another user, prompting for the user's password can potentially prevent the unauthenticated and therefore unauthorized user from performing a critical action.

Although Defense in Depth is a sound principle, be aware that security safeguards become more expensive and less valuable as they are accrued. Least Privilege I used to drive a car that had a valet key. This key worked only in the ignition, so it could not be used to unlock the console, the trunk, or even the doorsit could be used only to start the car.

I could give this key to someone parking my car or simply leave it in the ignition , and I was assured that the key could be used for no other purpose. It makes sense to give a key to a parking attendant that cannot be used to open the console or trunk.

After all, you might want to lock your valuables in these locations. What didn't make sense to me immediately was why the valet key cannot open the doors. Of course, this is because my perspective was that of revoking privilegeI was considering why the parking attendant should be denied the privilege of opening the doors. This is not a good perspective to take when developing web applications. Instead, you should consider why a particular privilege is necessary, and provide all entities with the least amount of privilege required for them to fulfill their respective responsibilities.

One reason why the valet key cannot open the doors is that the key can be copied. Such a copy can be used to steal the car at a later date. This situation might seem unlikely it is , but this illustrates why granting an unnecessary privilege can increase your risk, even if the increase is slight.

Minimizing risk is a key component of secure application development. It is not necessary that you be able to think of all of the ways that a particular privilege can be exploited. In fact, it is practically impossible for you to be able to predict the actions of every potential attacker. What is important is that you grant only least privilege. This minimizes risk and increases security. Simple Is Beautiful Complication breeds mistakes, and mistakes can create security vulnerabilities.

This simple truth is why simplicity is such an important characteristic of a secure application. Unnecessary complexity is as bad as an unnecessary risk. The primary remote sources are HTTP clients browsers and databases. If you properly track data, you should be able to identify when data is exposed. The primary source of exposure is the Internet, and you want to be particularly mindful of data that is exposed over the Internet because it is a very public network. Data exposure isn't always a security risk.

For example, if a user enters payment information, you should use SSL to protect the credit card information as it travels from the client to your server.

If you display this credit card number on a verification page, you are actually sending it back to the client, so this page should also be protected with SSL. In this particular scenario, displaying the credit card number to the user increases its exposure.

SSL does mitigate the risk, but a better approach is to eliminate the exposure altogether by displaying only the last four digits or any similar approach. In order to minimize the exposure of sensitive data, you must identify what data is sensitive, keep track of it, and eliminate all unnecessary exposure. In this book, I demonstrate some techniques that can help you minimize the exposure of many common types of sensitive data. Practices Like the principles described in the previous section, there are many practices that you can employ to develop more secure applications.

This list of practices is also small and focused to highlight the ones that I consider to be most important. Some of these practices are abstract, but each has practical applications, which are described to clarify the intended use and purpose of each.

Balance Risk and Usability While user friendliness and security safeguards are not mutually exclusive, steps taken to increase security often decrease usability. While it's important to consider illegitimate uses of your applications as you write your code, it's also important to be mindful of your legitimate users. The appropriate balance can be difficult to achieve, and it's something that you have to determine for yourselfno one else can determine the best balance for your applications.

Try to employ the use of safeguards that are transparent to the user. If this isn't possible, try to use safeguards that are already familiar to the user or likely to be.

For example, providing a username and password to gain access to restricted information or services is an expected procedure.

When you suspect foul play, realize that you might be mistaken and act accordingly. For example, it is a common practice to prompt users to enter their password again whenever their identity is in question.

This is a minor hassle to legitimate users but a substantial obstacle to an attacker. Technically, this is almost identical to prompting users to authenticate themselves again entirely, but the user experience is much friendlier. There is very little to gain by logging users out entirely or chiding them about an alleged attack. These approaches degrade usability substantially when you make a mistake, and mistakes happen. In this book, I focus on providing safeguards that are either transparent or expected, and I encourage careful and sensible reactions to suspected attacks.

Track Data The most important thing you can do as a security-conscious developer is keep track of data at all timesnot only what it is and where it is, but also where it's from and where it's going. Sometimes this can be difficult, especially without a firm understanding of how the Web works, and this is why inexperienced web developers are prone to making mistakes that yield security vulnerabilities, even when they have experience developing applications in other environments.

Most people who use email are not easily fooled by spam with a subject of "Re: Hello"they recognize that the subject can be forged, and therefore the email isn't necessarily a reply to a previous email with a subject of "Hello. Far fewer people realize that the From header can also be forged.

They mistakenly believe that this reliably indicates the email's origin. The Web is very similar, and one of the things I want to teach you is how to distinguish between the data that you can trust and the data that you cannot. It's not always easy, but blind paranoia certainly isn't the answer. A strict naming convention can help you keep up with the origin of all data throughout your code, and this is a technique that I frequently demonstrate and highly recommend. While understanding where data enters your application is paramount, it is also very important to understand where data exits your application.

When you use echo, for example, you are sending data to the client. When I audit a PHP application for security vulnerabilities, I focus on the code that interacts with remote systems. This code is the most likely to contain security vulnerabilities, and it therefore demands the most careful attention to detail during development and during peer reviews.

It is the process by which you prove the validity of data. By ensuring that all data is properly filtered on input, you can eliminate the risk that tainted unfiltered data is mistakenly trusted or misused in your application. The vast majority of security vulnerabilities in popular PHP applications can be traced to a failure to filter input.

Input is any data that originates from a remote source. For example, anything sent by the client is input, although the client isn't the only remote source of dataother examples include database servers and RSS feeds.

What you consider to be input is a matter of opinion in some cases. For example, session data is stored on the server, and you might not consider the session data store to be a remote source.

If you take this stance, you can consider the session data store to be an integral part of your application. It is wise to be mindful of the fact that this ties the security of your application to the security of the session data store. This same perspective can be applied to a database because the database can be considered a part of the application as well.

Generally speaking, it is more secure to consider data from session data stores and databases to be input, and this is the approach that I recommend for any critical PHP application.

Once you have identified input, you're ready to filter it. Filtering is a somewhat formal term that has many synonyms in common parlancesanitizing, validating, cleaning, and scrubbing.

Although some people differentiate slightly between these terms, they all refer to the same processpreventing invalid data from entering your application. The best approach is to treat filtering as an inspection process. Don't correct invalid data in order to be accommodatingforce your users to play by your rules.

History has shown that attempts to correct invalid data often create vulnerabilities. Consider the following The important point is that any attempt to correct invalid data can potentially contain an error and allow invalid data to pass through.

Inspection is a much safer alternative. In addition to treating filtering as an inspection process, you want to use a whitelist approach whenever possible.

In other words, you want to err on the side of caution. Using this approach, a mistake results in your considering valid data to be invalid. Although undesirable as any mistake is , this is a much safer alternative than considering invalid data to be valid. By mitigating the damage caused by a mistake, you increase the security of your applications. Although this idea is theoretical in nature, history has proven it to be a very worthwhile approach.

If you can accurately and reliably identify and filter input, your job is almost done. The last step is to employ a naming convention or some other practice that can help you to accurately and reliably distinguish between filtered and tainted data. I recommend a simple naming convention because this can be used in both procedural and object-oriented paradigms.

In truth, only the initialization is crucial, but it's good to adopt the habit of considering any variable named clean to be one thingyour array of filtered data. Of course, you could add a default case to this switch statement to take a particular action in the case of invalid data. One possibility is to display the form again while noting the errorjust be careful not to output the tainted data in an attempt to be friendly. While this particular approach is useful for filtering data against a known set of valid values, it does not help you filter data against a known set of valid characters.

These functions are less likely to contain errors than code that you write yourself is, and an error in your filtering logic is almost certain to result in a security vulnerability. Escape Output Another cornerstone of web application security is the practice of escaping outputescaping or encoding special characters so that their original meaning is preserved.

The backslash before the apostrophe is there to preserve itthe apostrophe is part of the data and not meant to be interpreted by the database. Although escaping alone can prevent many common security vulnerabilities, it should never be regarded as a substitute for filtering input. Tainted data must be first filtered and then escaped.

To escape output, you must first identify output. In general, this is much easier than identifying input because it relies on an action that you take. These cases all constitute output. Like filtering, escaping is a process that is unique for each situation. Whereas filtering is unique according to the type of data you're filtering, escaping is unique according to the type of system to which you're sending data. For most common destinations including the client, databases, and URLs , there is a native escaping function that you can use.

If you must write your own, it is important to be exhaustive. Find a reliable and complete list of every special character in the remote system and the proper way to represent each character so that it is preserved rather than interpreted.

The most common destination is the client, and htmlentities is the best escaping function for escaping data to be sent to the client. Like most string functions, it takes a string and returns the modified version of the string.

However, the best way to use htmlentities is to specify the two optional argumentsthe quote style the second argument and the character set the third argument. To distinguish between escaped and unescaped data, I advocate the use of a naming convention. It accepts the same arguments, and the only difference is that it is less exhaustive. If the username contains only alphanumeric characters, the escaping is not actually necessary, but it is a practice that adheres to Defense in Depth.

Consistently escaping all output is a good habit that dramatically increases the security of your applications. Another popular destination is a database.

When possible, you should escape data used in an SQL query with an escaping function native to your database. If there is no native escaping function for your database, addslashes can be used as a last resort.

Forms and URLs This chapter discusses form processing and the most common types of attacks that you need to be aware of when dealing with data from forms and URLs.

By the end of the chapter, you will not only see examples of these attacks, but also what practices you can employ to help prevent them. Vulnerabilites such as cross-site scripting exist when you misuse tainted data. While the predominant source of input for most applications is the user, any remote entity can supply malicious data to your application.

Thus, many of the practices described in this chapter are directly applicable to handling input from any remote entity, not just the user.

See Chapter 1 for more information about input filtering. Forms and Data When developing a typical PHP application, the bulk of your logic involves data processingtasks such as determining whether a user has logged in successfully, adding items to a shopping cart, and processing a credit card transaction.

This obvious observation is what makes it trustworthy. Any data that originates from a remote source is input, and all input is tainted , which is why it must always be filtered before you use it. Tainted data is anything that is not guaranteed to be valid, such as form data submitted by the user, email retrieved from an IMAP server, or an XML document sent from another web application.

For example, the following code outputs chris example. Any data that originates from a remote source must be considered tainted until it has been proven valid. Although a user can send data in multiple ways, most applications take the most important actions as the result of a form submission.

In addition, because an attacker can do harm only by manipulating anticipated data data that your application does something with , forms provide a convenient openinga blueprint of your application that indicates what data you plan to use. This is why form processing is one of the primary concerns of the web application security discipline. In fact, there is no difference between a GET request sent as the result of a user submitting an HTML form and one sent as the result of a user clicking a link.

Keep in mind that if you try to include a query string in the action attribute of the form tag, it is replaced by the form data if you specify the GET request method. The form data is in the content of the request rather than in the query string of the requested URL. The following sections discuss how attackers can take advantage of your forms and URLs by using these as openings to your applications.

This type of attack involves the user modifying the URL in order to discover what interesting thing can be done. While GET data is only slightly more convenient to manipulate than POST data, its increased exposure makes it a more frequent target, particularly for novice attackers.

Most vulnerabilities exist because of oversight, not because of any particular complexity associate with the exploits. Any experienced developer can easily recognize the danger in trusting a URL in the way just described, but this isn't always clear until someone points it out.

To better illustrate a semantic URL attack and how a vulnerability can go unnoticed, consider a web-based email application where users can log in and check their example. With a web-based email application, an email address may not already be stored, so a user who answers the verification question may be asked to provide one the purpose being not only to send the new password to this address, but also to collect an alternative address for future use.

If a user arrives at this form after answering the verification question correctly , you are reasonably assured that the user is not an imposter but rather the legitimate owner of the chris account. If this user then provides chris example. After recognizing this, the user may decide that php example. A new password will be generated for the php account, and it will be sent to chris example.

It is this lack of trust given to input that is the key to preventing such gaping holes in your applications This example is not completely contrived. It is inspired by a vulnerability discovered in Microsoft Passport in May File Upload Attacks Sometimes you want to give users the ability to upload files in addition to standard form data.

Traditionally, the interface includes a standard text field as well as a browse button, so that the user can either enter the path to the file manually or browse for it. In Safari, only the browse option is available.

Luckily, the behavior from a developer's perspective is the same. The restriction needs to be enforced on the server side in order to be considered reliable. The receiving script, upload. Security is an issue that demands attention, given the growing frequency of attacks on web sites. There are no reviews yet. Be the first one to write a review. Books for People with Print Disabilities.

Internet Archive Books. Includes 5. Exposed Source Code 5. Backdoor URLs 5. Filename Manipulation 5. Code Injection 6. Files and Commands 6. Traversing the Filesystem 6. Remote File Risks 6. Command Injection 7. Authentication and Authorization 7. Brute Force Attacks 7. Password Sniffing 7. Replay Attacks 7. Persistent Logins 8. Shared Hosting 8. Exposed Source Code 8. Exposed Session Data 8.

Session Injection 8. Filesystem Browsing 8. Chapters describe potential attacks with examples and then explain techniques to help you prevent those attacks. Chapters describe potential attacks with examples and then explain techniques to help shifflett prevent those attacks.

My library Help Advanced Book Search. Bestsellers in Computer Security. I will be recommending this book to people on my team and we will cover lessons from it in our monthly meetings where we can talk about the development procedures we have in place and how to improve code quality overall. Law and Guidance Helen Wong. The subject matter is covered thoroughly and simply. The Perfect Weapon David E. Core Objective-C in 24 Hours.



0コメント

  • 1000 / 1000