CS-GY this file and most of the PHPMailer

CS-GY 9163APPLICATION SECURITYSUMEDH KARANDEN13311003 (sak737)&MEGHANA KANAJIN13701524 (mbk410)OSS ASSESSMENTDUE 18TH DECEMBER 201726 PAGESOSS Assessment• The link to the application: https://github.com/PHPMailer/PHPMailerSummary:PHPMailer is a PHP code library that is used to send emails from a webserver and it includes a variety of functions. It can send emails safely using a PHP code and either from your own SMTP server or through any operating system configuration.Introduction:PHPMailer is a one of the most popular code class for sending emails. It has functions like TO, CC, BCC and Reply-to addresses. For OS environments like windows it has an integrated SMTP server to send emails without using a local mail server. It also supports attachments along with inline attachments. It supports UTF-8 content and 8bit, binary, base64 and quoted-printable encodings. It also has various SMTP authentication like LOGIN, PLAIN, CRAM-MD5 and XOAUTH2 mechanisms over SSL and SMTP + STARTTLS transports. It can also validate emails automatically while it can display error messages in 47 languages. We are using the latest PHPMailer version 6.0.2 for assessment and this version works fine with PHP 5.5 and above. We have done an assessment on all the possible vulnerabilities that can used to exploit PHPMailer library.Code Examination:In this section we structure the code. The Project folder has a source folder that contains 4 PHP files.• PHPMailer.php: This code contain the main class PHPMailer{}. All the code arguments are passed to the functions in this file and most of the PHPMailer code depends on the function calls that are present in the script. We can also set different characteristics and properties through this function• OAuth.php: This is the authentication module of the PHPMailer library.• SMTP.php: It implements RFC 821 and it also provides some good utility methods for sending emails to an SMPTP Server.S• POP3.php: This code is normally used for POP-SMTP before authentication.Threat Modelling:Threat Modelling is a common approach to analyze the security threats to an application. It makes sure that an application is built with security kept in mind from the very start. It makes it very convenient to analyze the code by prioritizing the most vulnerable section instead of reviewing the entire code.Following are the steps for Threat Modelling:1. Decompose the Applicationa) Internal Dependenciesb) External Dependenciesc) Entry Pointsd) Assetse) Trust levels2. Determine and rank Threats3. Determine countermeasures and mitigation.Decompose the Application:This step is taken in order to gain the insight of the application like what resources it uses, the external entities it interacts with. It should be a well-structured document that ensures the correctness of the information collected related to its working and dependencies.The important information must include:Application name:PHPMailerApplication Version:6.0.2Description:PHPMailer is a PHP code library that is used to send emails from a webserver and it includes a variety of functions. It can send emails safely using a PHP code and either from your own SMTP server or through any operating system configuration.Document Owner:Sumedh Karande & Meghana KanajiReviewer:Prof. Kelly LumInternal Dependencies:PHP Version: PHPMailer version 6.0.2 uses PHP version 5.5 and above.Loading Classes: It is necessary to import classes for PHP mailer’s script to function. There are two ways to do it and they are as follows:a) Composer: If we use Composer’s autoloader feature we can save a huge amount of time on updates, dependencies and downloads. We wouldn’t have to use “require” every time we want to load a class. If XOAUTH2 authentication is used, it is necessary to use composer.b) Using PHPMailer’s autoloader: To avoid loading SMTP classes explicitly we can use PHP’s autoloader using the following command: require ‘PHPMailerAutoload.php’;DNS Availability: DNS presence is an integral part of sending emails. We need to be sure that we have our DNS up and running by trying to resolve any host name: Example: gmail-smtp-msa.l.google.com.If we get the IP address for the above DNS then we can say that DNS is up and running but sometimes a disabled DNS server can also respond to normal DNS search. So, to make sure that the DNS server is active, we try to ping the server using the following command: ping smtp.gmail.comChecking if it is an email server : We can test if it’s an email server by using Telnet Tool, if it connects then we’ve gotten the right server but if doesn’t connect then we can try different ports. telnet smtp.gmail.com 587Firewall Direction: When we send a request to the mail server we expect a response form the same mail server or a server related to the same company. If we receive a response from some other server that is not related to the email service provider, then there is a possibly that the mails are going through the ISP’s email servers which may cause authentication failures. So, during such times encryption is a must since the emails are going through an unwanted server.External Dependencies:Apart from the code itself there are many other factors that can pose a threat to the user through the application or its resources and dependencies. The main lookout will be the production environment and the requirements of the application. Such information has to be documented perfectly to achieve successful threat analysis of the application. Following is the table for the dependencies and the requirement of the application.DependenciesNameDescriptionOperating SystemThe application can run on UNIX, LINUX, Mac OS, Windows (Doesn’t need local server)Mail ServersSMTP Server or Local HostConnection PrivacyThe connection between the sender and receiver servers will be over a public network.EncryptionIt can use TLS and SSLEntry Points:Every attacker should find an interface to interact with if he wants to tamper with the application and send harmful or undesirable data. There are many entry points in an application and we must make sure that they are kept secure to avoid any kind of security attack.Entry PointsNameDescriptionHTTP PortsData entering the web application through an untrusted sourceHosting BrowserMalicious scripts entering through browsers and executing on the user sideEncryptionFake SSL certificates are often used in such attacks.Assets:Asset is the actual target of the attacker and so your system so if your system has anything confidential then it is bound to be vulnerable to attacks without any security measures taken to protect them. Assets are normally a list of confidential information stored in the database or the data entered by the user that is passed by the application during communication. Following is the vulnerability to our application.AssetsNameDescriptionTrust LevelsUsernameThe username can be leaked if application is vulnerableValid UserPasswordThe password for the account can be compromised for an unsecure applicationValid UserBody ContentThe Body of the email that is sent can contain confidential information.Valid UserDatabase AccessIf the database contains a series of email addresses along with the confidential information of the users.Database Administrator and DeveloperWebsite IntegrityWebsite should be maintained and kept secureWebsite Administrator and DeveloperTrust Levels:Every organization has different access permissions. Trust level is something similar as it gives a specific group of people permissions to access a specific asset. Different assets have different security levels and different access rights, or privileges are required to access them. Following could be the important levels needed to access the information.Trust LevelsNameDescriptionA Legit UserA user who has legit credentials to access an application PHPmailer is a part ofInvalid userA user who is attempting to login using invalid credentialsDatabase AdminHe has read and write access to the databaseWebsite AdminHe can change the interface of the websiteSoftware DeveloperHe has read and write access to the database and can also change the structure of the databaseWeb DeveloperHe can change the structure of website along with its security features.Determine and rank Threats:It is necessary to determine the possible threats to the application and the affected security aspects of the application. Following is a table regarding the different potential threats to the application.Threat ListTypeExamplesSecurity compromisedSpoofingIllegal access using another’s credentialsAuthenticationDOSMaking the service temporarily unavailableAvailabilityTamperingAttempting to change data in the databaseIntegrityInformation DisclosureReading unauthorized dataConfidentialityRepudiationPerforming illegal operations that cannot be held accountable forNon-repudiationElevation of privilegeGaining unauthorized access to compromise a systemAuthorizationVulnerability Analysis:Since this application is purely based on PHP, we have decided to use RIPS scanner and Visual Code Grepper which is a robust static code scanner for PHP as stated in OWASP.I’m using it on my local host using Wamp server. RIPS and Virtual Code Grepper take in files for the entire project and scans it for numerous vulnerabilities. Following are the screenshot for the vulnerability analysis for the PHPMailer library. (From Virtual Code Grepper and RIPS)Virtual Code GrepperRIPS ScannerThere are numerous vulnerabilities in PHPMailer v6.0.2 as mentioned above.? Code execution? Command Execution? Protocol Injection? File Disclosure? File Inclusion? File Manipulation? XSS? HTTP Response Splitting? Possible Flow Control? Reflection InjectionCode-Execution Vulnerability:This attack includes inclusion of malicious code in any type of user data that is not validated. This type of attack is the result of poor IP/OP data validation. The attacker can induce any malicious script that he wants to execute in the target’s machine in the form of user-data. Some websites receive input in the form of strings and these inputs are used as a code to be executed on the server side. If the attacker injects a PHP Code in the input, then data inputs and if such an input is not validated properly then that code will be executed on the server side. This results in the compromise of the server. This kind of attack is attack is also known as a Remote File Inclusion attack since a file can be included in the input from a by a remote user. This kind of vulnerability is one of the top most rated vulnerability.The main causes of this type of vulnerability are as follows:• The most obvious reason for this type of attack is the usage of functions like include(), require(), require_once(). If the input that is untrusted is passed on to these functions as parameters, it can include a malicious file that would execute on the server and wreak Havoc.• Such type of parameters is also vulnerable to Directory Traversals. Using characters like string characters ../ or .. in the input path empowers the attackers to gain access to the file system that is used by the PHP code.• PHP functions like eval() can be used to include a PHP malicious code• Similarly, functions like preg_replace() can be used to include PHP files since it has the ability to accept strings as a parameter• Lack of architectural planning and no stringent laws for access permissions leads to unauthorized access.So, in the source code for PHPMailer we have several code injection vulnerabilities, to be exact 15.The vulnerabilities that are present in the code are due to the functions “preg_replace”.• preg_replace: The combination is $_GET + preg_replace = vulnerability. The attacker just has to provide some PHP malicious code that has to be executed by replacing some or the entire string with the malicious code. So if this is executed before any system call takes is executed the code will be exploited.The following is the screenshot for the preg-replace function without any kind of validation.The following is the screenshot for the major Code Injection vulnerability in the source code.File Inclusion Vulnerability:This vulnerability is similar to code injection vulnerability and it is ranked as one of the more serious threats to a web application and the network architecture. Like code injection, the attacker can run a script on the server side using the user input which is not properly validated.This kind of vulnerability are due to ‘include’ and ‘require’ statements. If common variables like $file are not sanitized before being called by any function like include() and if the web server has total access to the file system then the attacker can include any harmful PHP file that can be executed.These are the other various side effects of the vulnerabilities:• DOS• XSS• Compromise of the Web Server due to a malicious scriptFollowing is the screenshot for the file inclusion vulnerability.There are not many File Inclusion vulnerabilities.HTTP Response Splitting:HTTP Response splitting is a protocol manipulation attack. HTTP response is a type of vulnerability that can be caused due to entry of data from an untrusted source and through a HTTP request. HTTP Response splitting vulnerability is not an attack but a means to attack. The data is normally included in an HTTP Response Header without checking for harmful characters.The attacker will purposely mount the data in the HTTP request message and then the application will use that data in the HTTP Response header. He will normally set the HTTP Header value containing CR/LF which splits the HTTP response. This empowers the attacker to control the header contents along with the body contents of the message. Not just the body contents but the attacker will also get the ability to send extra responses that are totally under their control.Since HTML is a stateless language the browser will never check for any kind of odd behavior. The problem with this attack is that the attacker can include anything in the header since it is not checked for any malicious code.It can lead to the following consequences:• The user can be redirected to a different host or a webpage• The script induced by the attacker can steal browser’s stored Cookie information.• It can also mimic a webpage that prompts the user to enter his credentials.• Web cache poisoning can take place leading to site defacement.• Website Hijacking• XSS AttacksThis is the header vulnerability in the PHPMailer source code.The “header” function can be induced with a vulnerable URL that could be sent to the user to mislead him.Only 1 HTML Response Splitting Vulnerability in the PHPMailer Source Code.Cross Site Scripting:Cross site Scripting is a type of attack vector where a harmful code is injected in a web application. It is different from other injection attacks like SQL injection or file inclusion attack. The attack will not directly attack the application, but it will pose a danger to the user of the application. It can manipulate a legitimate website forcing the user to submit confidential data. User accounts can be compromised due to such an attack. It can also run Trojan programs on the user’s system. XSS attack can steal session cookie information and this might lead to an attacker impersonating a legit user and taking undue advantage of this situation.Causes of the XSS attacks could be as follows:• Scripts injected directly into applications by the attacker causing the users to execute it every time they visit the website.• Or malicious data being sent to the website user without examining for the malicious contents.The following is the flowchart for stealing a session cookie using XSS attack.Types of XSS attacks:• Stored XSS attack: The vulnerable script is already stored on the servers and every time a user visits the website or fetches data from the database, he receives the malicious script.• Reflected XSS Attack: This type of attack is not persistent that it is not stored on the servers all the time, but it only activates in the form of a link or an error message.PHPMailer Version 6.0.2 has a lot of XSS Vulnerabilities to be exact 16.In the source code there are lot of echo() commands where the application will reflect data to the screen numerous times with no proper sanitization or validation and such a variable can be a vulnerability since we don’t know if the variable is user controlled or not.Reflection InjectionReflection is a normal coding practice where programmers can treat class definitions as objects. This enables the programmers to view and modify class variables on the go. But it is possible that if an untrusted input from the user is used to manipulate the object in the code, it is possible that reflection injection can take place. The execution path will change, and unwanted functions or classes will be called during the execution of the code. The attacker will gain access to the functions and he may view or modify them to a certain extent.Probable causes:• Poor validation of user input• Calling functions and libraries based on user or external input• Validating library on the basis of their namesConsequences• Malicious code being executed.• Security will be bypassed.PHPMailer has 8 such vulnerabilities:In PHPMailer, the call_user_function is a user tainted data and it is used as a function name. This may result into abnormal behavior of the application.Mitigation techniquesCross Site Scripting:As we have seen that most the XSS vulnerabilities originate through the echocommands that reflect to the screen with no proper sanitization. We can mitigateXSS in such cases by applying ‘htmlspecialchars’ to the data. It will help covert anyspecial characters into HTML entities. But the only issue in this is that, one mustremember to apply ‘htmlspecialchars’ every time. Another way to mitigate this bychoosing a secure template engine that has HTML escaping by default and allHTML tags should pass through the template engine. Also by ensuring that alluntrusted data based on HTML context that the data would be placed to shouldbe properly escaped. Auto-sanitization libraries like OWASP’s AntiSamyor the JavaHTML Sanitizer Project can be considered for rich content. To defend against XSSacross the entire site one can consider Content Security Policy (CSP). Using awhitelist model will prevent adding untrusted data to other HTML slots where diddoes not belong to. It will basically deny everything that is not specificallyallowed.HTTP Response Splitting:HTTP Response Splitting can be avoided by validation of the CR/LF in the HTTP Headers. Any CR/LF values in the HTTP Response should be trimmed off to avoid such kind of attacks. Application level firewalls can be a good option for stateful filtering of data and data fields in the http headers. However, filtering seems to be a good option, sometimes it’s not good enough since we cannot reject or discard data where the user is prompted to input content that includes special characters and sequences. Then it becomes important to parse and validate the input for CRLF rn %0f%0a or any other form of encoding. Lastly while handling undiagnosed characters, sequences or scripts we should use mechanisms that transform the stream of encoded characters into a stream of special sequence characters that cannot be executed on the Server side.File Inclusion Mitigation:To minimize the risk of file inclusion mitigation it necessary to properly validateand sanitize inputs. But not all user inputs can be completely sanitized. It ispreferable to sanitize the user supplied or controlled inputs which can beGET/POST and, URL parameters, COOKIE values, HTTP Header values. This canalso be done by checking the input fields against a whitelist (allowed charactersets) instead of maintaining a blacklist as the attackers can choose to supply inputin a different format such as encoded or hexadecimal. Output validationmechanisms should be applied on the server end. Also by maintaining a whitelistfor allowable file types like PDF, DOC, PNG etc with also restricting the file sizeswill mitigate the risk of file inclusion attack.Reflection InjectionReflection injection can be avoided by validating the user input. A vigorous whitelist style input checking methodology should be implemented. To maintain web-surfing integrity and confidentiality, certificates signed by root authority should be used. The class should be loaded only if it passes the validation checks.ConclusionAfter analyzing the code of PHP Mailer for vulnerabilities, we found that it is susceptible to many attacks and has many loopholes which makes the application so vulnerable. With the help of RIPS vulnerability assessment tool and Virtual Code Gripper we could find the vulnerabilities and analyze them much more efficiently and provide the possible mitigation techniques. Overall the application is not secure.Reference• https://www.owasp.org/index.php/Application_Threat_Modeling• https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting• http://www.thegeekstuff.com/2012/02/xss-attack-examples/?utm_source=tuicool• http://searchsoftwarequality.techtarget.com/answer/How-to-prevent-HTTP-response-splitting• https://www.owasp.org/index.php/Code_Injection• https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)• https://paragonie.com/blog/2015/06/preventing-xss-vulnerabilities-in-php-everything-you-need-know• https://vulnerabilities.teammentor.net/article/0089dded-bd3d-4513-b479-624629634b4a