htaccess as a security option and using a login form - security

I am learning PHP, and I am obsessed with learning security. I know a few about some kind of attacks likes injections, session theft, etc., but I would like to code my own CMS with a perfect security (if possible).
Reading I drop on .htaccess security in directories. This is a good option because all my CMS files are in one directory. I just read this in a website:
HTAccess is the most secure method of password protection, as it relies on the Web server, so the valid usernames and passwords are never shared with the Web browser or stored in the HTML like they can be with other scripts.
Is this true? I mean, it is "unhackeable"? Of course with extra security (like hidding the .htaccess file).
If this is true, I mean, there is no way to hack a site with .htaccess security, how can I use a form (instead of the popup window) so I can log in my CMS? Is there a way to use a "Forgot Your Password" option?
Any help will be apreciated, as examples and links for reference.

HTAccess is the most secure method of password protection, as it
relies on the Web server, so the valid usernames and passwords are
never shared with the Web browser or stored in the HTML like they can
be with other scripts.
I'm a little scared of the person who wrote this sentence originally.
Usernames and passwords would never be shared with the web browser or stored "in the HTML" except in the cases of the most rank disregard for hygienic programming practices. That someone would even present that as an "option" as a straw man argument is troublesome. I recommend finding a better guide.
The htaccess mechanism for server security is also a bit of a misnomer. The .htaccess file in directories is really intended to be a mechanism for clients on shared hosting sites to have some degree of control over Apache configuration variables -- which is a complete non-starter for "totally secure CMS system" (as if such a thing were a possibility. :) You should expect to have complete and total control over your Apache configuration, including all authentication and authorization and access control mechanisms. The .htaccess files are re-loaded, re-parsed, and re-configure the server on every single request but the site-wide Apache configuration is loaded once, parsed once, and configures the server once.
The server-based mechanisms rely upon either HTTP basic authentication (which is roughly akin to shouting your user name and password in a crowded room) or HTTP digest authentication (which is significantly better and if your users pick good passwords, probably even vaguely safe). Tunneling either one through TLS would be wise. (Heck, if you really want "security", you might even go to the effort of using client certificates.)
Note that these mechanisms ask the browser to pop up a dialog box for authentication. If you want to integrate the username and password into your web page in a "beautiful" way, then you will need to do all the username and password authentication checks via a form submission, storing session information, and checking your internal security mechanisms to provide authorization whenever it is necessary. You will be responsible for everything. (And, again, TLS is the way to go.) The web server cannot help you at all. (And you further won't be sending usernames, passwords to the browser in HTML... sheesh. That still scares me.)

is this what your looking for? this will allow you to use a php form to login through htaccess
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
reference

Related

is there any security issue if I send a path in a QueryString?

is there any security issue if I send a path in a QueryString? like if send this request http://localhost/eCTDTreeViewer/Home/Index/?pathOnServer=G:\test\company2
Thinking about QueryString security, you should keep in mind (read as "worry") the following moments:
URLs are stored in web server logs
URLs are stored in the browser history
URLs are passed in Referrer headers
You can find more detailed information about this reading How secure are query strings over HTTPS article and Is an HTTPS query string secure? question on SO.
The risk of exposing a path, given the filesystem is not externally accessible, is negligible.
Especially if the sole purpose of the component you're talking about is to display directories as they exist on the server. What you see in the query string is what you will see in the payload of the response, so it's just fine having the path there in plain text.
Trouble can arise when this "TreeViewer" exposes sensitive files and allows the user to browse to arbitrary locations, enabling them to retrieve passwords stored in files and what not.
Of course it never hurts to add HTTPS, but that only prevents a man in the middle from finding out which directories and files exist on that server and does not offer anny additional security.
HTTPS does not make your improperly secured application secure, you still have to implement authentication and authorization, input sanitation and so on.
Yes, you open yourself up to Directory Traversal (DT) and Local File Inclusion (LFI) attacks.
The main difference between the two is that DT is read-only in which a user can access any file on your web server provided that they have sufficient privileges. LFI on the other hand would allow you to invoke a file (e.g. a PHP file) on the web server rather than reading it.
If, for example, you have a SQL Injection vulnerability on your web application, an attacker may deploy a web shell into your system:
SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE C:/tmp/shell.php
An attacker could then invoke the file:
http://localhost/eCTDTreeViewer/Home/Index/?pathOnServer=C:/tmp/shell.php?cmd=echo "foo"
This is very brief but it should provide a good idea as to how dangerous it can be.
If you stay in plain HTTP, yes. The request will be sent in plain text over the network. Don't be confused, it will be the same issue with a POST request with your information inside the body of it.
The good way to make it safe is to use HTTPS. Because of the handshake done before the exchange, the full request will be encrypted (with the path as well) to be sent to the endpoint.

Is there a way to password protect a directory with .htaccess and have it remember the password?

My experience is that using .htAccess to password protect a directory, it brings up a modal dialog box. And for some browsers (FF and Chrome) don't show the checkbox for "remember" this password.
Is there a way to that a password protect a directory and have the user fill in the username and password within the web page?
Or, is there a way to force the browser to remember that password?
tl;dr: No.
We are talking about something called Basic Authentication.
Unfortunately, these things are features of the browser, and cannot be controlled from the server side. Some browsers have the ability to remember your password forever (usually in the form of a "remember my password" checkbox). It is debatable whether this is a good idea, but at least the user makes the call; forcing this choice from the server side is really a bad idea and I don't think any browser would allow that. Why? The user probably don't want to store his credentials if using a shared device (for example, in a public library).
That said, using an Apache .htaccess file is not the only way to do basic authentication. Using any dinamic content framework (PHP, ASP, etc), you can store a session cookie after the user has authenticated and only send the 401 response and basic authentication headers if the user has no authentication cookie. Since you talk about .htaccess, I assume you are on a LAMP stack; take a look at:
Basic authentication: http://php.net/manual/en/features.http-auth.php
Sessions: http://www.php.net/manual/en/book.session.php

How do I protect sensitive information from cross site access?

My web application displays some sensitive information to a logged in user. The user visits another site without explicitly logging out of my site first. How do I ensure that the other site can not access the sensitive information without accept from me or the user?
If for example my sensitive data is in JavaScript format, the other site can include it in a script tag and read the side effects. I could continue on building a blacklist, but I do not want to enumerate what is unsafe. I want to know what is safe, but I can not find any documentation of this.
UPDATE: In my example JavaScript from the victim site was executed on the attacker's site, not the other way around, which would have been Cross Site Scripting.
Another example is images, where any other site can read the width and height, but I don't think they can read the content, but they can display it.
A third example is that everything without an X-Frame-Options header can be loaded into an iframe, and from there it is possible to steal the data by tricking the user into doing drag-and-drop or copy-and-paste.
The key point of Cross Site Attack is to ensure that your input from user which is going to be displayed, is legal, not containing some scripts. You may stop it at the beginning.
If for example my sensitive data is in JavaScript format, the other site can include it in a script tag
Yep! So don't put it in JavaScript/JSONP format.
The usual fix for passing back JSON or JS code is to put something unexecutable at the front to cause a syntax error or a hang (for(;;); is popular). So including the resource as a <script> doesn't get the attacker anywhere. When you access it from your own site you can fetch it with an XMLHttpRequest and chop off the prefix before evaluating it.
(A workaround that doesn't work is checking window.location in the returned script: when you're being included in an attacker's page they have control of the JavaScript environment and could sabotage the built-in objects to do unexpected things.)
Since I did not get the answer I was looking for here, I asked in another forum an got the answer. It is here:
https://groups.google.com/forum/?fromgroups=#!topic/mozilla.dev.security/9U6HTOh-p4g
I also found this page which answers my question:
http://code.google.com/p/browsersec/wiki/Part2#Life_outside_same-origin_rules
First of all like superpdm states, design your app from the ground up to ensure that either the sensitive information is not stored on the client side in the first place or that it is unintelligible to a malicious users.
Additionally, for items of data you don't have much control over, you can take advantage of inbuilt HTTP controls like HttpOnly that tries to ensure that client-side scripts will not have access to cookies like your session token and so forth. Setting httpOnly on your cookies will go a long way to ensure malicious vbscripts, javascripts etc will not read or modify your client-side tokens.
I think some confusion is still in our web-security knowledge world. You are afraid of Cross Site Request Forgery, and yet describing and looking for solution to Cross Site Scripting.
Cross Site Scripting is a vulnerability that allows malicious person to inject some unwanted content into your site. It may be some text, but it also may be some JS code or VB or Java Applet (I mentioned applets because they can be used to circumvent protection provided by the httpOnly flag). And thus if your aware user clicks on the malicious link he may get his data stolen. It depends on amount of sensitive data presented to the user. Clicking on a link is not only attack vector for XSS attack, If you present to users unfiltered contents provided by other users, someone may also inject some evil code and do some damage. He does not need to steal someone's cookie to get what he wants. And it has notnig to do with visiting other site while still being logged to your app. I recommend:XSS
Cross Site Request Forgery is a vulnerability that allows someone to construct specially crafted form and present it to Logged in user, user after submitting this form may execute operation in your app that he didin't intended. Operation may be transfer, password change, or user add. And this is the threat you are worried about, if user holds session with your app and visits site with such form which gets auto-submited with JS such request gets authenticated, and operation executed. And httpOnly will not protect from it because attacker does not need to access sessionId stored in cookies. I recommend: CSRF

how secure is an iframe

I'm in the process of making a portal website and I wanted to include an iframe which would route people to an intranet. Is there any downsides to this as far as security is concerned?
I think that maybe there's a misunderstanding on your side regarding the function of IFrames: An <iframe> will not route anything. It just tells the user's browser which URL to fetch and show inside it. This means that
People need access to the intranet to actually load the contents of the <iframe>, which might not be what you expected.
It's not a security risk per se.
It is no more or less secure than giving those people direct web access to that intranet.
If you really want to know whether something is "secure" or not, you need to specify the types of threat that you need to protect against, what your tolerance is for breaks in that security, and what additional mechanisms that you have taken to secure your site (for example password authentication, NTLM, SSL, etc).

Is it secure to submit from a HTTP form to HTTPS?

Is it acceptable to submit from an http form through https? It seems like it should be secure, but it allows for a man in the middle attack (here is a good discussion). There are sites like mint.com that allow you to sign-in from an http page but does an https post. In my site, the request is to have an http landing page but be able to login securely. Is it not worth the possible security risk and should I just make all users go to a secure page to login (or make the landing page secure)?
Posting a form from an http page to an https page does encrypt the data in the form when it is transmitted in the most simple terms. If there is a man-in-the-middle attack, the browser will warn you.
However, if the original http form was subjected to man-in-the-middle and the https post-back address was modified by the attacker, then you will get no warning. The data will still actually be encrypted, but the man-in-the-middle attacker would be able to decrypt (since he sent you the key in the first place) and read the data.
Also, if the form is sending things back through other means (scripted connections) there may be a possibility of unencrypted data being sent over the wire before the form is posted (although any good website would never do this with any kind of sensitive data).
Is there any reason not to use HTTPS for the entire transaction? If you can't find a very good one, use it!
It's arguably simpler than switching protocols.
The MITM risk is real.
Following your link, the user "Helios" makes an excellent point that using 100% HTTPS is far less confusing to the user.
This kind of thing is popping up all over the net, especially in sites for which login is optional. However, it's inherently unsafe, for quite subtle reasons, and gives the user a false sense of security. I think there was an article about this recently on codinghorror.com.
The danger is that while you sent your page with a post target of "https://xxx", the page in which that reference occurs is not secure, so it can be modified in transit by an attacker to point to any URL the attacker wishes. So if I visit your site, I must view the source to verify my credentials are being posted to a secure address, and that verification has relevance only for that particular submit. If I return tomorrow, I must view source again, since that particular delivery of the page may have been attacked and the post target subverted - if I don't verify every single time, by the time I know the post target was subverted, it's too late - I've already sent my credentials to the attacker's URL.
You should only provide a link to the login page; and the login page and everything thereafter should be HTTPS for as long as you are logged in. And, really, there is no reason not to; the burden of SSL is on the initial negotiation; the subsequent connections will use SSL session caching and the symmetric crypto used for the link data is actually extremely low overhead.
IE Blog explains: Critical Mistake #1: Non-HTTPS Login pages (even if submitting to a HTTPS page)
How does the user know that the form is being submitted via HTTPS? Most browsers have no such UI cue.
How could the user know that it was going to the right HTTPS page? If the login form was delivered via HTTP, there's no guarantee it hasn't been changed between the server and the client.
Jay and Kiwi are right about the MITM attack. However, its important to note that the attacker doesn't have to break the form and give some error message; the attacker can instead insert JavaScript to send the form data twice, once to him and once to you.
But, honestly, you have to ask, what's the chance of an attacker intercepting your login page and modifying it in flight? How's it compare to the risk of (a) doing a MITM attack strait on the SSL session, and hoping the user presses "OK" to continue; (b) doing the MITM on your initial redirect to SSL (e.g., from http://example.com to https://example.com) and redirecting to https://doma1n.com instead, which is under the attacker's control; (c) You having a XSS, XSRF, or SQL injection flaw somewhere on your site.
Yes, I'd suggest running the login form under SSL, there isn't any reason not to. But I wouldn't worry much if it weren't, there are probably much lower hanging fruit.
Update
The above answer is from 2008. Since then, a lot of additional threats have become apparent. E.g., access sites from random untrusted networks such as WiFi hotspots (where anyone nearby may be able to pull off that attack). Now I'd say yes, you definitely should encrypt your login page, and further your entire site. Further, there are now solutions to the initial redirect problem (HTTP Strict Transport Security). The Open Web Application Security Project makes several best practices guides available.
This post is the key one. Yes, if the user's data is sent to you, it will have arrived somewhere securely. But there is no reason to believe that somewhere will be your site. The attacker isn't just going to get to listen to the data moving in each direction at this point. He'll be the other end of the user's session. The your site is just going to think the user never bothered to submit the form.
For me (as an end-user), the value of an HTTPS session is not only that the data is encrypted, but that I have verification that the page I'm typing my super-secrets into has come from the place I want it to.
Having the form in a non-HTTPS session defeats that assurance.
(I know - this is just another way of saying that the form is subject to an MITM attack).
No, it's not secure to go from HTTP to HTTPS. The originating and resulting points of the request must be HTTPS for the secure channel to be established and utilized.
Everyone suggesting that you provide only a link to the login page seems to be forgetting that the link could easily be changed using a MITM attack.
One of the biggest things missed out in all of the above is that there is a general trend to place a login on a home page (Huge trend in User Experience Trends).
The big problem here is that Google does not like to search secure pages with good reason, so all those Devs who are wondering why not make it all secure, well if you want your page invisible to Google, secure it all. Else, the second best option to post from http to https is the lesser of two evils at this point?
I think the main consideration of this question has to do with the URL that users know and the protocol scheme (http:)that browsers substitute by default.
In that case, the normal behavior of a site that wants to ensure an encrypted channel is to have the http://home-page redirect to https://home-page. There is still a spoofing / MitM opportunity, but if it is by DNS poisoning, the risk is no higher than if one starts out with the https: URL. If a different domain name comes back, you need to worry then.
This is probably safe enough. After all, if you are subject to a targetted MitM, you might as well start worrying about keyboard loggers, your local HOSTS file, and all sorts of other ways of finding out about your secure transactions involving your system already being owned.

Resources