Alerts This Week
Warning Icon 1 697
Alerts This Week
Warning Icon 1 697

Stay Ahead With Linux Security Features

Filter Icon Refine features
X Clear Filters
X Clear Filters
View More

Get the latest News and Insights

Get the latest Linux and open source security news straight to your inbox.

Community Poll

What got you started with Linux?

No answer selected. Please try again.
Please select either existing option or enter your own, however not both.
Please select minimum {0} answer(s).
Please select maximum {0} answer(s).
/main-polls/150-what-got-you-started-with-linux?task=poll.vote&format=json
150
radio
0
[{"id":483,"title":"Self-taught through trial and error","votes":546,"type":"x","order":1,"pct":78.45,"resources":[]},{"id":484,"title":"Formal training or courses","votes":30,"type":"x","order":2,"pct":4.31,"resources":[]},{"id":485,"title":"A job that required it","votes":34,"type":"x","order":3,"pct":4.89,"resources":[]},{"id":486,"title":"Other","votes":86,"type":"x","order":4,"pct":12.36,"resources":[]}] ["#ff5b00","#4ac0f2","#b80028","#eef66c","#60bb22","#b96a9a","#62c2cc"] ["rgba(255,91,0,0.7)","rgba(74,192,242,0.7)","rgba(184,0,40,0.7)","rgba(238,246,108,0.7)","rgba(96,187,34,0.7)","rgba(185,106,154,0.7)","rgba(98,194,204,0.7)"] 350
bottom 200
Loading...

Explore Latest Linux Security features

We found 0 articles for you...
102

Effective Strategies to Secure PHP on Linux Web Servers for Safety

Running PHP on a Linux web server is a prerequisite for the use of many popular applications such as Wordpress, Joomla and Drupal. Linux administrators and web developers must approach PHP with caution, as new vulnerabilities in poorly written and implemented PHP code are abundant and dangerous. . In a recent security incident, hackers were able to add a backdoor to the PHP source code . Although the backdoor mechanism was discovered before it made it into production, the incident serves as the latest reminder of the importance of prioritizing PHP security. PHP security is inextricably tied to web server security. Because the popular open-source server-side scripting language is often paired with MySQL, PHP compromise can mean a compromise of the accompanying MySQL database, as well as any web applications running on the web server. This article will examine how you can configure and run PHP securely to mitigate the risk of attacks and compromise, secure web applications, protect user privacy and maintain a secure and properly functioning Linux web server. PHP Vulnerabilities Carry Great Risk for Admins Vulnerabilities in PHP code are a prevalent and serious threat to web server administrators and web application developers. These flaws are often introduced when developers are writing code, either due to a mistake or the inability to anticipate malicious hackers’ ever-evolving techniques. A plethora of vulnerabilities exist in the PHP core - with new security bugs being discovered each month. On March 28, 2021, hackers breached the internal PHP Git repository and inserted a backdoor into the PHP source code. Luckily, the malicious code was discovered by Michael Voříšek before it made it into production, and the hack led the PHP team to move source code management operations from its internal Git server to its official GitHub account, which will serve as PHP’s official Git repository going forward. In another PHP security incident that occurred less than three years ago and has yetto be explained today, hackers compromised the official PHP PEAR extensions system website and hosted a backdoored version of the PHP PEAR package manager for almost six months. PHP vulnerabilities can be exploited by attackers to spread malware & take control of hundreds of thousands of web servers in botnets. In one such instance this past year, the infamous hackers-for-hire group DarkCrewFriends resurfaced with a dangerous botnet strategy exploiting an unrestricted file upload vulnerability to compromise PHP servers running websites. In another malicious campaign a year prior, the Neutrino botnet was discovered hijacking servers by taking over other hackers’ PHP and Java web shells to install a cryptocurrency-mining malware . To help you better understand the threats that your web servers and web applications face, let’s take a look at some of the most notorious types of PHP vulnerabilities. A Quick Look at the Most Common & Dangerous Types of PHP Vulnerabilities Threatening Your Web Servers Remote Code Execution (RCE) In this type of vulnerability, a bug in a PHP application accepts user input and evaluates it as PHP code, enabling an attacker to upload code to a website and execute it. This could, for example, allow a malicious actor to tell the website to create a new file containing code that gives him or her full access to the compromised website. RCE vulnerabilities are very serious because they are easy to exploit and grant an attacker full access when exploited. SQL Injection (SQLi) SQL injection (SQLi) occurs when a hacker is able to send instructions to a database and the database executes those instructions. This type of vulnerability occurs when a PHP developer takes input from a website visitor and passes it to the database without reviewing it for malicious code. SQLi vulnerabilities are very serious because they are easy to exploit and often grant full access immediately. Cross-Site Scripting (XSS) Cross-site scripting (XSS) takes place when an attacker causesmalicious code to load in a website visitor’s browser and execute. This code often steals user cookies to grant the attacker administrative level access or performs functions as the user to grant additional access. Cross-site Request Forgery (CSRF) Cross-site request forgery (CSRF) describes a scenario in which a user is tricked into issuing a request that is not in his or her best interest. For instance, an attacker may create a link and trick an administrator into clicking on that link, causing the site to take a certain action such as creating a new ‘admin’ user with a known password. This critical WordPress vulnerability which was fixed in November of 2020 left servers vulnerable to a variety of attacks including cross-site request forgery and cross-site scripting. Authentication Bypass This type of vulnerability is introduced through incorrect validation that a site visitor has the access level required to take a certain action. For example, a developer may wrongly use a function called ‘is_admin()’ - which is designed to indicate if someone is viewing an admin page - to try to validate that someone is an administrator, mistakenly granting non-admin users access to features that only administrators should have access to. PHP Object Injection PHP object injection is a complex attack that occurs when a PHP application takes user input and passes it to the unserialize() function, which takes a stored object and turns it into an object in memory. This type of vulnerability occurs when a developer allows user input to be used in an unsafe way within a PHP application. The unserialize() function must be approached with extreme caution, as this function is commonly exploited by attackers. PHP 7 has includes a new filtered unserialize feature designed to mitigate the impact of code injection vulnerabilities by requiring that developers specify classes that are safe to unserialize. However, it is critical to keep in mind that even with this improvement, passing untrusted input tounserialize() is never safe. Remote File Inclusion (RFI) & Local File Inclusion (LFI) Remote file inclusion (RFI) and local file inclusion (LFI) take place when a PHP application takes user input and passes it to a function designed to load a file. The inclusion of a remote file in a URL is known as Remote File Inclusion (RFI) while the inclusion of a local file in a URL is known as Local File Inclusion (LFI). LFI is often the method an attacker employs to gain access to a WordPress website’s wp-config.php file. Source Code Revelation This type of vulnerability has to do with people being able to see the names and content of files that they shouldn’t be able to view due to the breakdown of a web server’s configuration. The code revealed in this type of vulnerability may list accessible configuration files or contain sensitive information such as database credentials. Session Hijacking Session hijacking occurs when a malicious actor steals a user’s session ID. When a session is set up between a client and a web server, PHP will store the session ID in a cookie on the client side. Sending the ID with the page request provides access to this confidential information, potentially resulting in session hijacking. Session IDs are commonly stolen via XSS attacks, and can also be vulnerable server-side through the use of hosting services that store session information in globally accessible directories. These vulnerabilities in Apache versions 2.4.33-1 and prior - which have since been fixed upstream - left web servers susceptible to session hijacking and an array of other dangerous exploits. Directory Traversal Directory traversal looks for vulnerable websites and causes files to be accessed that the owner did not plan on making publicly accessible. It is also referred to as the ../ (dot, dot, slash) attack, the climbing attack, or the backtracking attack. Tracking advisories is critical in preventing all of these prevalent and serious types of PHP vulnerabilities. Subscribing to ourweekly Linux Advisory Watch newsletter is an easy, convenient way to stay up-to-date on the latest advisories and updates issues by your Linux distro. In addition to tracking advisories, we recommend that web server administrators implement the ModSecurity web application firewall (WAF), which can provide another line of defense against the attacks listed above. The open-source, cross platform WAF has a robust event-based programming language and allows for HTTP traffic monitoring, logging and real-time analysis. Best Practices for Improving PHP Security The majority of attacks on Linux web servers can be attributed to misconfigurations and poor administration. Thus, it is essential that administrators configure their web servers to be as secure as is practical within the construct of their environment. The Open Web Application Security Project (OWASP) , a nonprofit fo undation we trust and admire that works to improve the security of software through community-led open-source projects, suggests that administrators and developers implement these secure PHP configuration recommendations to protect their web servers against dangerous PHP vulnerabilities and prevent attacks. LinuxSecurity.com PHP security experts Brittany Day and Dave Wreski have additional tips and advice for improving PHP security, which we will explore in this section. Our Top PHP Security Tips & Advice Update Your PHP Version and Modules Regularly It is critically important that administrators and developers update their PHP version and modules regularly. With the support of the open-source community behind PHP, patches and bug fixes for vulnerabilities are released frequently, and newer versions of PHP and its modules often contain mitigations for known security issues that can be exploited by malicious hackers. As of January, 2022, the stable release for PHP is version 8.1.1 , from December 2021. It should be noted that when PHP is being used in a hosting environment, users may not be able to update their PHPversion number. In such scenarios, users must be especially careful and vigilant. They should also explore potential workarounds and demand that their hosting provider update PHP at the earliest opportunity. Restrict PHP Information Leakage The unfortunate reality is that it is common for platforms to leak sensitive information - and PHP is no exception. For example, PHP releases versions and the fact that it is installed on a server through the expose_php directive. To prevent the leakage of this sensitive data, administrators should set this directive to off in /etc/php.d/security.ini. expose_php=Off Control File System Access PHP can access files by default via the open_basedir directive using functions like fopen(). To control file access and prevent security issues, the open_basedir directive should always be set to the /var/www/html directory. open_basedir="/var/www/html/" Disable Remote Code Execution (RCE) In PHP, remote code execution is enabled by default. The "allow_url_fopen" directive allows functions including require, include, or URL-aware fopen wrappers to obtain direct access to PHP files. Remote access can be obtained using the HTTP and FTP protocols, leaving system defenseless against code injection vulnerabilities. To protect against these types of exploits, administrators should disable remote code execution by setting the "allow_url_fopen" directive to "Off". Disable Dangerous PHP Functions & Get Rid of Unnecessary Modules PHP comes with a selection of useful functions, but is also plagued with functions that can be exploited by attackers and should be disabled. To disable these dangerous functions, administrators must edit the php.ini file. In this file, they should find the disable_functions directive and disable the dangerous functions in it using: disable_function =exec,passthru, shell_exec,system,proc_open, popen,curl_exec, curl_multi_exec,parse_ini_file,show_source PHP also comes with an array of excellent modules; however, not all modules arerequired for every project. In PHP, all the extension modules found in /etc/php.d/ directory are loaded by default. Administrators should get rid of all modules that are not currently required, as doing so will improve both security and performance. To view available PHP modules, use the command: php -m Once you have accessed this list, you will be able to get rid of all unnecessary modules. To enable or disable a particular module, simply find the configuration file in the /etc/php.d/ directory and comment the module name. Scan PHP Scripts & Audit PHP Code for Security Vulnerabilities Scanning PHP scripts and auditing PHP code is essential in identifying and fixing potential security vulnerabilities before they are exploited by attackers. There is a plethora of excellent free and open-source tools and utilities available to assist Linux users in this process. Here are some of our favorites: Phpcs-security-audit is a set of customizable PHP_CodeSniffer rules that identifies security vulnerabilities and weaknesses in PHP code. The tool checks for CVE issues and security adviso ries related to the CMS/framework, enabling administrators to follow the versioning o f components during static code analysis. SensioLabs Security Checker is a command line tool that checks if an application uses dependencies with known security vulnerabilities using the Security Check Web service and the Security Advisories Database . Suhosin is an advanced security system for PHP installations designed to protect servers and users from known and unknown flaws in PHP applications and the PHP core. PHP Malware Finder (PMF) is a self-hosted solution designed to help administrators and developers identify potentially malicious code in files. Detection is performed by crawling the filesystem and t esting files against a set of YARA rules. RIPS is a PHP static code analysis tool that is integrated through the development lifecycle to identify security issues in real-time. The toolsupports 15 different types of vulnerabilities, and is able to scan PHP applications very rapidly for PHP-specific vulnerabilities. SonarPHP is a static code analyzer that uses pattern matching and data fl ow techniques to identify vulnerabilities in PHP code. It is used as an extension for the SonarQube platform and features over 200 rules, along with support of custom rules. Dependency-check-cli is a great tool from OWASP that uses dependency-check-core to detect publicly disclosed vulnerabilities associated with the scanned project dependencies. The tool will generate a report listing the dependency, any identified Common Platform Enumeration (CPE) identifiers, and the associated Common Vulnerability and Exposure (CVE) entries. PHP Secure Configuration Checker is a single file that checks a current PHP configuration for potential security flaws. It is user-friendly and has almost no dependencies. The Bottom Line PHP offers web server administrators and web application developers an array of valuable functions and modules paired with robust security inside out - a characteristic that can largely be attributed to the support that PHP receives from the vibrant, global open-source community. However, PHP security is ultimately in the hands of the administrator. He or she must make sure code is written properly, the proper configurations have been made and that the best practices covered in this article are being implemented. PHP security should be a primary concern for administrators and developers, as it is inextricably tied to the security of a web server as a whole. Sound PHP security can help mitigate the risk of attacks and compromise, secure web applications, protect user privacy and maintain a secure and properly functioning Linux web server. Do you have questions about PHP security or want to discuss the topic in more depth? Let’s chat! Connect with us on social media: Twitter | Facebook . In a recent security incident, hackers were able to add a backdoor tothe PHP source code. Although . running, linux, server, prerequisite, popular, applications. . Brittany Day

Calendar 2 Jan 02, 2022 User Avatar Brittany Day
102

Safeguarding Your Apache Web Server: Preventing Data Leaks and Errors

Over the next couple of weeks and months, LinuxSecurity editors and contributors will be writing a series on Linux Web Server Security. This week, we’re summarizing the risks Linux administrators face when trying to secure their systems, as well as outlining the first steps that should be taken toward ensuring that your systems are secure. This series will dive deeper into topics including preventing information leakage, firewall considerations, protecting file and directory permissions, securely running PHP applications, monitoring logs and how to verify the security of a Linux server. . Much of this information originated from the Linux Security HOWTO, a comprehensive resource written by LinuxSecurity.com Founder Dave Wreski more than twenty years ago to offer the Linux community a place to start with securing their systems before much of the existing open source security documentation was created, now updated to reflect modern security principles and practices. With the growing prevalence of Linux web servers globally, security is often touted as a strength of the platform for such a purpose. Due to the transparency of Linux source code, vulnerabilities are identified and fixed very rapidly and, as a result, Linux generally fares better than alternative proprietary OSes when it comes to security . However, a Linux-based web server is only as secure as its configuration, and the unfortunate reality is that often many Linux servers are quite vulnerable to compromise due to misconfigurations and poor administration. While specific configurations vary wildly due to factors such as environment and specific use cases, there are various universal steps to securing a Linux web server that can be taken to ensure basic security considerations are in place. Misconfigured Servers Carry Great Risk A selection of serious security risks are associated with the compromise of a web server, including the use of the hijacked server as a source of malware or the creation of a spam-sending relay, among othermalicious activities. Even if the operating system and packages are fully patched with security updates, a misconfigured server can still be compromised. Server Security: A Fundamental, And Often Neglected, Aspect of System Hardening Many aspects of a system’s overall security are contingent upon server security. For instance, securing web applications begins with configuring the server itself strictly with security in mind. It is common for server owners to deploy various layers of security to react in real-time to hacking attempts and threats for HTTP requests. However, securing the server as a whole and any running services to the highest level is the first fundamental step to mitigating the risk of being hacked or compromised. With the abundance of malware being installed into web applications hosted on Linux-based servers, it is clear that many servers are configured with little or no security in mind. For users of personal blogs, a compromise is often both an embarrassment and an inconvenience. However, for small and large businesses alike, having your company’s site or blog serving up malware due to a compromise often results in a significant loss of business and creates a very poor reflection of your company's IT services on the public, as well as on potential clients. As you can see, server security is of utmost importance - and should be a top priority for all server owners and system administrators. That being said, let’s take a look at some risks administrators face, considerations that should be made and steps that can be taken improve the security of your Linux web servers. This series will provide general information that can be applied to improve the security of any Linux server, but will focus predominantly on securing an Apache web server. Information Leakage Information leakage, or the actions of revealing information to an unauthorized party, carries severe consequences for both businesses and individuals including data compromise, reputation damage and financialloss. Information leakage can be the result of either intentional actions such as those taken by malicious insiders, or unintentional actions such as employee negligence. Luckily, there are various measures that system administrators can take to secure web servers against this serious threat. The first and relatively trivial configuration changes that should be made to secure a Linux server are to disable any potential sources of information leakage. All Linux distributions have poor default configurations in regards to preventing information leakage. As a result, it is imperative that the correct manual configurations are made in order to protect sensitive data. Potential sources of information leakage that Apache web server administrators should disable include the directory browsing listing, the ETag header, the Trace HTTP request and SSL v2/v3. Administrators should also ensure that the server version banner has been removed. Let’s take a closer look at these configurations and how they can be made. Remove Server Version Banner Removing the server version banner is one of the first configurations that Apache server administrators should consider to prevent information leakage. It is critical not to expose what web server version you are using, as this information can be exploited by malicious hackers. The Apache default configuration shows Apache Version and OS type. To hide this information from unauthorized parties. Edit your httpd.conf config file to add or modify the following directives if they don’t already exist. ServerTokens Prod ServerSignature Off Save and exit, then restart apache. Disable Directory Browser Listing It is critical that Apache server administrators disable directory browser listing to prevent visitors from being able to see the files and folders listed under root or subdirectory. When directory browser listing is disabled on a server, a forbidden error message will be displayed when a user attempts to access this information. To disabledirectory browser listing, add -Indexes to the Options directive for the required directory. Edit the config file corresponding with the virtual domain you’re configuring and add “Options -Indexes” to the Directory section corresponding with the directory for which you wish to disable indexes. Options -Indexes Be sure to restart apache after you’ve saved the file. If you don't have administrator access to the system or just want to easily manage directory listing on a per-directory basis, you can use the above Options -Indexes directive in the htaccess file corresponding with the directory, too. Disable the ETag Header The ETag header should always be disabled, as it allows remote attackers to obtain sensitive information such as inode number, multipart MIME boundary and child processes. To mitigate the risk of potential exploits associated with the compromise of this sensitive information, edit your apache config and add the following Header unset ETag FileETag None Restart apache for the change to take effect. Disable Trace HTTP Request The Trace HTTP method is enabled by default in an Apache web server. Failing to disable this HTTP request can provide malicious hackers with access to cookie information, and can also result in a Cross Site Tracing attack. To disable the TRACE request so all such requests are blocked with 405 Method Not Allowed, edit your apache config and add the following: TraceEnable off Restart apache for the change to take effect. Disable SSL v2 & v3 SSL v2 and v3 are ridden with security flaws, and must be disabled to prevent Man-in-the-Middle attacks which can result in data tampering or theft. Disabling SSL v2 and v3 is also essential to PCI compliance and penetration testing. To configure an Apache web server to accept only the latest versions of TLS and reject all SSL v2/v3 connection requests, edit the ssl.conf file in your apache config directory and add the following: SSLProtocol all -SSLv2 -SSLv3 Once you have saved your config and restarted, you should verify your SSL configuration . Review Additional Running Services It is critical to review and disable any services running on the host that are not required. Many administrators run a 'web server' and unknowingly are running a host of other services simultaneously, which all need to be carefully reviewed and secured. If other services are running on the same web server, the banner for those services should be edited to remove any broadcast of the version number or other non-required information that could potentially be leaked. Firewall Considerations All Linux servers should make use of the built-in software firewall which, in most cases, is iptables. Iptables makes a very easy command line interface for managing the firewall - there is no need to write intricate iptables scripts. Debian and Ubuntu incorporate an application called ufw which is a command line interface for iptables. Using ufw, simple commands can open or close ports, without the user being an iptables wizard. Regardless of whether or not additional firewalls are in place, the host internal software firewall should always be enabled. Only allowed services should be able to communicate in and out of specified ports and network interfaces. Consider if a company's perimeter firewall is compromised. In this case, the only layer of defense would be the software firewall on the host. Similarly, if the host is compromised through a web application, restricting access to network traffic of that host will provide some protection against island hopping or other intrusions. ModSecurity is an excellent free and open-source web application firewall that can be used with Apache. You can download ModSecurity download . Installation, configuration and troubleshooting documentation is available on Github . Multiple other great free and open-source firewalls, which you can learn about in this TechRadar.pro article , are also available to Linux users. Disabling ICMP– Not Required Administrators will often disable or filter ICMP requests, though doing this has no security benefits. In the case of something like DNS, ICMP requests are actually used in the DNS spec to query if a server is available before sending the DNS request. ICMP replies are extremely beneficial to web servers as well and can serve in troubleshooting a web server that appears to not be responding to HTTP requests. The threat of a ping flood is minimal today. Unless the attacker has considerably larger network bandwidth than the target, the flood attempt is going to cause little effect. Ping echo replies take very little CPU from the target to reply to - making the threat of a ping flood a bit like throwing many small pebbles in an attempt to take down a brick wall. This is why the majority of modern DoS attacks focus on HTTP requests instead of ICMP - driving up CPU and memory usage from the web server is far more effective to execute. In short, there is no reason to disable ICMP. Permissions File and directory permissions in Linux is often a confusing topic which leads to differing views, especially in the case of web directories and files. The worst advice, which should never be followed, is to change files or folders to 777. This allows anyone in the world to execute or write to your server. The best example of this is rogue WordPress plugins that malicious hackers push to servers via a simple HTTP POST command. If directory permissions are 777, anyone can read, write or execute anything in that directory - and anyone can post malicious code. Apart from the read/write/execute permissions, ownership permission also needs attention. The web directory on your server should not be owned by the Apache user. A regular user should be the owner of the web directory, and the group should be the Apache user. Even if the read/write/execute permissions are accurate, a rogue or runaway process or PHP application can then have full access to make changes to your entire web directory. Unfortunately,this ownership change can make the push button upgrades for Drupal and WordPress problematic. The binary and configuration directory permissions must also be protected. In Apache, the permission for binary and configuration is 755 by default, meaning that any user can access the conf and bin folder and view the configuration of the server. Administrators should consider disallowing access to the main config files by restricting ownership and file permissions on these files. PHP Applications Running PHP on a Linux server is required for many popular applications such as Drupal and WordPress, among others. New vulnerabilities are being found in not only poorly written PHP code, but in the language itself, at an alarming rate. Since PHP is often paired with MySQL, a PHP compromise can mean a compromise of the accompanying MySQL database for the web server. Hence, it is critical to be on top of any PHP software or plugin updates. Do not install or use PHP code from unknown sources. For blogging software, minimize the number of plugins or extensions in use. If a plugin or add-on is not activated or in use for the blog or website, remove the unused files from the server. Ensure that 404 pages for the server do not provide any extraneous information and do not interpret what was put in the URL bar. Visit a random 404 page on the web server as a test. The resulting 404 page should only provide a generic 'Sorry, that page was not found', and should not try to interpret or relay results that the user placed in the URL bar. 404 pages that allow user input manipulation are an entry point for attackers to craft XSS and other malicious attempts. Learn about other PHP security best practices in this NixCraft tutorial. Monitoring Logs Logs are a critical part of monitoring the security of a web server. Many Linux distributions offer tools for automating log monitoring. The Logwatch application sends a daily email report of all of the logs on the server to inform on varying log entries such as thenumber of emails sent, potential web attackers, SSH attempts and IPs causing errors in logs. In a large corporate environment it is common to send logwatch emails along with other mail directed to the root user (cron errors and other system messages) to a single company email list. Administrators in the company then subscribe to that single email list to stay informed of any alarming notifications in various servers' logs for the company. Learn how to install and use Logwatch in this TechRepublic tutorial . Conclusion Linux is a popular operating system for web servers and web hosting, and is unfortunately also becoming an increasingly popular target for compromise - mainly due to misconfigurations and poor administration. Strict security considerations are needed to ensure that attacks and attempts to insert malicious code are avoided. Taking care to reduce information leakage, restrict permissions, keep PHP and other applications updated, and monitor all server logs will help Linux server administrators stay on top of potential attack vectors and avoid compromise. Got a tip for securing a Linux web server that hasn’t been addressed in this article? Please let us know in the Comments section below and we’ll include it here. Next week we will take a deeper dive into preventing information leakage. . Much of this information originated from the Linux Security HOWTO, a comprehensive resource written . couple, weeks, months, linuxsecurity, editors, contributors, writing. . Brittany Day

Calendar 2 Sep 21, 2020 User Avatar Brittany Day
102

Securing Apache Web Server: Effective Logging And Access Control

This is the second installation of a 3 part article on LAMP (Linux Apache MySQL PHP). Apache is the most widely used HTTP-server in the world today. . It is also the most used web server for a Linux system. A web server like Apache, in its simplest fun ction, is software that displays and serves HTML pages hosted on a server to a client browser that understands the HTML code. You must always be careful in knowing the web services that run. Run: [root@aquarius /# netstat -a | grep LISTEN to scan your ports. A secure site should have only ports 22 (SSH), 80 (HTTP) and 443 (SSL) exposed. Log files are another useful utility for monitoring attacks on your server. One must set up a centarlised secure log server so that hackers will not be able to remov e traces of their intrusion so easily. Various logfile analyzers like analog, webaliser help in keeping track of the web server access by people. By installing and configuring a good logfile analyser one can know details about the total traffic across the network and the various files and directories accessed,mod ified,deleted or any such activity. It will also tell you the pages that were visited and by whom. In addition to that are all the resources that are busy with respect to apache. Maintaining Logfiels is such an important task that one must follow in order to keep track of his system's activities.Apache web server logfiles are httpd.log,error _log and access_log These files log all the attempts by a user in order to perform a task,it can be an attempt for compromising the system The daemon syslog must be enabled which is responsible for logging activity. Care must be taken that logging is on for mail and auth privileges in /etc/syslog.conf In typical operation, Apache is started by the root user, and it switches to the user defined by the User directive to serve hits. As is the case with any command th at root executes, you must take care that it is protected from modification bynon-root users. Not only must the files themselves be writeable only by root, but so mu st the directories, and parents of all directories. For example, if you choose to place ServerRoot in /usr/local/apache then it is suggested that you create that directory as root, with commands like these: mkdir /usr/local/apache cd /usr/local/apache mkdir bin conf logs chown 0 . bin conf logs chgrp 0 . bin conf logs chmod 755 . bin conf logs It is assumed that /, /usr, and /usr/local are only modifiable by root. When you install the httpd executable, you should ensure that it is similarly protected: cp httpd /usr/local/apache/bin chown 0 /usr/local/apache/bin/httpd chgrp 0 /usr/local/apache/bin/httpd chmod 511 /usr/local/apache/bin/httpd You can create an htdocs subdirectory which is modifiable by other users -- since root never executes any files out of there, and shouldn't be creating files in there. If you allow non-root users to modify any files that root either executes or writes on then you open your system to rootcompromises. For example, someone could repla ce the httpd binary so that the next time you start it, it will execute some arbitrary code. If the logs directory is writeable (by a non-root user), someone could repl ace a log file with a symlink to some other system file, and then root might overwrite that file with arbitrary data. If the log files themselves are writeable (by a no n-root user), then someone may be able to overwrite the log itself with bogus data. Server Side Includes Server Side Includes (SSI) present a server administrator with several potential security risks. The first risk is the increased load on the server. All SSI-enabled files have to be parsed by Apache, whether or not there are any SSI directives included within the f iles. While this load increase is minor, in a shared server environment it can become significant.SSI files also pose the same risksthat are associated with CGI script s in general. Using the "exec cmd" element,SSI-enabled files can execute any CGI script or program under the permissions of the user and group Apache runs as, as config ured in httpd.conf. That should definitely give server administrators pause. There are ways to enhance the security of SSI files while still taking advantage of the benefits they provide. To isolate the damage a wayward SSI file can cause, a server administrator can enable suexec as described in the CGI in General section. Enabling SSI for files with .html or .htm extensions can be dangerous. This is especially true in a shared, or high traffic, server environment. SSI-enabled files shoul d have a separate extension, such as the conventional .shtml. This helps keep server load at a minimum and allows for easier management of risk. Another solution is to disable the ability to run scripts and programs from SSI pages. To do this replace Includes with IncludesNOEXEC in the Options directive. Note that users may still use to execute CGI scripts if these scripts are in directories desginated by a ScriptAlias directive. Non Script Aliased CGI Allowing users to execute CGI scripts in any directory should only be considered if: You trust your users not to write scripts which will deliberately or accidentally expose your system to an attack. You consider security at your site to be so feeble in other areas, as to make one more potential hole irrelevant. You have no users, and nobody ever visits your server. Script Aliased CGI Limiting CGI to special directories gives the admin control over what goes into those directories. This is inevitably more secure than non script aliased CGI, but only if users with write access to the directories are trusted or the admin is willing to test each new CGI script/program for potential security holes. Most sites choose this option over the non script aliased CGI approach. CGI in General Always remember that youmust trust the writers of the CGI script/programs or your ability to spot potential security holes in CGI, whether they were deliberate or accidental. All the CGI scripts will run as the same user, so they have potential to conflict (accidentally or deliberately) with other scripts e.g. User A hates User B, so he writes a script to trash User B's CGI database. One program which can be used to allow scripts to run as different users is suEXEC which is included with Apache as of 1. 2 and is called from special hooks in the Apache server code. Another popular way of doing this is with CGIWrap. Protecting System Settings To run a really tight ship, you'll want to stop users from setting up .htaccess files which can override security features you've configured. Here's one way to do it. In the server configuration file, put AllowOverride None This prevents the use of .htaccess files in all directories apart from those specifically enabled. Protect Server Files by Default One aspect of Apache which is occasionally misunderstood is the feature of default access. That is, unless you take steps to change it, if the server can find its wa y to a file through normal URL mapping rules, it can serve it to clients. For instance, consider the following example: # cd /; ln -s / public_html If a client accessed , this would allow them to walk through the entire filesystem. To work around this, add the following block to your serve r's configuration: Order Deny,Allow Deny from all This will forbid default access to filesystem locations. Add appropriate blocks to allow access only in those areas you wish. For example, Order Deny,Allow Allow from all Order Deny,Allow Allow from all Pay particular attention to the interactions of and directives; for instance, even if denies access, a directivemight overturn it. htpasswd authentication With apache,you can secure your files and directories in a more simplest way by using any of the authentication methods like basic,digest etc. By using htpasswd one can allow only specific users to access a particular file or a directory like this. Create a file called users and list all the names of the users u want to give access and place it in a location like /etc/httpd/ Use the following command: root# htpasswd -cm /etc/httpd/users username -c is only used the first time For other users you need not use the -c option type the password on prompt You can notice the file users containing the passwords encrypted Now add this in httpd.conf file at the end o fthe file AuthType "Basic" AuthUserFile /etc/httpd/users AuthName "Authorisation Required" require valid-user Whenever a user tries to access /var/www/html/test directory he will be prompted for the username and password and if he is allowed to access only then he will be pe rmitted to enter into the directory and access fiels otherwise he will not be allowed. This is just one way of securing your files with apache. Roopa Rannorey Roopa has been in the IT field in Karnataka, India for about three plus years. Her interests include Linux Security and Networking and she has been at them for a while.. Uncover methods to safeguard, track, and oversee file folders efficiently using the well-known Nginx web server on Unix. Apache Management, Log Security, Directory Access Control. . Brittany Day

Calendar 2 Nov 22, 2002 User Avatar Brittany Day
102

Best Practices For Securing PHP Installations on Linux Using Apache

As we know that the vulnerabilities in PHP are increasing day by day there comes the need to secure the PHP installation to the highest level. Due to its popularity and its wide usage most of the developers and the administrators will be in trouble if they don't take appropriate steps on security issues during the installation. . First comes the question of choosing the platform for PHP! I have choosen Linux OS and Apache Web server to explain this because of its performance and security aspects. It depends on the developer's need whether he is going to install it as an Apache module or a CGI interpreter. When choosing to build PHP in either of the two ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and you don't have to recompile everything as you add to, or change PHP. Building PHP into apache staticly means that PHP will load and run faster. Advantages Server is more flexible. It can be run as SSL, mod_perl, or php with only one installation. Servers can be extended with other modules even after installation. Easier module development and testing as the compiling apache source is not required each time the module is changed. Disadvantages DSO is not supported on all platforms. Startup of the server is 20% slower due to symbol resolving. The server is approximately 5% slower at execution time under some platforms because position independent code (PIC) sometimes needs complicated assembler tricks for relative addressing which are not necessarily as fast as absolute addressing. DSO can produce a slightly slower server depending on platform and address resolutioning. DSO modules cannot be linked with other DSO modules. For example a.out-based platforms usually don't provide this functionality while ELF-based platforms do. You cannot use the DSO mechanism for all types of modules. This requires either the code be referenced directly through theApache core, or that you compile Apache with chaining available. Some platforms cannot force the linker to export all global symbols for linking DSO and Apache executables. This is overcome using the SHARED_CORE feature of Apache and is used by default on such platforms. Advantages/Disadvantages of compiling PHP as a CGI interpreter PHP can be compiled as a CGI binary, this allows a user to separate PHP from their web server entirely. Each PHP script that is written will need to contain a statement that points to the path of the PHP binary just as in PERL. #!/usr/local/bin/php CERT Advisory CA-96.11 advises against placing any type of interpreter in the CGI-BIN so it is a good idea to create an isolated directory where PHP can be run. PHP has built in security measure to prevent malicious attacks of this type as well. In the configuration file for PHP, you can specify the following security features: doc_root This options only works when PHP is installed in Safe Mode. This specifies where the root document directory of PHP is. Scripts outside of this directory will not be interpreted. User_dir This option only works when PHP is installed in Safe Mode. This variable specifies user directories so that scripts outside of this directory cannot be executed. --enable-force-CGI-redirect This allows you to force redirection so that scripts cannot be access directly from the internet. Scripts are redirected to a URL, hiding their full path names. Building as a CGI Binary means efficiency could be improved by having only a single Perl interpreter running in memory, and passing it the Perl scripts. This is where mod_perl comes in to the picture. It provides a single embedded Perl interpreter within the Apache web server. This can be either statically linked, or as a DSO module. Some of the advantages of mod_perl are: Able to write Apache modules entirely in Perl. Having a persistentinterpreter in the server saves on overheads due to starting a perl interpreter for each script. Offers code caching, where the modules and scripts are being loaded and compiled only once. Increased power and speed. Full access to the web server. Allows customized processing of URI to filename translation, authentication, response generation and logging practically no run-time overhead. Improved performance of %200 - %2000 is apparently obtained. One of the major drawbacks of a CGI interpreter is when PHP is compiled as a CGI. This means a lack of effieciency in handling high traffic applications. PHP installation is very easy but installing PHP in a secured manner depends on your platform, installation type selection, and configuration options considered. Whatever method you choose please remember to follow the recommended PHP Configuration Options. There are various options that can be set in PHP to increase the overall security of your server. We will discuss some of the most common and useful options. Safe_mode Safe mode is required for nearly all of the following options, safe mode allows PHP to impose more security restrictions than a normal configuration. Safe_mode_exec_dir Setting this variable helps you in forceing PHP to only execute scripts from a specified directory. Open_basedir This option allows you to control which directories PHP scripts are allowed to access files from. By default PHP will allow a script to access a file from anywhere so it is recommended that is option be set. By predefining valid directories, data can be protected. Max_execution_time This variable enables you to set a maximum execution time that a script can have. If a script runs longer than the allocated execution time, it will be terminated. This option will allow you to prevent attackers from tying up your web server with malicious scripts that could cause denial of service. Memory_limit This allows you to control the maximumamount of memory that a script can use. Using this will help to prevent buffer overflows which may lead to more serious threats. Upload_tmp_dir This designates where PHP will place files that are being uploaded. We will discuss both cases here. PHP AS AN APACHE MODULE: Here Apache should run as an ordinary user with least privileges. Never run apache as a root user. Try to run Apache in a root jail. If you are running PHP as an Apache Module it is fine, means it provides maximum security. Following are the steps to install and configure the same. gunzip apache_xxx.tar.gz tar -xvf apache_xxx.tar gunzip php-xxx.tar.gz tar -xvf php-xxx.tar cd apache_xxx ./configure --prefix=/www --enable-module=so make make install cd ../php-xxx ./configure --with-mysql --with-apxs=/www/bin/apxs make make install If you decide to change your configuration options after installation, you just have to repeat the last three steps. You also have to restart apache for the new module to take effect. A recompile of Apache is not needed. cp php.ini-dist /usr/local/lib/php.ini You can edit your .ini file to set PHP options. If you prefer this file in another location, use --with-config-file-path=/path in step 8. Edit your httpd.conf or srm.conf file and check that these lines are present and not commented out: AddType application/x-httpd-php .php LoadModule php4_module libexec/libphp4.so The path on the right hand side of the LoadModule statement must point to the path of the PHP module on your system. The above statement is correct for the steps shown above. Different examples of compiling PHP for apache are as follows: ./configure --with-apxs --with-pgsql This will create a libmodphp4.a library, a mod_php4.c and some accompanying files and copy this into the src/modules/php4 directory in the Apache source tree. Then youcompile Apache using --activate-module=src/modules/php4/libphp4.a and the Apache build system will create libphp4.a and link it statically into the httpd binary. The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP. ./configure --with-apache=/path/to/apache_source --with-pgsql=shared ./confgure --enable-debug=no Note: Will not disclose the physical path if some error occurs. ./confgure --enable-safe-mode Banner Off in apache's configuration file httpd.conf, will not disclose the server's banner information. This makes attacks more difficult for would-be intruders. Lets consider the second case... PHP AS A CGI INTERPRETER: Download the latest version of PHP from PHP: Downloads . Extract the package # tar zxvf php-x.x.x.tar.gz Where x.x.x. is the version number. Change to the PHP directory # cd php-x.x.x Configure it with the various options present #./configure --without-apache --without-apxs --enable-force-cgi-redirect This is to tell PHP that it isis built without Apache support and as a CGI binary. You should get the binary in /usr/local/bin/php. Now you know why it is compiled with the --enable-force-cgi-redirect option. The CGI binary isn't compiled within Apache, it runs under a separate process and user. Hence the question comes of placing the CGI binary in a proper location. I would suggest that the CGI binary should be placed outside the web directory, as the risk would be greatly reduced and also make sure that you have enabled safe mode in the php.ini configuration file. Most commonly attacks arise in the form of getting access to files. Therefore you can prevent the user from calling the CGI binary directly by forcing a CGI to redirect within Apache. For this, just add the following directives in Apache's httpd.conf file: Action php-script /cgi-bin/php.cgi AddHandler php-script .php Now you will see that URL is rewritten http;//test.com/application/test.htm into: Note: Ensure that you perform permission checks on the application/directory in the process. This gives you the added benefit of making the URL a little shorter. Lastly, change your doc_root and user_dir options in the php.ini appropriately. SUMMARY: Here we have discussed the issues on how best the user can secure PHP installation considering both cases and I hope this will be helpful to all those who are keen in securing PHP and thus eliminating the many of the security risks involved. Article By: Dharmendra.T Linux Security Expert This email address is being protected from spambots. You need JavaScript enabled to view it. . Discover essential techniques for safeguarding PHP deployments on a Linux system utilizing Apache, as you delve into numerous configuration possibilities.. PHP Security, Apache Configuration, Secure Installations. . Brittany Day

Calendar 2 Aug 22, 2002 User Avatar Brittany Day
102

Create a Safe Web Server Configuration with Apache and OpenSSL Tools

Using apache and OpenSSL you can create your own secure web server to keep authentication and other information private from prying eyes. . Having a secure web server is a vital necessity if you are doing on-line administration, banking and/or e-commerce. You may just have personal information you need to access over the web and wish to make secure. Using a secure web server is perfect for these implementations. Using Apache , mod-ssl and OpenSSL we can create a secure server quickly and easily. We also no longer have to worry in the U.S. about the RSA encryption. Prior to Sept. 6, 2000 the RSA algorithm was fully patended by RSA. The patent officially expires on September 20, 2000, but RSA lifted the patent a little earlier. Because of this we no longer need to use the RSAREF package, which is still under license from RSA. The first task in setting up our secure server will be to retreive the software required to do it. We will need three vital packages, Apache, OpenSSL and mod-ssl. You must have the following packages installed: Apache 1.3.12 or later mod-ssl-2.2.6 or later OpenSSL-0.9.5a or later RPMs and Debian packages most certainly also exist. See your favorite mirror site for pre-built packages. Instead of using mod-ssl you also have the option to use Apache-SSL. This document will instead focus on using mod-ssl instead. Mod_SSL was derived from Apache-SSL originally. The code has been completely rewritten since then. Mod_SSL has been known to run faster and be easier to configure than Apache-SSL. Compile and Install OpenSSL First Assuming you have perl and a working compiler installed, decompress the three packages. Compile OpenSSL first (this takes a while): $ ./config $ make $ make test $ make install Once this is all done compile mod-ssl: Note: ' ALL ' means you MUST have the option and ' optional ' is optional. $ cd mod_ssl-2.6.x-1.3.x ALL $ ./configure \ ALL --with-apache=../apache_1.3.x \ ALL --with-ssl=../openssl-0.9.x \ ALL --with-mm=../mm-1.1.x \ OPTIONAL --with-crt=/path/to/your/server.crt \ OPTIONAL --with-key=/path/to/your/server.key \ OPTIONAL --prefix=/path/to/apache \ ALL [--enable-shared=ssl] \ OPTIONAL [--disable-rule=SSL_COMPAT] \ OPTIONAL [--enable-rule=SSL_SDBM] \ OPTIONAL [--enable-rule=SSL_EXPERIMENTAL] \ OPTIONAL [--enable-rule=SSL_VENDOR] \ OPTIONAL [...more APACHE options...] OPTIONAL $ cd ../apache_1.3.x $ make $ make certificate $ make install For more information on compiling mod-ssl directly into Apache read the mod-ssl INSTALL and README files included with the package. They will provide you with the steps necessary to do this. Configure httpd.conf for SSL Support After Apache mod-ssl is installed, you can configure your httpd.conf like you would for a normal site. You will, however, have to setup your SSL secure site through a VirtualHost . You will access with instead of . There are many configuration options and requirements for a VirtualHost in Apache. Since there is too much to talk about here I will only give you an example of a basic VirtualHost . A VirtualHost contains the server name, system administrators e-mail address, the path to the files and a path to the logs for the host. It turns out looking something like this: ServerAdmin This email address is being protected from spambots. You need JavaScript enabled to view it. DocumentRoot /home/httpd/mysite/ ErrorLog /var/log/httpd/mysite-errors_log TransferLog /var/log/httpd/mysite-transfers_log To add SSL support to your VirtualHost you must enable it and tell it where you have your certificate and key to decrypt it with. Add these lines before the ' ' tag: SSLEngineon SSLCertificateFile /etc/httpd/conf/ssl.crt/server.crt SSLCertificateKeyFile /etc/httpd/conf/ssl.key/server.key These are basic SSL options for VirtualHosts. There are many more than can be listed in this short document. When you install mod_SSL into Apache the new httpd.conf will have examples and descriptions of VirtualHosts and SSL options. You can also find numerous documents at www.apache.org and . Once configured, you are all set to start up the server. Start Apache in SSL mode by typing the following: [root@myhost #] /usr/sbin/httpd -startssl read RSA key Enter PEM pass phrase: Notice it asks you for a password. It will require a password to decrypt your key for the SSL encryption. This could prevent apache from working on startup. Here is a way around it, but it can be a security hazard. Go to where your stored httpd.conf and in the ssl.key directory you should see server.key . This contains your encrypted key. What we are going to do here is decrypt the key permently. The upside is you won't have to enter a password anymore. The security risk is that if the key is compromissed someone can possibly decrypt the information you send across your once secure connection. Before you decrypt the key make a backup first: [root@myhost #] cp /path/to/apache-conf/ssl.key/server.key server.key.old Now, using OpenSSL, decrypt the key: [root@myhost #] /usr/sbin/openssl rsa -in server.key.old -out server.key read RSA key Enter PEM pass phrase: It will prompt you for your password and decrypt your key. server.key now contains an unencrypted key. You must still start apache with httpd --startssl or the start-up file included with your RPM or dpkg. Resources A Netscape document on How SSL Works Apache Main Page OpenSSL Main Page Mod-SSL Main Page DevShed.com article on Building an E-Commerce Site Information on the RSA patent expiration at this O'Reilly article The RSA Press Release . Securing your onlineadministration, banking, and e-commerce is essential with a web server configuration using Apache and OpenSSL.. using, apache, openssl, create, secure, server, authentication, other. . Brittany Day

Calendar 2 Sep 19, 2000 User Avatar Brittany Day
News Add Esm H240

Get the latest News and Insights

Get the latest Linux and open source security news straight to your inbox.

Community Poll

What got you started with Linux?

No answer selected. Please try again.
Please select either existing option or enter your own, however not both.
Please select minimum {0} answer(s).
Please select maximum {0} answer(s).
/main-polls/150-what-got-you-started-with-linux?task=poll.vote&format=json
150
radio
0
[{"id":483,"title":"Self-taught through trial and error","votes":546,"type":"x","order":1,"pct":78.45,"resources":[]},{"id":484,"title":"Formal training or courses","votes":30,"type":"x","order":2,"pct":4.31,"resources":[]},{"id":485,"title":"A job that required it","votes":34,"type":"x","order":3,"pct":4.89,"resources":[]},{"id":486,"title":"Other","votes":86,"type":"x","order":4,"pct":12.36,"resources":[]}] ["#ff5b00","#4ac0f2","#b80028","#eef66c","#60bb22","#b96a9a","#62c2cc"] ["rgba(255,91,0,0.7)","rgba(74,192,242,0.7)","rgba(184,0,40,0.7)","rgba(238,246,108,0.7)","rgba(96,187,34,0.7)","rgba(185,106,154,0.7)","rgba(98,194,204,0.7)"] 350
bottom 200
Your message here