0% found this document useful (0 votes)
26 views

Laravel Cheatsheet

laravel-cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
26 views

Laravel Cheatsheet

laravel-cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series Laravel Cheat Sheet Introduction This Cheatsheet intends to provide security tips to developers building Laravel applications. It aims to cover all common vulnerabilities and how to ensure that your Laravel applications are secure. ‘The Laravel Framework provides in-built security features and is meant to be secure by default. However it also provides additional flexibility for complex use cases. This means that developers unfamiliar with the inner workings of Laravel may fall into the trap of using complex features in a way that is not secure. This guide is meant to educate developers to avoid common pitfalls and develop Laravel applications in a secure manner. You may also refer the Enlightn Security Documentation, which highlights commen vulneral and good practices on securing Laravel applications. The Basics + Make sure your appis not in debug mode whl APP_DEBUS environment variable to false: in production. To tum off debug mode, set your APP_DEBUG-false * Make sure your application key has been generated. Laravel applications use the app key for ‘symmetric encryption and SHA256 hashes such as cookie encryption, signed URLs, password reset tokens and session data encryption. To generate the app key, you may run the key:generate Artisan command: php artisan key :generate ‘+ Make sure your PHP configuration is secure. You may refer the PHP Configuration Cheat Sheet ‘for more information on secure PHP configuration settings, + Set safe file and directory permissions on your Laravel application. In general, all Larevel directories should be setup with a max permission level cf 775 andnonexecutable files with a max permission level of 664 . Executable files such as Artisan or deployment scripts shouldbe provided with amax permission level of 775. Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html ans 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series ‘* Make sure your application does nct have vulnerable dependencies. You can check this using ‘the Finlightn Security Checker. Cookie Security and Session Management By default, Laravelis configured in a secure manner. However; if you change your cookie or session ‘configurations, make sure of the folowing: ‘+ Enable the cookie encryption middleware if you use the cookie session store or if you store ‘any kind of data that shouldnot be readable or tampered with by clients. In general, this should be enableduniess your application has avery specific use case that requires disabling this. To enable this middleware, simply add the EneryptGookies middleware tothe web middleware OUP in your App\Http\Kernel class: yee % The application's route middleware groups. * evar array ” protected $middlewareGroups = | web’ => [ \App\Http\Niddleware\EncryptCookies : :class, 7 «+ Enable the 11ttponly attribute on your session cookies via your config/session.php file, so ‘that your session cookies are inaccessible from Javascript: “hetp_only’ => true, ‘¢ Unless you are using sub-domain route registrations in your Laravel application, itis recommended to set the cookie domain attribute to null so that only the same origin (excluding subdomains) can set the cookie. This can be configuredin your config/session.php file: domain’ => null, + Setyour Sanesite cookie attribute to lex oF strict inyour config/session.php file to restrict your cookies to afirst party or same-site context: Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series ‘same_site' => ‘lax’ ‘© If your application is HTTPS only, it is recommended to set the secure configuration option in your config/session. php file to true to protect against man-in-the-middle attacks. If your application has a combination of HTTP and HTTPS, then it is recommended to set this value to null So that the secure attribute is set automatically when servingHTTPS requests: secure’ => null, + Ensure that you have a low session idle timeout value, OWASP recommends 22-5 mhutes idle timeout for igh value applications and 15-30 minutes for low risk applications. This can be ‘configured in your config/session.php file lifetime’ => 15, You may also refer the Cookie Security Guide to learn more about cookie security and the cookie attributes mentioned above. Authentication Guards and Providers At its core, Laravel's authentication facilities are made up of "guards" and "providers". Guards define how users are authenticated for each request. Providers define how users are retrieved from your persistent storage. Laravel ships with a session guard which maintains state using session storage and cockies, and @ token quatd for API tokens. For providers, Laravel ships witha eloquent provider for retrieving Users using the Eloquent ORM andthe databese provider forretrieving users using the database query builder. Guards and previders can be configured in the config/auth.pho file, Laravel offers the ability to build custom guards and providers as well Starter Kits Laravel offers a wide variety of first party application starter kits that include in-buit authentication features: Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html ans 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series 1. Laravel Breeze: A simple, minimal implementation of all Laravels authentication features including login, registration, password reset, email verification and password confirmation. 2. Laravel Fortify: A headless authentication backend that includes the above authentication features along with two-factor authentication. 3. Laravel Jetstream: An application starter kit that provides @ UI on top of Laravel Fortify’s authentication features. Itis recommended to use one of these starter kits to ensure robust and secure authentication for your Laravel applications. API Authentication Packages Laravel also offers the following API authertication packages: 11, Passport: An OAuth? authentication provider, 2, Sanctum: An APHtoken authentication provider. Starter kits such as Fortify and Jetstream have in-built support for Sanctum, Mass Assignment Mass assignment is @ common vuherability in modern web applications that use an ORM like Laravets Eloquent ORM. Amass assignments a Vulnerability Where an ORM pattem is abused to madify data items that the user should nct benormallyallawed to modify. Consider the following code: Route: :any(‘/profile’, function (Request Srequest) { Srequest->user()->forceFill(Srequest-al1())->save(); Suser = Srequest->user()->fresh(): return response()->json(conpact(‘user')): sniddlewere( auth’) “The above profile route allows the logged in user to change their profile information. However let's say there isan is_adnin column in the users table. You probably donot want the User to be allawed to change the value of this column. However, the above code allows users to change any column values for their row in the users table. This is amass assignment vulnerability. Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html ans 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series Laravel has in-built features by defautt to protect against this vulnerability. Make sure of the following to stay secure: + Qualify the allowed parameters that you wish to updateusing Srequest->only or Srequest- >validated ratherthan Srequest->al1. + Donot unguardmodels or setthe Sguarded variableto an empty array. By doing this, you are ‘actually disabling Latavefs in-built mass assignment protection. ‘+ Avoid using methods such as forceFil1 of forceCreate that bypass the protection mechanism. You may however use these methods if you are passingin a validated array of, values. SQL Injection ‘SQL Injection attacks are unfortunstely quite common in modem web applications and entail attackers providing malicious request input data to interfere with SQL queries. This guide covers, SQL injection and how it can be prevented specifically for Laravel applications. You may also refer the SQL Injection Prevention Cheatsheet for more information that is net specific to Laravel. Eloquent ORM SQL Injection Protection By default, Laraver's Eloquent ORM protects against SQL injection by parameterizing queries and using SQL bindings. For instance, consider the following query: use App\odels\User; User::where(‘email’, Semail)->get(); “The code abcve fres the query below: =? select * from ‘users’ where ‘email So, even if Senai is untrusted user input data, you are protected from SQL injection attacks. Raw Query SQL Injection Laravel also offers raw query expressions and raw queties to construct complex queries or database specific queries that arentt supported out of the box. While thisis great for flexibility, you must be carefulto always use SQL data bindings for such queries. Consider the following query: Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html sits Laravel -OWASP Cheat Sheet Series use Tlluminate\Support \Facades\DB; use App\Models\User; User : :whereRaw( ‘email Srequest->input(‘emeil').'*')->get(): DB; :table( ‘users’ )->whereRaw(‘email = "'Srequest->input(‘email")."*" oget(); Both lines of code actually execute the same query, which is vulnerable to SQL injection as the query does not use SQL bindings for untrusted user input data. ‘The code above fires the following query: select * from ‘users* where ‘email’ = “value of email query parameter* ‘Always remember to use SQL bindings for request data. We can fix the above code by making the following modification: use App\Models\User; User swhereRaw(‘enail = 2°, [Srequest->input(‘email’)])-=get(); We can even use named SQL bindings like so: use App\Models\User; User::whereRaw("enail = email’, [‘email’ Srequest->input(‘email')])->get(); Column Name SQL Injection You must never allow user input data to dictate column names referenced by your queries. The following queries may be vulnerable to SQL injection use App\Nodels\User; User : :where(Srequest->input('colname’), ‘sonedata’ )->get() User : :query()->orderBy (Srequest->input(' sortBy’))->get(); Itis important to note that even though Laravel has some in-built features such as wrapping column names to protect against the above SQL injection vulnerabilities, some database engines (depending on versions and configurations) may still be vulnerable because binding column names is not supported by databases. Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html es 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series ‘At the very least, this may result in a mass assignment vulnerability instead of a SQL injection because you may have expected a certain set of column values, but since they are not validated here, the user is free to use other columns as well. Always validate user input for such situations like so: use App\Models\User; Srequest--validate(| ‘sortBy’ => ‘in:price,updated_et']); User : :query()->orderBy (Srequest->validated( | ‘sortBy’ ])-> Validation Rule SQL Injection Certain validation rules have the option of providing database column names. Such rules are vulnerable to SQL injection in the same manner as column name SQL injection because they construct queries in a similar manner. For example, the following code may be vulnerable: use I1luminate\alidation\Rule; Srequest->validate(| Ad’ => Rule: :unique(users")->ignore(Sid, Srequest->input(colnane’)) D: Behind the scenes, the above code triggers the following query: use App\Models\User; Scolname = Srequest->input(‘colnane' ); User: :where(Scolnane, Srequest->input('id"))->where(Scolnane, “<>', $id)- count); Since the column name is dictated by user input, it is similar to column name SQL injection. Cross Site Scripting (XSS) XSS attacks are injection attacks where malicious scripts (such as JavaScript code snippets) are injected into trusted websites. Laravet's Blade templating engine has echo statements {( }} that automatically escape variables using the htmlspecialchars PHP function to pretect against XSS attacks. Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html m3 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series Laravel also offers displaying unescaped data using the unescaped syntax {11 11}. This must not be used on any untrusted data, otherwise your application will be subject to an XSS attack. For instance, if you have something lke this in any of your Blade templates, it would resutt in a vulnerability: {11 request()->input('somedata’) 1!) This, however, is safe to dot {4 request ()->input(’somedata’) }} For cther information on XSS prevention that is nat specific to Laravel, you may refer the Cross Site Scripting Prevention Cheatsheet. Unrestricted File Uploads Unrestricted file upload attacks entail attackers uploading malicious files to compromise web applications. This section describes haw to protect against such attacks while building Laravel applications. You may also refer the File Upload Cheatsheet to learn more. Always Validate File Type and Size Always validate the file type (extension or MIME type) and file size to avoid storage DOS attacks and remote code execution: Srequest->validate(| photo’ => ‘file|size:1@/mines: jpg, bmp, png" D: Storage DOS attacks exploit missing file size validations and upload massive files to cause a denial of service (DOS) by exhausting the disk space. Remote code execution attacks entail first, uploading malicious executable files (such as PHP files) and then, triggering their malicious code by visiting the file URL (if public). Both these attacks can be avoided by simple file validations as mentioned above. Do Not Rely On User Input To Dictate Filenames or Path Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html ans 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series Ifyour application allows user controlled data to construct the path of a file upload, this may result in overwriting a critical file or storing the file in a bad location. Consider the following code: Route: :post('/upload’, function (Request $request) { Srequest->file(‘file’)->storeds(auth()->id(), Srequest->input( ‘filename’ )) return back(); » This route saves fileto a directory specificto a user ID. Here, werely onthe Filename user input data and this mey result ina vulnerability as the filename could be something like /2/lenane. pdf . This will upload the file in user ID 2's directory instead of the directory pertaining to the current loggedin user. To fix this, we should use the basenane PHP function to strip out any directory information from the filename input data: Route: :post('/upload’, function (Request Srequest) { Srequest->file(' file" )->storess(auth()->1d(), basename(Srequest- >input(' filename" ))); return back(); »: Avoid Processing ZIP or XML Files If Possible XML files can expose your application to a wide variety of attacks such as XXE attacks, the billion laughs attack and others. If you process ZIP files, you may be exposed to zip bomb DOS attacks. Refer the XML Security Cheatsheet andthe File Upload Cheatsheet to leam mare, Path Traversal ‘A path traversal attack aims to access files by manipulating request input data with ../ sequences and variations or by using absolute file paths. If you allow users to download files by filename. you may be exposed to this vulnerability if input data is nct stripped cf ditectory information. Consider the following code: Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html ons 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series Route: :get(‘/download', function(Request Srequest) { return response()->download(storage-path( ‘content/").$request- >input(" filename’); ) Here, the filename is nct stripped of directory information, so a matformed filename such as 1. .enw Could expose your application credentials to potential attackers. Simfarto unrestricted file uploads, you should use the basenane PHP function to strip out directory information like so: Route: :get('/download', function(Request Srequest) { return response()->download(storage_path( ‘content/*).basename(Srequest- >input(' Filename’ ))) y: Open Redirection Open Redirection attacks in themselves are not that dangerous but they enable phishing attacks. Consider the following code: Route: :get('/redirect’, function (Request Srequest) ( return redirect (Srequest->input(‘url")); n: This code redirects the user to any extemal URL providedby user input. This could enable attackers tocreate seemingly safe URLS like hetps://exanple.con/redi rect? urlehttp://evi1 .coa . For instance, attackers may use a URL of this type to spocf passwordreset emails and lead victims to expose their credentials on the attacker's website. Cross Site Request Forgery (CSRF) Cross-Site Request Forgery (CSRF) i8@ type of attack that ocaurs when a malicious web site, email, blog instant message, or program causes a user's Web browser to perform an unwanted action on atrusted site when the user is authenticated. Laravel provides CSRF protection out-of the-box with the VerifycsrrToken middleware. Generally, if youhave this middlewarein the web middleware group of your App\Http\Kernel class, you should be well protected: Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html sons 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series yee % The application's route middlewere groups * evar array 7 protected SmiddlewareGroups = [ web! => [ \App\Http\ Middleware \VerifyCsrfToken: :class, Next, for all your Post request forms, you may use the eesrf blade directive to generate the hidden CSRF input token fields:
Equivalent to... --> For AJAX requests, you can setup the X-CSRF-Token header, Laravel also provides the abilty to exclude certain routes from CSRF protection using the Sexcept variable in your CSRF middleware class. Typically, you would want toexclude only stateless routes (e.g. APIs or webhooks) from CSRF protection. If any other routes are excluded, these may result in CSRF vulnerabilities. Command Injection Command injection vuherabilities involve executing shell commends constructed with unescaped User input data, For example, the following code performs a whois ona user provided domain name’ public function verifyDomain(Request Srequest) 4 exee('whois *.Srequest->input(“domain’)) : ‘The above code is vulnerable as the user data is not escaped properly. To do so, you may use the escapeshellond and/or escapeshellarg PHP functions. Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html ss 9123122, 8:39 AM Laravel -OWASP Cheat Sheet Series Other Injections Object injection, eval code injection and extract variable hijacking attacks involve unserialzing, evalueting orusing the excract function on untrusted user input data. Some examples are: unserialize(Srequest->input(' 4 eval Srequest->input( data’): extract (Srequest-re11()); In general, avoid passing any untrusted input deta to these dangerous functions. Security Headers ‘You should consider adding the following security headers to your web server or Laravel application middleware: + XFrame-Options + X-Content-Type-Options « Strict-Transport Security (for HTTPS only applications) ‘* ContentSecurty-Folicy For more information, refer the OWASP secure headers project. Tools ‘You should consider using Enlightn, @ static and dynamic analysis tool for Larevel applications that has over 45 automated security checks to identify potential security issues. There is both an open ‘source version anda commercial version of Enlightn available. Enightn includes an extensive 45 page documentation on security vulnerabilities and a great way to learn mere on Laravel security is to just review its documentation, You should also use the Enlightn Security Checker or the Local PHP Security Checker, Both of them are open source packages, licensed under the MIT and AGPL licenses respectively, that scan your PHP dependencies for known vulnerabilities using the Security Advisories Database, References Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html sans Laravel -OWASP Cheat Sheet Series « Laravel Documentation on Authentication * Laravel Documentation on Authorization *# Leravel Documentation on CSRF « Laravel Documentation on Validation «# Enlightn SAST and DAST Tool Laravel Enlightn Security Documentation Intps:ifcheatshectseries.owasp.orgicheatsheetsLaravel_Cheat_Sheet.html

You might also like