Filebasename ruby on rails
Dating > Filebasename ruby on rails
Download links: → Filebasename ruby on rails → Filebasename ruby on rails
И требуйте от пользователя ввести старый пароль при его изменении. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. However, the code is fairly simple, so it should be easy for you to figure out.
MySpace блокировал много тегов, но позволял CSS. Также возможно производить ротацию алгоритмов шифрования и дайджестов, используемых для зашифрованных и подписанных куки. The first step is to add a few things to our view files. By default, Rails logs all requests being made to the web application. Here is how we do that: AWS::S3::Bucket.
In general there is no such thing as plug-n-play security. Amazon S3 is a great way to store files, but learning how to integrate it into your website can be a challenge. To match hidden files that start with a. Он также может использоваться как мощный язык сценариев и очень эффективная альтернатива обычному написанию сценариев в оболочке, в большинстве случаев используемых для написания скриптов системного администрирования.
Basic File and Directory Operations in Ruby - Posted over 5 years ago This article will show you how to add a CSV export option to your application. Best, --Â Marnen Laibow-Koser marnen marnen.
Ruby On Rails Security Guide This manual describes common security problems in web applications and how to avoid them with Rails. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem. In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself and possibly other layers or applications. This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person. The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack methods in order to find the correct countermeasures. That is what this guide aims at. In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs and make updating and security checks a habit check the chapter. Sessions make it stateful. Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request. Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application. A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. And the other way round: the browser will send it to the server on every request from the client. A session id consists of the hash value of a random string. The random string is the current time, a random number between 0 and 1, the process id number of the Ruby interpreter also basically a random number and a constant string. To date MD5 is uncompromised, but there have been collisions, so it is theoretically possible to create another input text with the same hash value. But this has had no security impact to date. Many web applications have an authentication system: a user provides a user name and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session id in the cookie identifies the session. Hence, the cookie serves as temporary authentication for the web application. Everyone who seizes a cookie from someone else, may use the web application as this user — with possibly severe consequences. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. This is one more reason not to work from a coffee shop. For the web application builder this means to provide a secure connection over SSL. Provide the user with a log-out button in the web application, and make it prominent. Read more about this so-called session fixation later. The main objective of most attackers is to make money. Instead you should store them in the database and save their id in the session. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate. If the user clears his cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data. The most important are ActiveRecord::SessionStore and ActionDispatch::Session::CookieStore. There are a number of session storages, i. Most real-live applications choose ActiveRecord::SessionStore or one of its derivatives over file storage due to performance and maintenance reasons. ActiveRecord::SessionStore keeps the session id and hash in a database table and saves and retrieves the hash on every request. Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. This is fine as you should not store large amounts of data in a session anyway, as described before. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie. That means the security of this storage depends on this secret and on the digest algorithm, which defaults to SHA512, which has not been compromised, yet. Put the secret in your environment. Including a nonce a random value in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers mongrels. Storing nonces in a database table would defeat the entire purpose of CookieStore avoiding accessing the database. This is called session fixation. It is therefore not necessary for the attacker to steal the session id afterwards. Expiring sessions, for example every 20 minutes, greatly reduces the time-frame for attack. Therefore he accesses the web application from time to time in order to keep the session alive. As you may not change a cookie of another domain because of the same origin policy , the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: document. Read more about XSS and injection later on. The most effective countermeasure is to issue a new session identifier and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Note that this removes any value from the session, you have to transfer them to the new session. Another countermeasure is to save user-specific properties in the session, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent the web browser name , though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. These might change over the course of a session, so these users will not be able to use your application, or only in a limited way. One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to expire sessions in a database table. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. Now you can delete sessions that were created a long time ago. It tries to load the suspected image from www. As explained before, it will also send along the cookie with the valid session id. It then returns a result page which is an unexpected result for the browser, so it will not display the image. CSRF appears very rarely in CVE Common Vulnerabilities and Exposures — less than 0. This is in stark contrast to the results in my and others security contract work — CSRF is an important security issue. Secondly, a security token in non- GET requests will protect your application from CSRF. The HTTP protocol basically provides two main types of requests — GET and POST and more, but they are not supported by most browsers. If your web application is RESTful, you might be used to additional HTTP verbs, such as PUT or DELETE. POST requests can be sent automatically, too. Here is an example for a link which displays www. In fact it dynamically creates a new form that sends a POST request. Note: In Rails versions prior to 3. Note that cross-site scripting XSS vulnerabilities bypass all CSRF protections. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Whenever the user is allowed to pass parts of the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. A simple countermeasure would be to include only the expected parameters in a legacy action again a whitelist approach, as opposed to removing unexpected parameters. And if you redirect to an URL, check it with a whitelist or a regular expression. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, do not allow the user to supply parts of the URL to be redirected to. Many web applications allow users to upload files. File names, which the user may choose partly , should always be filtered as an attacker could use a malicious file name to overwrite any file on the server. Of course, the Ruby interpreter would need the appropriate permissions to do so — one more reason to run web servers, database servers and other programs as a less privileged Unix user. This is opposed to a blacklist approach which attempts to remove not allowed characters. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server. The solution to this is best to process media files asynchronously: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background. The popular Apache web server has an option called DocumentRoot. This is the home directory of the web site, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested might require some options to be set. Examples for this are PHP and CGI files. Just as you have to filter file names for uploads, you have to do so for downloads. This is also a good approach to avoid possible code in an uploaded file to be executed. Although this would require several extra-security measures, the opposite is the case in the real world. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF. XSS If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS. Having one single place in the admin interface or Intranet, where the input has not been sanitized, makes the entire application vulnerable. Refer to the Injection section for countermeasures against XSS. It is recommended to use the SafeErb plugin also in an Intranet or administration interface. CSRF Cross-Site Reference Forgery CSRF is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface. A real-world example is a. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change his credentials. Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination. For countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section. You could introduce roles for the admin interface to limit the possibilities of the attacker. Or how about special login credentials for the admin interface, other than the ones used for the public part of the application. Or a special password for very serious actions? This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though. This makes stealing an admin cookie from the usual domain, www. This is because of the same origin policy in your browser: An injected XSS script on www. The problem is that it is often used in conjunction with the parameters params hash available in the controller, which may be manipulated by an attacker. Note that this vulnerability is not restricted to database columns. In fact, this vulnerability is extended even further with the introduction of nested mass assignment and nested object forms in Rails 2. All other attributes will be protected. If no :as option is provided then the :default role will be used. This can be easily achieved with a very simple application config option of: config. This technique is best applied at the start of a new project. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure. There are a number of authentication plug-ins for Rails available. Good ones, such as the popular and , store only encrypted passwords, not plain-text passwords. Every new user gets an activation code to activate his account when he gets an e-mail with a link in it. You can find out more about it in. It is advisable to update your plug-ins from time to time. Moreover, you can review your application to find more flaws like this. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of user names and a dictionary, an automatic program may find the correct password in a matter of minutes. However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered user name or e-mail address has not been found. This allows an attacker to compile a list of user names and brute-force the accounts. In order to mitigate such attacks, display a generic error message on forgot-password pages, too. Note, however, that this is not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack. Why not be different and make it more difficult? If it is easy to change the password, the attacker will hijack the account with a few clicks. As a countermeasure, make change-password forms safe against CSRF, of course. And require the user to enter the old password when changing it. As a countermeasure require the user to enter the password when changing the e-mail address, too. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in. In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to his e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, review your application logic and eliminate all XSS and CSRF vulnerabilities. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. But not only spam robots bots are a problem, but also automatic login bots. You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too. If it is too far in the past, or if it is in the future, the form is invalid. By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got full access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can filter certain request parameters from your log files by appending them to config. Bruce Schneier, a security technologist, 34,000 real-world user names and passwords from the MySpace phishing attack mentioned. It turns out that most of the passwords are quite easy to crack. It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. If an attacker knows your user name and you use a weak password, your account will be easily cracked. A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the first letters of a sentence that you can easily remember. Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too. Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Remember that every parameter may be changed, no matter how much you hide or obfuscate it. It will be available in params in the controller. As a rule of thumb, no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated. JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values. The Live Http Headers plugin for Mozilla Firefox logs every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are even client-side proxies that allow you to intercept any request and response from and to the Internet. Prominent examples of injection are cross-site scripting XSS and SQL injection. Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection. A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. See below for details. However, this is a very devastating and common attack in web applications, so it is important to understand the problem. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails. Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this: Model. Make it a habit to think about the security consequences when using an external string in SQL. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off. The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable — just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter — obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the , or client-site proxies make it easy to change requests. XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser. During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The also documented 239 browser plug-in vulnerabilities in the last six months of 2007. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets. A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to. Escaping user input is essential. Here is the most straightforward test to check for XSS: 8. In JavaScript you can use the document. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. However, you can read and write this property, if you embed the code directly in the HTML document as it happens with XSS. Http only cookies can be used from IE v6. Safari is still considering, it ignores the option. But other, older browsers such as WebTV and IE 5. Be warned that cookies , though. This iframe is taken from an actual attack on legitimate Italian sites using the. Mpack tries to install malicious software through security holes in the web browser — very successfully, 50% of the attacks succeed. Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but included in the URL. Especially search forms fail to escape the search string. However, it can easily happen that the programmer forgets to use it, so it is recommended to use the plugin. SafeErb reminds you to escape strings from external sources. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding: This example pops up a message box. It will be recognized by the above sanitize filter, though. The following is an excerpt from the Yahoo! The filter is applied only once, however, so the onload attribute with the worm code stays in place. Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on. Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with. In December 2006, 34,000 actual user names and passwords were stolen in a. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form. The MySpace Samy worm will be discussed in the CSS Injection section. Think twice about allowing custom CSS in your web application. CSS Injection is explained best by a well-known worm, the. This worm automatically sent a friend request to Samy the attacker simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm. MySpace blocks many tags, however it allows CSS. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token. In the end, he got a 4 KB worm, which he injected into his profile page. The CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers Firefox, for example. However, as custom CSS in web applications is a quite rare feature, I am not aware of a whitelist CSS filter. If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application. However, up to the current version 3. Get the that removed serious bugs. However, even that version has , so the countermeasures still apply. Here is an example for version 3. If you use the , or actions that return a string, rather than rendering a view, you have to escape the return value in the action. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h method. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon ; or a vertical bar. A countermeasure is to use the system command, parameters method which passes command line parameters safely. This can lead to false redirection, XSS or HTTP response splitting. HTTP request headers have a Referer, User-Agent client software , and Cookie field, among others. Response headers for example have a status code, Cookie and Location redirection target URL field. All of them are user-supplied and may be manipulated with more or less effort. Remember to escape these header fields, too. For example when you display the user agent in an administration area. Besides that, it is important to know what you are doing when building response headers partly based on user input. For example you want to redirect the user back to a specific page. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first. And what could an attacker do with a false redirection? He could redirect to a phishing site that looks the same as yours, but asks to login again and sends the login credentials to the attacker. Or he could install malicious software through browser security holes on that site. Make sure you do it yourself when you build other header fields with user input. In HTTP, the header block is followed by two CRLFs and the actual data usually HTML. The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. However, this only seems to work with Keep-Alive connections and many browsers are using one-time connections. In any case this is a serious bug, and you should update your Rails to version 2. If you see any typos or factual errors you are confident to patch, please clone the repository and open a new pull request. You can also ask for commit rights on if you plan to submit several patches. Commits are reviewed, but that happens after you've submitted your contribution. This repository is cross-merged with master periodically. You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Check the for style and conventions. If for whatever reason you spot something to fix but cannot patch it yourself, please. And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the.
Last updated