Sambar Server Documentation

.htaccess Security


Overview
The most common use of .htaccess files is for restricting access to documents on an individual basis. Setting up user authentication consists of:

  • Creating a file containing usernames and passwords.
  • Telling the server what resources are to be protected and which users are allowed to access them.

Creating a User Database
By default, the Sambar Server uses the config/passwd file for user and group access permissions. The Users forms (under System Administration Security) can be used to dynamically modify this file via a browser interface. If no User Database is specified, this is the mechanism that is used.

It may be desirable to provide an alternative list of users and passwords for user authentication. To accomodate this use, the Sambar Server supports the "standard" user:password file format used by NCSA and Apache. Important! The default encryption mechanism used by the Sambar Server is not compatible with crypt which is used on Apache UNIX servers (the -d flag can be passwd to htaccess to use Unix crypt; the config.ini parameter Use Unix Crypt must also be set to true if you wish to use UNIX encryption). By default, both the Sambar Server passwd server config.ini file should set the Use Unix Crypt file and htpasswd files use the encryption mechanism implemented by the sacrypt utility shipped with the Sambar Server. Important! If using the sacrypt utility for generating password entries, the Public Key in the config.ini cannot be modified (Sambar Server Encryption Key) as this key is hardcode in the sacrypt utility.

The htpasswd file format consists of a list of usernames and passwords, with the username and password being separated by a colon. To be compatible with Apache and NCSA, an htpasswd program is provided for creating the user file and to add or modify users. At this time, DBM-type user authentication is not supported.

Using htpasswd
To create a new user database file and add the username "billy" with the password "bob" to the file C:\sambar\users

htpasswd -c C:\sambar\users billy

The -c argument tells htpasswd to create a new user file. When you run this command, you will be prompted to enter a password for billy and confirm it by entering it again. Other users can be added to the existing file in the same way, except the -c argument is not needed. The same command can also be used to modify the password of an existing user.

An optional -d argument tells htpasswd encrypt the passwords using the Unix crypt() functionality (allowing the file to be compatible with Apache Unix servers). To use this functionality, the server config.ini file should set the Use Unix Crypt parameter to true.

Important! For security reasons, the htpasswd file should not be placed under the documents directory.

Configuring the Sambar Server
The directives to create a protected area can be placed in a .htaccess file within the Sambar Server documents directory that should be restricted. The Sambar Server also supports the use of <Directory> and <Location> section directives like those found in the httpd.conf or access.conf files under Apache and NCSA. For system-wide security, the Sambar Server first looks for a config/htaccess file. Administrators can this "global" config/htaccess file to restrict access to any directory in the server and/or prevent users from over-riding security via per-directory .htaccess files. Important: For optimal performance, the AllowOverride none directive can be used in the config/htaccess file to eliminate per-directory lookups.

To restrict access to a directory using a .htaccess file, you must first ensure that the Sambar Server user authentication is enbled. The config/config.ini file parameter Enable .htaccess should be set to true. This parameter can be configured via the Server Configuration system administration forms.

To restrict a directory to any user listed in the users file (created in the preceeding section), you should create a .htaccess file containing:

AuthName      "Login to Secret Stuff"
AuthType      Basic
AuthUserFile  C:\sambar\users

require       valid-user

The following .htaccess example illustrates the most simple and straightforward access constraint used with the Sambar Server:

AuthName      "My Secret Stuff"
require       valid-user

This two line .htaccess file indicates that all content within and below this directory in which this file is located should only be available to "valid" Sambar Server users (users configured via the Users section of the System Administration Security page).

The .htaccess constraints are hierarchical, meaning that a constraint higher in the directory tree can affect contents nested below. When multiple .htaccess files are found within a hierarchy, the rules enforced are generally a composite of all rules found, unless override of the constraints are not permitted. Sambar Server Pro users can view a report on the ultimate rules that apply to a given directory using the Document Manager forms found in the Administrative console.

IMPORTANT!An unknown or malformed directive will cause the server to stop processing the .htaccess file and deny access with an Internal Server Error. Not all NCSA/Apache directives and/or directive options are supported. The maximum length permitted for any single directive line is 1024 bytes.

The following specifies the directives presently supported by the Sambar Server:

DirectiveUsage
<Directory path>Specifies that the directives following this line should only be applied to requests beneth the physical path location (case insensitive), i.e. c:/docs/samples. The directives are terminated by the </Directory> directive. Important! If the path being specified contains spaces, it must be quoted; in addition, all directory separators are translated to forward slashes (/) rather than the traditional Windows backward slash (\). (For regular-expression matching, use <DirectoryMatch>).
<DirectoryMatch regex> Provide access control just as the <Directory> directive does, however, it accepts a regular expression. For example:
<DirectoryMatch "^c:/www/.*/hidden">
would match sub-directories under "c:/www/" that contain the directory "hidden".
<Files filename>Specifies that the directives following this line should only be applied when the object basename being requested matches the filename (case insensitive), i.e. index.htm. The directives are terminated by the </Files> directive. Important! If the filename being specified contains spaces, it must be quoted. The filename argument may include a wild-card string, where ? matches a single character, and * matches any sequence of characters. (For regular-expression matching, use <FileMatch>).
<FilesMatch regex> Provide access control just as the <Files> directive does, however, it accepts a regular expression. For example:
<FileMatch "\.(gif|jp?g|png)$">
would match files ending in ".gif", ".jpg", ".jpeg", and ".png".
<Location url-path>Specifies that the directives following this line should only be applied to requests beneth the url-path location (case insensitive), i.e. /samples. The directives are terminated by the </Location> directive. (For regular-expression matching, use <LocationMatch>).
<LocationMatch regex> Provide access control just as the <Location> directive does, however, it accepts a regular expression. For example:
<LocationMatch "/(secure|hidden)/data">
would match URLs that contain the substring "/secure/data" or "/hidden/data".
<Host host-name>Specifies that the directives following this line should only be applied to requests directed to the host-name (case insensitive), i.e. www.sambar.com. The directives are terminated by the </Host> directive. (For regular-expression matching, use <HostMatch>).
<HostMatch regex> Provide access control just as the <Host> directive does, however, it accepts a regular expression. For example:
<HostMatch ".*sambar.*">
would match all *sambar* Hosts (i.e. www.sambar.com, www.sambar.net).
AllowOverride none | all The none directive specifies that no other .htaccess files can override the directives in this file. This directive has a performance benifit of allowing the server to stop traversing the hierarchy looking for .htaccess files. The all directive allows you to specifically re-enable htaccess parsing within a file; this directive only makes sense when AllowOverride none has been used in a file and then re-enabled within a specific Directory, Location or File section.
AuthNameSpecifies the realm name for this user authentication area. Once a user has entered a valid username and password, any other resources within the same realm name can be accessed with the same username and password. Note: Strings with spaces must be quoted.
AuthType Basic | Digest Specifies the protocol to be used for authorization. Both Basic and Digest are supported.
AuthUserFile <filename> Tells the server the location of the user file created by htpasswd. If this directive is missing, the Sambar Server config/passwd contents are used as the default. If the path provided does not include the "drive" (i.e. d:\sambar\users), the path is assumed to be relative to the Sambar Server configuration (config) directory. Important! You cannot explicitly specify the config/passwd for this directive as it does not follow the proper format.

Each line of the user file contains a username followed by a colon, followed by the crypt() or sacrypt() encrypted password. For security reasons, make sure the AuthUserFile is stored outside the document tree of the WWW server.

AuthGroupFile <filename> Tells the server the location of the groups file to used for authentication. If this directive is missing, the Sambar Server config/passwd contents are used as the default. If the path provided does not include the "drive" (i.e. d:\sambar\users), the path is assumed to be relative to the Sambar Server configuration (config) directory. Note: A user can belong to at most 200 groups. Important! You cannot explicitly specify the config/passwd for this directive as it does not follow the proper format.

Each line of the group file contains a group name followed by a colon, followed by the member usernames separated by spaces. Example:

mygroup: bob joe sue
AuthMethod <method> Specifies the method to be used for authorization. If an AuthUserFile is specified, this directive is ignored. All other authentication directives needed by the specified mechanism are must be configured in the configuration file. See the authentication documentation for details of each method.
passwd Use the Sambar Server config/passwd file.
ntauth Use the NT Authentication mechanism.
sqlauth Use the SQL Server authentication mechanism.
radius Use the Radius Server authentication mechanism.
AuthSQLQuery <sql-query> Specifies SQL query that should be used for authentication. This is used to override the SQL AUTH Query in the config/config.ini and is only used if the AuthMethod is set to sqlauth.
AuthSQLCache <cache-name> Specifies database cache that should be used for authentication. This is used to override the SQL AUTH Cache in the config/config.ini and is only used if the AuthMethod is set to sqlauth.
AuthPage <auth-page> Specifies the URL of the HTML page to return to the user rather than a 401 error message when a user fails to authenticate. By default, when require is used to ensure a valid user login, a 401 error code is returned if the user fails to authenticate. The browser recieves this error code and throws a pop-up dialog instructing the user to login. If you wish to return an HTML page in place of the 401 error dialog, this instruction can be used along with the full URL of the page to display. The authentication page must begin with a slash (/) and must be outside the directory being protected. If the AuthPage is in a protected directory, an infinite loop will be created.
ReauthPage <auth-page> Specifies the URL of the HTML page to return to the user rather than a 401 error message when a user fails to authenticate for the section they are access, but is already authentiated. This directives differs slightly from the AuthPage directive in that it allows you to craft a page indicating that the current credentials the user has authenticated with are insufficient to access the area requested and gives you the opportunity to craft a page explaining the additional login requirements. By default, when require is used to ensure a valid user login, a 401 error code is returned if the user fails to authenticate. The browser recieves this error code and throws a pop-up dialog instructing the user to login. If you wish to return an HTML page in place of the 401 error dialog, this instruction can be used along with the full URL of the page to display. The re-authentication page must begin with a slash (/) and must be outside the directory being protected. If the ReauthPage is in a protected directory, an infinite loop will be created.
AuthDuration <seconds> Indicates that the credentials associated with a successful authentication should be permitted beyond the scope of the single call for use. the realm name for this user authentication area. Once a user has entered a valid username and password, a cookie is returned permitting access to the resource on subsequent calls without subsequent authentication for the duration specified (in seconds). This feature is useful for one-time ticket based authentication systems or when repeated authentication requests are inappropriate due to performance or load considerations.
require valid-userSpecifies that any user found in the user database can access the the area.
require user user1 user2... userNSpecifies a space-separated list of users that can access the area. i.e.
require user billy ray
require group group1 group2... groupNSpecifies a space-separated list of groups that can access the area. i.e.
require group engineering marketing

If both a require user and a require group are defined, any user in the listed groups, or any user listed explicitly can access the resource.

norequire from ip1 ip2... ipNSpecifies a list of IP addresses which a valid-user authorization is not required to access the area. This IP list over-rides the require directives. Wild-card pattern matching can be used within the IP addresses (i.e. * and []). Note: Only IP address may be specified unless DNS address resolution is turned on, in which case hostnames should be provided.
requireSSL from ip1 ip2... ipNSpecifies a list of IP addresses which SSL access is required to access the area. Wild-card pattern matching can be used within the IP addresses (i.e. * and []). Note: Only IP address may be specified unless DNS address resolution is turned on, in which case hostnames should be provided.
norequireSSL from ip1 ip2... ipNSpecifies a list of IP addresses from which SSL access is not required to access the area. All IP addresses not in this list will be required to access the server via SSL. Wild-card pattern matching can be used within the IP addresses (i.e. * and []). Note: Only IP address may be specified unless DNS address resolution is turned on, in which case hostnames should be provided.
allow from allAllow access from all hosts.
allow from ip1 ip2... ipNSpecifies a list of IP addresses which are allowed access to the area. Wild-card pattern matching can be used within the IP addresses (i.e. * and []). Note: Only IP address may be specified unless DNS address resolution is turned on, in which case hostnames should be provided. i.e.
allow from 192.164.170.128 193.160.*
deny from allDeny access from all hosts.
deny from ip1 ip2... ipNSpecifies a list of IP addresses which are denied access to the area. Wild-card pattern matching can be used within the IP addresses (i.e. * and []). Note: Only IP address may be specified unless DNS address resolution is turned on, in which case hostnames should be provided.
order deny,allowSpecifies that the deny directives are evaluated before the allow directives (the initial state is OK.)
order allow,denySpecifies that the allow directives are evaluated before the deny directives (the initial state is FORBIDDEN.) Note: This is the default.
order mutual-failureSpecifies that only those hosts which appear on the allow list and do not appear on the deny list are granted access.
satisfy anyIt is possible to restirct both by username (via require) and hostname (via allow) restrictions at the same time. The server will require that both restricts be satisfied unless the satisfy any directive is specified.
ExpiresActive on | off Enables or disables the generation of the Expires header for the documents generated from the directory in which the .htaccess applies. If set to off, no Expires header will be generated unless overridden at a lower level. If set to on, the header will be added (following any applicable ExpiresByType and ExpiresDefault directives.)
ExpiresByType mimetype <code>seconds Defines the value of the Expires header generated for documents of the specified type (i.e. text/html or text/*). The second argument specifies the number of seconds added to the base time to construct the expiration date. A <code> of M indicates that the files last modification time should be used as the base time, an A means the client's access time should be used. i.e.
ExpiresActive on # enable expirations
ExpiresByType image/gif A2592000 # expire GIFs after one month
ExpiresByType text/html M604800 # expire HTML files one week after they were last changed
ExpiresDefault <code>seconds Sets the default algorithm for calculating the expiration time of all documents generated from the directory in which the .htaccess applies.
ErrorDocument status <error-page> Return the error-page (Sambar Server script, ASP, or HTML data) to the user for all errors corresponding to the status. Important: The path to the error-page is always relative to the documents directory; the error-page must begin with a slash (/).
<ErrorDocument 500 /cgi-bin/servererror.pl>
<ErrorDocument 401 /sitemap.htm>
PrependMacro mimetype <macro-name> Prepend a macro data (from config/macros.ini) to the output of all content matching the mimetype served from the directory in which the .htaccess applies. Note: Feature not available for JSPs. Mime types can be wildcarded (i.e. text/*)
AppendMacro mimetype <macro-name> Append a macro data (from config/macros.ini) to the output of all content matching the mimetype served from the directory in which the .htaccess applies. Example usage:
AppendMacro text/html PUBLIC_FOOTER
Note: Feature not available for JSPs. Mime types can be wildcarded (i.e. text/*)
PrependScript mimetype <script-file> Prepend a Sambar Server script file to the output of all content matching the mimetype served from the directory in which the .htaccess applies. Important: The path to the script-file is always relative to the documents directory; the script-file must begin with a slash (/).
Usage Note: The PrependScript is not evaluated until the initial contents of the request file are returned. Because of this, any script assignments in the request file that utilize variables from the PrependScript must appear after the <HTML> header. Note: Feature not available for JSPs and only applies to GET and POST requests. Mime types can be wildcarded (i.e. text/*)
AppendScript mimetype <script-file> Append a Sambar Server script file to the output of all content matching the mimetype served from the directory in which the .htaccess applies. Note: The path to the script-file is always relative to the documents directory; the script-file must begin with a slash (/). Note: Feature not available for JSPs and only applies to GET and POST requests. Mime types can be wildcarded (i.e. text/*)
Compress mimetype Compress all content generated by the Sambar Server that matches the mimetype served from the directory in which the .htaccess applies. Note: Content is only compressed if the client sends Accept-encoding: gzip in it's header, reglardless of this directive. Mime types can be wildcarded (i.e. text/*)
CompressMatch <regex-match> Compress all content generated by the Sambar Server that matches the regular expression served from the directory in which the .htaccess applies. Note: Content is only compressed if the client sends Accept-encoding: gzip in it's header, reglardless of this directive. For example:
<CompressMatch "\.(htm?|jsp|php)$">
would match files ending in ".htm", ".html", ".jsp", and ".php".
Header set name value Directive to control the sending of HTTP headers. Presently only the ability to set headers is supported. The response header is set, replacing any previous header with this name.
NotifyOnChange e-mail address(s) Send an email notifycation to the comma-separated list of users specified if a file is created, updated, checkin, or deleted to the directory in which the .htaccess applies. The SMTP Server parameter or mail server must be configured to allow the sending of mail. Note: This parameter will typically be applied to modifications made via the FTP server or Document Manager.
IMOnChange IM-address(s) Send an IM notifycation to the comma-separated list of users specified if a file is created, updated, checkin, or deleted to the directory in which the .htaccess applies. The IM Server must be enabled and the recipients must be local users and be online. This parameter will typically be applied to modifications made via the FTP server or Document Manager.
RedirectMatch [permanent | temp | gone] <regex-match> <url> Redirect all requests that match the regular-expression (<regex-match>) to the URL specified. For example:
RedirectMatch permanent (.*)\.gif$ /moved.html
RedirectMatch permanent (.*)\.exe$ http://www.microsoft.com/
RedirectMatchUrl [permanent | temp | gone] <regex-match> <url> Redirect all requests that match the regular-expression (<regex-match>) to the URL specified and appends the original URI. For example:
RedirectMatch permanent (.*)\.exe$ http://www.microsoft.com/downloads
The request http://localhost/a/b/c.exe would be redirected to http://www.microsoft.com/downloads/a/b/c.exe.
RedirectMatchFile [permanent | temp | gone] <regex-match> <url> Redirect all requests that match the regular-expression (<regex-match>) to the URL specified and appends the document requested. For example:
RedirectMatch permanent (.*)\.exe$ http://www.microsoft.com/downloads/
The request http://localhost/a/b/c.exe would be redirected to http://www.microsoft.com/downloads/c.exe.
options <key-word(s)> The options directive allows you to control what actions someone may take in this directory and sub-directories. You may specify one or more of the following keywords.
none No features are allowed
all All features are allowed
NoDelete WebDAV, Document Manager and FTP server users are not allowed to delete files from this directory.
NoDBMS Scripts run in this directory are not permitted to access DBMS caches.
NoExec Scripts are not allowed to be executed in this directory (applies to Sambar Server *.stm, *.jsp, CGI scripts, ISAPI, and SSI includes that execute either CGIs or non-virtual file paths.)
NoIncludes Server-side includes are not allowed in this directory
NoCGI CGI scripts are not allowed to be executed in this directory
NoISAPI ISAPI DLLs are not allowed to be executed in this directory
NoASP ASP scripts are not allowed to be executed in this directory
NoJava Java scripts (i.e. *.jsp) are not allowed to be executed in this directory
NoDirlist Directory listings are not permitted.
RequireSSL Access to the contents requires use of the SSL interface.
RedirectSSL Access to the contents requires use of the SSL interface; automatically redirect the request to the SSL interface (https).
NoSSL Access to the contents requires the client NOT use SSL.
RedirectNoSSL Access to the contents requires the client NOT use SSL; automatically redirect the request to the non-SSL interface (http).
LoginOnAuth Create a server-side USER session (full login) when authenticating via .htaccess rule.td>
Dirlist Directory listings are permitted for this directory tree. Note: 'options all' does not implicitly enable this feature.

Using Groups
By default, the groups restriction applies to the single group associated with the user in the Sambar Server config/passwd file. However, a group file can be created and used to associate a user with numberous groups. A groups file is also convienent if there are many users for a given user authentication area.

A group file consists of lines giving a group name followed by a space-separated list of users in that group. For example:

engineering: tod billy
marketing: stacia admin

Limiting Methods Differently
In the example .htaccess file above, the require directive is not given inside a <LIMIT> section. This is valid in both the Sambar Server and Apache, and means that the directive applies to all request methods. You can use the <LIMIT> section to specify the request methods to which the directive applies:

<LIMIT GET POST PUT DELETE FTP WEBDAV>
require valid-user
<LIMIT>

For example, to limit just the PUT method, the .htacess would be:

AuthName     Restricted Uploads
AuthType     Basic

<LIMIT PUT>
require      valid-user
<LIMIT>

Now, only valid Sambar Server users would be allows to PUT (upload) files to the specified directory. Other users (unauthenticated) can use other methods such as GET and POST to access content in the directory.

As the original example illustrates, FTP access to subdirectories may also be restricted using the LIMIT section. This functionality is designed to prohibit access to a subdirectory which an FTP user would otherwise be granted access. So, even though a user might have an FTP "root directory" of /docs, a subdirectory within the /docs directory tree can be restricted.

The WEBDAV directive is used to limit access to a directory via the Sambar Server Document Manager and WebDAV interfaces. This directive is often used in conjunction with the FTP access directive to prohibit users from modifying a directory under which they would otherwise have full privileges. This directive is the superset of the finer-grained WebDAV=specific directives: GET, PUT, DELETE, COPY, MOVE, LOCK, UNLOCK, CHECKIN, CHECKOUT, UNCHECKOUT.

<LIMITEXCEPT> and </LIMITEXCEPT> are used to enclose a group of access control directives which will apply to any HTTP access methods not listed in the arguments. For example, the following allows read-only access to a directory, and requires a login to perform any updates (via WebDAV or the Document Manager).

<LIMITEXCEPT GET HEAD OPTIONS>    require valid-user </LIMITEXCEPT>

Regular Expression Hints

Text:
    .
    [chars]
    [^chars]
    text1|text2


Any single character.
Character class: One of chars
Character class: None of chars
Alternative: text1 or text2
Qualtifiers:
    ?
    *
    +


0 or 1 of the preceeding text
0 or N of the preceeding text (N > 0)
1 or N of the preceeding text (N > 1)
Grouping:
    (text)


Grouping of text
(either to set the borders of an alternative
or for making backreferences where the Nth
group can be used on the right-hand side of a
RewriteRule with the $N)
Anchors:
    ^
    $


Start of line anchor
End of line anchor
Escaping:
    \char


escape that particular char
(for instance to specify the characters ".[]()" etc.)

© 1998 Sambar Technologies. All rights reserved. Terms of Use.