How to develop Secure software

how to design secure software and how to make secure software and how secure is encryption software how to make secure software how to make your software secure
Dr.MohitBansal Profile Pic
Dr.MohitBansal,Canada,Teacher
Published Date:26-10-2017
Your Website URL(Optional)
Comment
Developing Secur e Software Computers have a strange habit of doing what you say, not what you mean. (CWE/SANS Top 25 Monster Mitigations 1 ) Some or ganizations take the view that features are the most important delivery and with limited time and resources, this becomes the focus. At the end, security is added in. The problem with this approach is that deployment may occur with little to no security features. This ensures that the software is defenseless or near defense- less against attackers and data breaches are the inevitable result. Consider instead that designers and de velopers know standard security practices, since they were trained in security before their projects began. Security require- ments are decided based on risk analysis and regulatory compliance to ensure that high priority risks are mitigated and included in the schedule. Secure designs ensure that the architecture is effective and effi cient. When code is written, secure utilities are familiar to the coders and correctly used the fi rst time. Knowledgeable testers perform competent penetration testing and use automated test tools for faster, more accurate testing. The code may still be released before all bugs are fi xed, but the organization knows and approves of any security fl aws that remain. This chapter introduces secure softw are engineering. These techniques are described within the software development lifecycle of Requirements, Design, Coding and Test. It is assumed that the reader has done some programming and testing before reading this chapter. This chapter builds on the Unifi ed Modeling Language ( UML ), commonly used in design. Ho wever, in case the reader has not yet developed expertise in UML, an introduction to each UML diagram is dis- cussed before describing the security enhancements to UML. However, every security- minded software developer should also be aware of common attacks to software. 256 15 Developing Secure Software 15.1 Important Concepts: Attacks to Software This book has addressed a slew of attacks to computer systems and network, but there are vulnerabilities that are peculiar to software development. General software attacks include buffer overfl ow, integer/fl oating point overfl ows, SQL injection and OS command injection, directory traversal, race conditions, abusing direct object references, and network sniffi ng or otherwise causing a breach of confi dential data. Most of these attacks are further described elsewhere or will be addressed in specifi c sections in this chapter, but some attacks need to be further described here. Previously we defi ned an SQL injection as appending database commands to form input, causing an additional SQL command to occur in addition to the program’s intended command. An OS command injection is similar , except that an OS com- mand is appended to form input, and is possible if the software enables OS access through the database interface. A r ace condition enables attackers to see data from other users or to cause a denial of service attack. A race condition is caused when multiple threads simulta- neously access shared data within the same process. Critical sections, implemented with semaphores or monitors, ensure safe access when shared data is required. 15.1.1 Service Oriented Architectures and the Web Most applications today use a client-server, distributed architecture, such as Service- Oriented Architecture (SOA). SOA uses platform neutral messaging, such as HTTP or Extensible Markup Language (XML). Components of the distributed architec- ture are interoperable, modular and reusable 2. Services are disco verable, with contract-based interfaces. Service discovery may be implemented via a server yel- low page (e.g. Universal Discover Description and Integration Server or UDDI). The discovery service employs an interface description language to describe the calling and return parameters for a web service (e.g., Web Services Description Language, or WSDL) 2. W e will evaluate web services as an example SOA architecture. The W orld Wide Web enables hackers from around the world to attack your software from the convenience of wherever the attacker happens to be. In general, client software can easily be modifi ed, rewritten or spoofed to attack. In addition to the attacks listed previously, web attacks may include reading and modifying cook- ies and causing a victim server to store or execute attacks 3 , 4 . W eb session IDs may be easily spoofed and cookies modifi ed. Other web attacks are listed in Table 15.1 5 . Because of the distrib uted nature of web services, security must be implemented on both client and server sides. Controls for both sides (and transmissions in between) include authentication, authorization, confi dentiality, integrity, availability, and non-repudiation 5. In addition, b usiness rules and regulations must be in effect. 15.1 Important Concepts: Attacks to Software 257 Table 15.1 W eb form and web service attacks Attack name Attack description Directory A URL is coded to access unexpected fi les or commands on the web server, traversal such as www.company.com/../../cmd . In each of these cases, characters may be encoded to hide their contents: %2e%2e%2 f WSDL The disco very of web services via UDDI or a search for WSDL fi les for enumeration attack purposes Replay T ransmitted packets may be copied and resent. Packets may also be modifi ed before transmission URL jumping To attempt to avoid authentication, web references are accessed out-of-order XPath injection Modifi es XML format or contents to create unintended data. Attacks are similar to SQL Injection except that XML is attacked instead of SQL XML overfl ow This Denial of Service attack constructs in valid or repeats XML structures in an attempt to confuse the server or overfl ow memory Packet replay must be countered. If web sessions are maintained by the server, session IDs should time-out and not be easily guessable 3 . Cross - site scripting ( XSS ) is a common web attack that requires an e xtended explanation. In an XSS attack, a malicious user provides data that will be executed in other users’ browsers. This can occur when an attacker injects data with embed- ded executable scripts into forms with prebuilt scripts which will be executed 6 . This can occur in three ways 4 : • Local XSS: W ebpage code is modifi ed, often by modifying a Document Object Model (DOM) that is executed using JavaScript. • Stored XSS: The attack er uses form input to modify a database. The input includes infected links or fi les. • Refl ective XSS: The victim server returns infected client data, submitted as part of the client input. Cross Site Scripting can be defended against using a same - origin policy . This policy ensures that all components of a web page must use the same protocol and port number, and be derived from the same host. If we compare two URLs: http:// www.organization.com/directory1 and https://organization.sales.com:85/direc- tory3 , we can see they differ in protocol (http versus https), in port number (default 80 versus specifi ed 85) and in host ( www.organization.com and organization.sales. com ). An y single difference would violate the same-origin policy. Cross - site request forgery occurs when a serv er provides an authentication token to a user, which an attacker copies and uses for similar or other purposes 3 . The root cause of this problem is the pre-approved nature of the authentication token, which instead should be validated on a per input basis. Complete mediation ensures that every request to an operating system or server is verifi ed for authorization, regardless of the number of repeated accesses 2 . Attacks may also be application-specifi c. Therefore, being aware of secure prac- tices at each development stage is important. 258 15 Developing Secure Software 15.2 Requirements The purpose of the Requirements Stage is to determine what the product to be developed will do, who will be using it, and why it is being developed. This stage involves interviewing the customer to fi nd out how the software should look, act and perform; developing a prototype; and may include developing a requirements docu- ment, which serves as a contract between the software developers and the customer. A well-designed human–machine interface can minimize user errors and wasted time and thus assure data accuracy and integrity. Contracts may require that products operate according to security re gulation or industry standards, such as Common Criteria, Open Group, or American government stan- dards: NIST or STIGs. ISO 15408 Common Criteria ( www.commoncriteriaportal.org ) offers a standard for product development and testing, with a rating system between one and seven 2. Open Group ( www.opengroup.org ) requires that products specify a list of detailed security features pertaining to authentication, passwords, event notifi ca- tions, failure handling, access control, object reuse, malware control, and the recogni- tion of tampering 7 . U.S. Defense standards are called Security Technical Information Guides (STIGs): http://iase.disa.mil/stigs . These and NIST sources include a series of documents for security implementation. The Health First Requirements Document, included at http://extras.springer. com , is an e xample of a professional requirements document that uses UML Use Cases. The current version of the Requirements Document lacks in privacy and security features and HIPAA adherence. Therefore, there are a number of exercises that the reader can perform to enhance this document for security, privacy and compliance. The Health First Requirements Document includes a Use Case Dia gram , which is a single diagram that shows the basic features of the software from a user’s perspecti ve—in this case, a doctors’ offi ce database. This document also includes Use Case Descriptions , which describes how each feature appears to work from a users’ perspective. The Use Case Descriptions are described in text by listing the sequential steps of user-does-this and then system-does-this, etc. In the document, each use case is shown with its database form(s) to help the reader understand what the user will see. The reader is encouraged to look through the Requirements Document to get a better feel for these concepts, if the user has little or no experi- enced with UML requirements and design. The e xample demonstrated in this chapter will be a simpler application of a reg- istration system, which distributes documentation or source code to any person who registers for it. Figure 15.1 shows a simple Use Case Diagram for the registration system. In this fi gure, a Client actor Registers for documentation by entering their name, email and job function, and can Send Feedback after they receive the docu- mentation. The Provider actor may Send Email to the Clients, notifying them of any updates to the documentation. In a Use Case Diagram, actors, who are sho wn as stick fi gures with labels, are the planned users of the system 8. The diagram also shows ovals, called Use Cases, which each list one basic user feature. No w that you 15.2 Requirements 259 Registration System for Product Distribution Client Register Enter Feedback Provider Send Email Update Fig. 15.1 Registration use case diagram understand the basic demo application, we will proceed with designing requirements for it. The fi rst step is risk analysis. The OCT AVE Security Requir ements Process defi nes how risk analysis (also known as threat modeling) can be performed for software. (OCTAVE is an abbre- viation for Operationally Critical Threat, Asset and Vulnerability Evaluation.) OCTAVE steps include 9 : 1. Identify critical assets 2. Defi ne security goals 3. Identify threats 4. Analyze risks 5. Defi ne security requirements The fi rst step, Identify Critical Assets , is concerned with describing the assets (e.g., data) that the software will be working with. Figure 15.2 shows a Business Process Model (or Activity Diagram) for the Registration System, split into two parts to demonstrate a fl ow chart for each of the two actors, Client and Administrator. The solid bullet is where each user starts, and each actor performs the activities (shown as rounded-corner rectangles) in order as the arrows indicate. Notice that the data, shown as squared-off rectangles, are either created or accessed by both the actors. When the dotted arrow points to the data, the data is created or modifi ed, whereas if the dotted arrow points to the activity, the activity is reading the data. In any case, the data (or assets) to protect in this diagram include Contact Information, Materials and Comments. This represents the registration information (name, email, job function), documentation to be distributed, and feedback, respectively. The second OCTAVE step, Defi ne security goals , considers how the three secu- rity goals: confi dentiality, integrity and availability each relate to the three data assets of the Registration System. In Table 15.2 , each data is rated from 1 to 3 to represent low (), moderate () and high () for each security goal. For this example, we want to distribute the materials to the public (preferably with their 260 15 Developing Secure Software Client Administrator Enter menu Select admin selection function Accept Enter contact comments information Generate email Generate list for all contacts of comments Contact info Comments Materials Edit contact Email Provide links information comments to materials to Administrator Fig. 15.2 Business process model for registration system Table 15.2 Defi ne security goals Assets Confi dentiality Integrity Availability Contact Info No PII maintained Require accurate list Weekly backup of interested persons Materials Public with login Accurate – 24/7 preferred tamper-proof Comments Confidential pref. Accurate – tamper-proof Weekly backup, email registration), so the requirement for Confi dentiality of Materials is rated low = 1. However, we would like the materials to be accurate, so the requirement for Integrity of Materials is rated high = 3. Availability for the materials is important, but if the registration system is down for a couple days, since the materials are free, there is no fi nancial loss. Therefore the requirement for Availability of Materials is rated moderate = 2. The third OCT AVE step, Identify threats, considers what threats the softw are may be vulnerable to. Consider who your adversaries are, and what they are inter- ested in. Figure 15.3 shows the STRIDE threat model , where each letter in STRIDE represents a threat to consider (S = Spoof, T = Tamper, etc.) In this diagram, the left column describes what the threat is, then the two right describes example software enhancements, in increasing sophistication, to combat that threat. A much more extensive threat model is provided by The Common Attack Pattern ™ Enumeration and Classifi cation ( CAPEC ) initiative ( https://capec.mitre.org ). 15.2 Requirements 261 Fig. 15.3 Identify threats with STRIDE The “What it is” column in Fig. 15.3 is a summary of their weaknesses. Their Common Weakness Risk Analysis Framework recommends prioritizing weak- nesses specifi cally for your software, from their accumulated weakness list. Your implementation would address your highest priority weaknesses. After gaining an understanding of threats, we need to apply them to the Registration System. For that we can use a MisUse Case Diagram—a kind of Use Case Diagram that also shows the ‘features’ or attacks a hacker or fraudster may use to threaten our system (Fig. 15.4). The MisUse Case Diagram adds attack ers or MisUsers as black-headed stick persons, and MisUse Cases as black ovals, naming attacks 10. (This is of course, independent of the skin color of the actual actor and MisUser) The dotted arrows point from the MisUse Cases to the Use Cases they “threaten”. MisUse Cases are labeled similar to Use Cases in ‘Verb Noun’ or ‘Verb Adjective Noun’ form, such as ‘Launch DOS’ or ‘Change Valid Data’. Most of these diagrams are drawn with SeaMonster 11, b ut in many cases other commercial tools or Suraksha can also color use cases and/or actors with some fi nagling. W ith further consideration, we can think of more attacks, which causes the dia- gram to become a bit unruly. Inheritance can compress our threats, by having spe- cifi c threats point to generalized threats. This is shown in Fig. 15.5 . An alternative solution is to generate a MisUse Case Diagram per Use Case. A Thr eat Tree may also document lik ely attacks 13 , such as in Fig. 15.6 . An advantage of developing such a Threat Tree is that they are portable to other similar products/environments. A good one can be reused from one similar product to another, and need only be maintained as new threats, products, and/or environments arise. 262 15 Developing Secure Software Fig. 15.4 Registration MisUse case diagram Send Continual Requests Overflow DB Enter client info threatens Launch DOS threatens Client Attacker Attack SQL Enter Feedback Register Change valid data Obtain list Fig. 15.5 MisUse case diagram with inheritance 12 There are three main attacks we will discuss here in depth. One attack is that someone might obtain materials without registering, for example by searching the Internet for them. Another attack may be a Denial of Service, where an automated system registers random garbage to quickly fi ll up our database with garbage regis- trants. A third problem might be an SQL attack, where an attacker adds SQL com- mands to our form input, to perform unintended database commands. We have an idea of the possible threats, but now let us consider the details. For each MisUse Case oval, we create one MisUse Case Description. The MisUse Case 15.2 Requirements 263 Attack Confidentiality Integrity Availability Bypass Password SQL Attack DOS Registration Attack Google Friend provides Subvert System via Fail System Fill DB materials link to materials system file access with bug Resources Fig. 15.6 Threat tree for registration system Table 15.3 Launch denial of service MisUse case MisUse Case: Launch denial of service Summary : An attacker issues repeated Registrations, resulting in fi lling the database with fake data, and depleting system and fi le resources Basic path : 1. Do forever 2. The attacker requests a Registration form 3. The attacker sends random fake data in the form 4. Enddo Alternative paths : AP1. Repeat data is entered Mitigation points : MP1. At BP Step 2–3 use CAPTCHA in Re gistration form to avoid bot attack MP2. At BP Step 3 validate data: no duplicates, data type matching Description describes the steps of an attack 14 , similar to how a Use Case Description describes the steps of a normally executing process. Table 15.3 shows the detailed Launch Denial of Service MisUse Case attack. The Basic Path is a numbered outline of the steps of the attack. The Alternate Paths section describes slightly variant attack methods. The Mitigation Points section describes how we intend to defend against this attack type. Our Mitigation Point 1 (MP1) says that at Basic Path (BP) steps 2–3 we will use CAPTCHA to a void a Distributed Denial of Service (DDOS) attack. A CAPTCHA requests that users enter the letters/numbers shown in an image on the form. CAPTCHA is used to maximize the possibility that the user is a real person, and not an automated program.264 15 Developing Secure Software Table 15.4 Circumvent input MisUse case Misuse case : Circumvent input Summary : Deviant client bypasses registration by going directly to the download web page Pr eCondition: Client does Google search and fi nds link to download web page OR obtains link reference from a colleague Basic path : 1. DeviantClient obtains web reference from Google or friend 2. DeviantClient uses web reference to download materials without registering Mitigation points : MP1: W eb page has no other web references MP2: Create dynamic web page with unique reference. This web page is accessible only if a key is provided during registration. Key expires in 1 week Related b usiness rule : Users must register to obtain materials Mitigation guar antee : MP1 and MP2 solves Google search problems. MP2 could be used by friends for 1 week, which is acceptable Table 15.5 Risk analysis Threat Impact Likelihood Priority = IL DOS 9 SQL Attack 9 (affects integrity, confidentiality) Invalid Input 3 Circumvent input 6 Hea vyweight Misuse Case Descriptions include additional information, such as: Extension points, Triggers, Preconditions, Assumptions, Mitigation guarantee, Related business rules, Stakeholders and threats, Terminology and explanations, Scope, Abstraction level and Precision level 14. An e xample MisUse Case Description with more options is shown in Table 15.4, which describes ho w a user could bypass registration. This description includes a Precondition, Related Business Rule and Mitigation Guarantee. The fourth OCT AVE step is Analyze risks. In this step, SANS recommends con- sidering the damage that may arise from loss of reputation and user productivity, and legal issues. Consider also the ease of attack and attack repetition, and the ease of detecting a successful penetration 15. Similar to calculating or ganizational risk, the risk priority is calculated as Impact multiplied by Likelihood. In Table 15.5 , both Impact and Likelihoods are rated on a 1–10 scale (here 1–3, with three stars being serious.) Any threat which negatively affects the database is considered seri- ous (). Invalid Input affects only one user’s registration, and so has a low impact rating. The fi nal priority scores are high (9) for Launch DOS and SQL Attack, mod- erate (6) for Circumvent Input, and low (3) for Invalid Input. The fi fth and last OCTAVE step is Defi ne security requirements. In this step we document the security functions or features in detail using a Security Use Case Diagram and Security Use Case Descriptions. 15.2 Requirements 265 Fig. 15.7 Depiction usecase of a security use case include Security use case mitigate misuse case Fig. 15.8 Security use case diagram for three threats W e can modify our MisUse Case Diagram to include Security Use Cases , which are white ovals describing a security feature. (Retain a copy of the original MisUse Case Diagram, before modifying it) A Security Use Case (SUC) is shown in Fig. 15.7. Basically , our original user feature, shown as a use case (UC), includes a SUC which mitigates one or more misuse cases (MUC). Figure 15.8 is an applied Security Use Case Diagram mitigating three of our threats: Launch DOS, Attack SQL, and Enter Invalid Data MUCs. The Validate Registration SUC will include a CAPTCHA check and will validate input to prevent 266 15 Developing Secure Software Table 15.6 V alidate registration security use case Security use case : V alidate registration Summary : This include validates a registration Precondition : A name, email, job function, and Captcha are provided Basic path : 1. The user enters a name, email, and job function in Step 3 of Register 2. Do for fi ve attempts or until valid CAPTCHA: 3. Rerequest form with new CAPTCHA 4. The system checks for valid characters, to prevent SQL injection 5. The system checks for valid name, email and job function 6. If email is unique in database 7. Save record to database 8. The system returns success P ostconditions : The input has been checked for bot attempt, SQL injection, and validity SQL attacks, redundant registration entries and other mistakes. Note that the Enter Client Info UC includes Validate Registration SUC, which means that that Validate Registration is always executed by Enter Client Info, similar to an uncon- ditional procedure call. Because DOS is a se vere problem, a second Security Use Case is Edit/Delete Client, which enables the Administrator to delete suspicious registrations. The Send Email Update UC extends to the Edit/Delete Client SUC to show that it is an optional execution. Note that includes implies always, whereas extends implies sometimes or optional. We have written a full description of our Use Cases and MisUse Cases, and we should also do so of our Security Use Cases. Table 15.6 sho ws the Validate Registration Security Use Case, which is patterned after a regular Use Case. The Basic Path describes the overall functions of verifying CAPTCHA, validating input, and checking for duplicate registration entries. The Postcondition describes the attacks that are mitigated as part of this security function. Certainly it is important to modify the Use Cases to sho w when they call the SUCs. An example is shown in Table 15.7 , which shows the Register Use Case. An Include statement is shown in bold and italic for emphasis. The Include calls the Validate Registration SUC. While the full requirements cannot be fully sho wn in this chapter, we summarize the Security Requirements with the following Business Rules 12 : 1. Users cannot access the web pages without re gistering their emails into the system; 2. Email registrations shall be accurate; 3. The database with user emails shall not be easily broken into; 4. It is not easy to circumv ent the registration process; 5. The re gistration system is near-immune to DDOS attacks; and 6. Obvious attacks would be logged and emailed to the administrator. 15.2 Requirements 267 Table 15.7 Use case includes security use case Use case : Register Summary : Client re gisters to obtain access to download materials Preconditions: Client is at welcome web page Basic path : 1. The client selects the Obtain Materials link 2. The system asks the client for name, email address, job function, and CAPTCHA 3. The client enters all three required information 4. Include (validate registration) 5. The system displays the URL for the download materials Alternative path : AP1. If an attack is detected, no URL is displayed Postcondition : The client has access to the download materials The database contains the client contact information This e xample has given an overview of the different steps and activities that make up the OCTAVE risk analysis through using MisUse Cases. To complete the full requirements would mean documenting all the UCs, MUCs and SUCs. A Requirements Inspection provides feedback from the customer, experienced security/design staff and/or auditors, to avoid future problems. Errors found and fi xed at this stage save re-development time and the high costs of security breaches, following deployment. 15.2.1 Specify Reliability The a vailability requirements are not severe for this registration system. However, for mission critical systems, such as air transportation or defense software, reliabil- ity may be a life or death concern. Reliability can be defi ned as software operating as expected, for a defi ned duration of time and within defi ned conditions 16 . Reliability engineers calculate the failure rate of all mission critical components of a system, to determine the allowable tolerance (or intolerance) for failure. Reliability requirement statistics are defi ned in the contract and requirements, and then must be implemented in later development stages. Metrics that may be specifi ed in a con- tract, project plan, reliability plan and/or the non-functional requirements section of a Requirements document include 16 : • Number of defects in softw are: failure rate data, measured during test and deployment; or defect density, measured as the number of defects per thousand lines of code. • T otal test time/performance: Considers the failure count relative to total test time or total CPU time during testing; mean time between failures. 268 15 Developing Secure Software • Defect elimination metrics: defects found per de velopment stage: A mature organization can predict, for a given size of code, how many defects should be found per development stage inspection and testing. If expected defects are not found, quality control is probably lacking and the project is at risk of a high defect rate. These metrics may be required to be simply provided and/or to achieve a speci- fi ed level of reliability. 15.3 Analysis/Design The purpose of the Analysis/Design Stage is to determine ho w the software will be built to fulfi ll the features specifi ed during the Requirements Stage. During design, the eventual product is taking shape and details in the implementation are becoming known. If we consider that a suit of armor protects a knight’s attack surface (by covering nearly his entire body), how can our program also be completely pro- tected? An attac k surface analysis considers where newly arising vulnerabilities may lie that have not already been considered. An attack surface minimization con- siders how features may be turned off, wherever possible, as part of a least privilege implementation 2 . Error or exception handling is also carefully designed. Considering our Registration System case, new concerns will naturally arise during Design related to a web service implementation. Within UML, two aspects of design include 8 : 1. Static Model: These diagrams sho w the structure of the software, including classes, components and subsystems. 2. Dynamic Model: These diagrams describe the system behavior, including how each Use Case is executed. 15.3.1 Static Model In lar ge standardized systems, such as Open Group’s Common Data Security Architecture (CDSA), security may be layered as shown in Fig. 15.9 17 . The application issues requests through an Application Programming Interface to the Common Security Services Manager. Within the security manager, the upper layer includes security services, such as digital certifi cate and key management, while the lowest layers are library utilities for specifi c functions. All interfaces are specifi ed. This implementation takes advantage of software reuse and reliability. Regardless of the actual architecture used, during Static Modeling a blueprint of the new service is developed. Subsystems are shown as folders in UML. Figure 15.10 shows how a CAPTCHA and Sanitizer security packages protects the Registration Subsystem. The purpose of the Sanitizer package is to validate 15.3 Analysis/Design 269 Application Common Security Services Manager Application Programming Interface System Security Services (Digital Certificate, key management, integrity services, security contexts) Cryptographic Trust Policy Authorization Certificate Data Elective Services Mgr. Services Computation Library Mgr. Storage Module Mgr. Mgr. Library Mgr. Mgr. CS Library Trust AC Library Cert. Library DS Library New Library Services Lib. Fig. 15.9 Open group’s common data security architecture Fig. 15.10 Documenting security packages (or sanitize) user input. Security packages can be labelled with a Security Package label and name, a Risk Factor showing the priority calculated during Requirements, and one or more Security Descriptor, which describe the threat(s) that the package defends against 18 . At a more detailed (drill-do wn) level, each subsystem could be diagramed using a class diagram. Of course some classes and even patterns of classes will have secu- rity functions, but security does not change how Class Diagrams work. Components are reusable softw are modules that could be classes or subsystems. For example, CAPTCHA, VPN, database server, and Sanitizer modules are plug-in utility software, which certainly qualify as components. Figure 15.9 is an example of a MisUse Deployment Diagram showing components as pink (or gray) rectan- gles. Components have standardized input and output to serve as an explicit inter- face that the utility component advertises to the outside world. 270 15 Developing Secure Software Fig. 15.11 A MisUse deployment diagram W ith the Internet, software has become distributed in its deployment and/or use. A Deployment Diagram shows where the various components of the software will reside (e.g., on client or server) 8 . A MisUse Deployment Dia gram or MDD (Fig. 15.11 ) in addition shows where security components reside, and the attacks that those security components mitigate. This single diagram is useful in that it eas- ily shows the concrete security deployment, including how attacks can be mitigated across systems 12. F or example, input validation must occur to combat SQL attacks. But if this validation occurs only on the client side, security is inadequate. Therefore, the location of security code is as important as its existence. In Fig. 15.11 , the Sanitizer is on the Server side, protecting against an SQL Attack there. In a MDD, Misusers represent general attack types. Packages are shown in white to represent application subsystems, and in pink to represent security components or packages. The attack name is assigned to the misuser. Figure 15.10 was drawn with Microsoft Visio 12 . Security components for the Register System are described as follows 12 : • Dynamic web pages: Ensures documents are available only at download time. Server-side programs enforce registration, by requiring users to register their email address. • Do wnloads provided by email: Users obtain the Dynamic web page via email following registration. 15.3 Analysis/Design 271 • CAPTCHA: CAPTCHA helps to mitigate automated Distrib uted Denial of Service attacks. • Input sanitization and v alidation: A server-side program allows all user input from the registration form to be sanitized of input attacks such as cross-site scripts or SQL injections. The program also validates all incoming data. • Ev ent logging: A server-side program logs any event needing to be tracked, thus providing a record of activity at the web site. Each system module has the ability to write information to the system log. The amount of logging is confi gurable. 15.3.2 Dynamic Model The purpose of this model is to design the beha vior of the classes, components and subsystems defi ned in the Static Model. Sequence Diagrams show how objects (or class instances) interact in order to fulfi ll a use case 8. Figure 15.12 is an e xample Sequence Diagram for the Register Use Case. At the top of the diagram are objects, shown as actor instances or as rectangles listing object names. Theoretically, objects send messages to other objects, which are shown as labelled arrows between the objects. In practice, messages are method calls or packet transmissions, and the labels represent the method or packet name. Figure 15.12 shows packet transmis- sions between the actors on the client side, and the Register and Download software on the Server side 12; each arro w represents one packet transmission, where dot- ted arrows show responses to solid arrows. In Fig. 15.12, a Le gal:Client requests the materials using the Request_Info message sent to the Register program. The Register program replies with the Legal: Register Download Client Request_Info Registration_Form Submit_Register_CAPTCHA_Form Email_Link_&_Key Parallel Request_Download_w_Key Illegal:Client Dynamic_HTML_w_Links Email_Link_&_Key illegal Request_Download_w_Key Dynamic_HTML_w_Links Fig. 15.12 MisSequence diagram for the re gister use case model 12 272 15 Developing Secure Software Registration_Form, which the Legal:Client completes and sends in as a completed Submit_Register_CAPTCHA_Form. The form data is received by Register, which sanitizes and validates the form data including verifying the CAPTCHA input. Once the input is validated, Register inserts Legal:Client’s registration data into the database, together with a newly generated unique key. Register then sends an email to Legal:Client’s email address, shown in Fig. 15.11 as the message Email_ Link_&_Key. This email contains a link back to the dissemination web site. The link includes an appended unique access key. When the link is clicked by the user, an HTTP Request_Download_with_Key message is sent to the Download program. The key contained in the packet identi- fi es the user as having previously registered with the web site and serves as a type of password for temporary access to the downloadable fi les. Thus, without a valid email, no download occurs. When the Download program receives the key or temporary password, it gener- ates a Dynamic_HTML_with_Links for Legal:Client. The downloadable fi les are provided temporarily during the web access and deleted soon after. This minimizes the possibility of non-registrants obtaining the downloadable fi les. The dynamic web page ensures that search engines will not ordinarily provide access to this page. While Sequence Diagrams generally sho ws normally executing logic, Mis - Sequence Dia grams also show attack handling logic 19 . Attacks are shown as conditional logic, which demonstrate how attacks are received and handled. The Parallel box at the bottom of the diagram shows the normal occurrence on top half of the Parallel box, and the attack in the bottom half, below the dashed line. The Parallel label indicates that the two activities can occur together. In this attack, Legal:Client passes the email with link and key to their friend, Illegal:Client, during the one week duration the key is valid. This is shown as the Email_Link_&_Key message sent from Legal:Client to Illegal:Client, and Illegal:Client’s subsequent access to the downloadable data. We have no easy fi x to this, but some risk is accept- able in the interest of getting the system up quickly. State T ransition Diagrams (STDs or State Diagrams) can ensure inte grity of real-time processing, thus avoiding incorrect actions when receiving a right input at the wrong time 20 . For example, an ATM money machine will not give you money whenever you ask for it; you must slide your card and enter your PIN fi rst, then you can input the amount of money you would like. Thus, STDs show how one class/ object should behave, depending on what state that object is in. STDs can ensure that software retains the proper order of processing, recognizes out-of-sequence steps, and can change behavior based on time or past history. In other words, a well- designed STD can ensure that an object behaves properly in all scenarios. Figure 15.13 is an e xample STD. STDs have states, shown as rectangles with rounded edges, and transitions, shown as labelled arrows. Any object can only be in one state at a time. The object transitions from one state to another when any of its outgoing transitions is received or becomes true; then it transitions to the state where the arrow points. Each state is split into two parts. The top part contains the state name. The bottom part shows the processing that occurs in the state, and which does not cause a transition to a different state. This bottom part describes Events that may 15.3 Analysis/Design 273 Fig. 15.13 State transition diagram for client Receive Registration_CAPTCHA_form Registered entry / Save reg. info Generate key Generate email Tx Email_link_and_key Downloadable do / IF HTTP_Req_w_key THEN Check key in Database Send Dynamic_html_page_w_links Tx Email_link_and_key one week Download_Expired do / IF HTTP_Req_w_key THEN Send Req_Register_Form IF Submit_Reg_CAPTCHA_form Generate email with key Save key to registration be received, and how they are handled. In Fig. 15.13 , events include entry/ and do/. The entry/ event indicates that this processing should occur once, on entry to the state. The do/ text indicates that this processing should occur whenever the described event occurs: in Fig. 15.13, when a HTTP_Request_with_K ey is received. In other words, with do/ the described processing can occur multiple times; once per event. Figure 15.13 is a state diagram for the state of a Client. The fi rst state, Registered, is entered upon receipt of a validated Submit_Register_CAPTCHA_form. On entry/ to the Registered state, the Register program saves the registration information, and generates the email with associated key for LegalClient. This is transmitted to LegalClient in the Email_Link_and_Key message, which then sets the new state of LegalClient to Downloadable. In the Downloadable state, the Download program validates the key in the database before sending the Dynamic_HTML_page_with_ links. LegalClient stays in the Downloadable state until 1 week expires. Then LegalClient transitions to the Download_Expired state. The single remaining transi- tion that can get LegalClient back to the Downloadable state, is if the Register 274 15 Developing Secure Software program gets another Email_Link_and_Key message from LegalClient. This state diagram ensures legal transactions and processing for any Client object. The last step is the inspection for the Design. Security experts can help fi nd secu- rity fl aws before they are coded and deployed. When evaluating a design, multiple heads are better than one. Consider that multiple heads will be attacking your soft- ware, and they only need to fi nd one strong vulnerability. 15.4 Coding The purpose of the Coding Stage is to develop the programs to implement the design. At this level we are concerned with secure coding techniques. The best way to ensure compliance is to have a documented coding standard and ensure everyone is trained in using the coding standard as well as secure utilities and processes. 15.4.1 Sanitize Input and Output Input sanitization should occur using a bullet-proof standardized utility that has survived the test of time. Attacks can occur at raw input stage, such as buffer over- fl ows and integer or fl oating point overfl ows. In the case of buffer overfl ow, the user enters more characters than an input string buffer allows for, spilling over and affecting nearby data (or worse yet, the program stack) 21. In the case of inte ger or fl oating point overfl ows, users enter numbers large or small enough to overfl ow or underfl ow the bounds of what a computer can store in a normal integer, fl oat, double or other type. This can cause (for example) large numbers to appear small or become negative, and cause negative numbers to become positive 21 . Calculated totals are also subject to underfl ow and overfl ow. Therefore, verify length before reading in data and use an input utility where you specify the maximum buffer size. Data should also be correctly typed and the syntax should be checked. Java and other type-safe languages are safer than C/C++, which allow more fl exibility in type conversions. Any input from an external source should be suspect, including: parameters or arguments, cookies, network packets, environment variables, client request headers/data, query/server results, URL components, e-mail, fi les and data- bases 1 . A second type of input error is data that may appear correct in length, type and syntax, but is not correct. One example is the SQL or OS Injection attack, where SQL or OS statements are appended to form input to attack a database 21 . Standard utilities can help to prevent attacks. OWASP is an organization dedicated to free, open source, secure application code. Their ESAPI (Enterprise Security Applications Programmer Interface) includes a Validation API that defends against masterfully coded attacks.

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.