+ All Categories
Home > Documents > Securing SQL Anywhere Server 10

Securing SQL Anywhere Server 10

Date post: 08-May-2015
Category:
Upload: databaseguys
View: 2,015 times
Download: 14 times
Share this document with a friend
46
Securing SQL Anywhere Server 10 A whitepaper from iAnywhere Solutions, Inc., a subsidiary of Sybase, Inc.
Transcript
Page 1: Securing SQL Anywhere Server 10

Securing SQL AnywhereServer 10

A whitepaper from iAnywhere Solutions, Inc.,a subsidiary of Sybase, Inc.

Page 2: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

ContentsIntroduction 3

Why bother with security? 4

Pre-installation security procedures 5Securing the physical machine . . . . . . . . . . . . . . . . . . . . . . . . 5Network security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Securing the operating system . . . . . . . . . . . . . . . . . . . . . . . . 5Securing mobile devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6IT policies and procedures regarding mobile devices . . . . . . . . . . . . 8

Database access and permissions 9User accounts and permissions . . . . . . . . . . . . . . . . . . . . . . . . 9Integrated logins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10Kerberos authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Directory services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11User password policies . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Using a custom login procedure . . . . . . . . . . . . . . . . . . . . . . . 12Disabling database features . . . . . . . . . . . . . . . . . . . . . . . . . . 13Securing access to SQL Anywhere utilities . . . . . . . . . . . . . . . . . 14Debugging database activity . . . . . . . . . . . . . . . . . . . . . . . . . 16Securing SQL Anywhere configuration files . . . . . . . . . . . . . . . . . 17Database auditing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Securing backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Securing web services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Data protection with encryption 21Encryption types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Communication encryption 27Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Digital certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Enabling communications encryption . . . . . . . . . . . . . . . . . . . . . 30Performance analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

SQL injections 32Preventing SQL injections . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Injections in the URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

Conclusion 34

Appendix A: SQL Anywhere security checklist 35

Appendix B: Guidelines for strong passwords 36

Appendix C: Social engineering 38

Appendix D: Sample password verification function 39

1

Page 3: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

Legal Notice 45Contact Us . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

2

Page 4: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

IntroductionIn today’s IT world, where computers and computer-enabled devices are a crucialpart of any business, it has become a necessity to ensure that proper informationsecurity practices are implemented. With businesses storing more and more dataabout their daily activities in electronic form, failing to enforce proper securityprocedures can lead to unwanted problems and expose a business tounnecessary danger.

When it comes to information security, it is crucial to pay attention the componentof IT infrastructure that actually stores and transmits information—the databaseserver. Failing to secure a database server can make it the weak link that anunauthorized person can exploit to obtain crucial business data. Also, datacommunications into and out of the database server have to be properly securedto prevent instances of eavesdropping and intentional data corruption.

The biggest security breaches to receive national media attention in recentmonths have all involved the loss or theft of sensitive, personal data. Examplesinclude the U.S. Health and Human Services department, where Social Securitynumbers and other personal information for nearly 17000 Medicare beneficiariescould have been compromised when an insurance company employee called upthe data through a hotel computer and then failed to delete the file. Such incidentsnot only tarnish the name and reputation of the organization involved, but alsopose a very real danger of identity and financial theft.

This whitepaper first discusses the security infrastructure that is required toprevent unauthorized access to business data, and then focuses on the stepsneeded to secure a SQL Anywhere 10 database server installation properly. SQLAnywhere 10 is a leading database in the small to medium enterprise databasemarket, as well as a leading database offering for mobile devices. With its strongmobile solutions, it is important to pay attention to securing the database serveritself, as well as the communication transmissions between the database serverand mobile databases. Not all of the techniques and methods described in thispaper lend themselves to both a mobile and a server environment. For example,physical security of hardware is a much more difficult problem with mobile devicesthan it is with server or desktop hardware.

There are four general areas that must be addressed in order to secure a SQLAnywhere 10 database:

♦ Pre-installation security This encompasses the physical and networksecurity of the server running the database, as well as the security of theunderlying operating system.

♦ Database access and permissions You should pay the most attention tothis area because securing a database largely involves securing access to it.This includes user accounts and permissions, authentication methods,password policies, backup security, and so on.

♦ Database encryption For maximum security, a database should always beencrypted with a strong encryption key.

3

Page 5: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Communication encryption No matter how secure a database file is, onceit starts sending data over a network, that data becomes susceptible tointerception and abuse. It is recommended that you use the built-intransport-layer security in SQL Anywhere to encrypt communication andsecure traveling data.

Why bother with security?With the rise of the Internet and corporate computer networks, information hasbecome a key commodity for businesses. The loss of information can, in somecases, result in incredible difficulties for a business. As a result, most enterprisesare at least aware of (or have in place) security procedures and preventativemeasures to deal with the very real threat of data theft and/or loss.

This raises the question of how much a security-conscious organization shouldspend. The answer to this question is not simple, because in addition to theprimary, tangible results of information security spending, there exist secondary,invisible costs. Although the primary costs associated with information securityare not small in most cases, it is the secondary costs that should be consideredfar more carefully. It is the secondary costs that determine the size of the primaryones.

Primary security costs include the quantifiable charges a business will incur whileincreasing its preventative measures. These can include security personnel,administrative personnel, cost of facilities, cost of computer equipment, securityconsultant costs, physical security measures, and so on. It is estimated thatbusinesses spend approximately 30% of their IT budgets on security. The totalamount of primary costs can run into the millions of dollars for large enterprises.

Secondary costs are future, worst-case-scenario costs. Because of their moreintangible nature, these costs can never be measured perfectly. They are thecosts that the business may incur in the case of data loss or theft. These varygreatly with the amount and type of data stored, but are never zero, and couldpotentially lead to the death of the business. These costs include the following:

♦ Time No matter what type of data is lost/stolen, the amount of time to getthat data is always a cost. This includes public stores of data that are widelyavailable because you still have to make sure that the integrity of the data hasnot been compromised.

♦ Legal costs A business may be legally obligated for the customer data itstores (depending on country or state law). In the case of a lawsuit due to dataloss, the costs to a business could be massive. Besides a possibly largesettlement, there are also extensive legal fees involved in any court case.

♦ Lost opportunity costs Data loss usually results in downtime. Even ifdowntime is minimized because proper backups are made on a regular basis,in today’s information and Internet-driven world, downtime is equivalent to lossof productivity in terms of time or sales, both of which are non-recoverable.

♦ Lost credibility A breach in security can cause stakeholders (such as

4

Page 6: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

employees, customers, or partners) to lose trust, and regaining that trust canbe a difficult and time-consuming process.

In the end, it is up to the business to determine the amount that should be spenton primary security costs. To do this properly, the worst-case scenario secondarycosts have to be kept in mind. When it comes to information security, prevention isnot only better than the cure, but it can mean the difference between survival andbankruptcy for the enterprise.

Pre-installation security proceduresThis section outlines steps that are taken outside of SQL Anywhere that helpincrease the security of the database server. These steps deal with generalserver precautions, operating system security, and so on.

Securing the physical machine

Securing any server setup has to begin with the physical nature of the server. Nomatter how protected the server software is, most software security measures areineffective if an unauthorized person has physical access to a machine. Besideshardware theft, a number of software tools are available for gaining administratorprivileges on a server, which can subsequently be used to perform variousmalicious activities.

Therefore, it is imperative that any database server is stored in a physicallyprotected location, such as a secure server room, which requires specific entrycredentials. Also, the server room should ideally have flood detection, as well asfire detection and fire suppression systems.

Network security

After the server is physically safe, the issue of securing network access to theserver needs to be addressed. First of all, the database server should not bedirectly exposed to the Internet. Data should always be accessed throughmiddleware software systems, so that the connection mechanisms to thedatabase are never exposed. For example, when SQL Anywhere MobiLinkdatabase synchronization is used, the mobile devices themselves are by defaultunable to talk to the database directly, and instead have to communicate with aMobiLink server, which then talks to the backend database server.

Most businesses are aware of the need for proper firewalling. It is imperative thatfirewall policies be as conservative as possible, only allowing communication withan internal network computer. Holes should not be punched in the firewall (suchas exposing the default SQL Anywhere connection port 2638) without carefulconsideration.

Securing the operating system

The operating system running the database server should be dedicated solely for

5

Page 7: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

that purpose. Disable all unnecessary services and daemons (FTP, Telnet, and soon) to eliminate the possibility of unauthorized access to the database because ofa security flaw in another piece of software. Finally, all relevant security updatesfor the operating system need to be downloaded and installed on a regular basis.

Also, care should be taken with respect to operating system user accounts. Onlyusers with administrator privileges should be allowed to have access to thedatabase executables and data files. Moreover, if network authentication is used,the database server should not be started using a local (non-network) useraccount. Permissions to start and stop processes should also be tightly controlledto prevent users from intentionally or accidentally stopping the database server.

Securing mobile devices

Using mobile devices can pose a significant security danger for a business if youdo not take proper security precautions. This danger increases significantly if amobile device is able to access data remotely that is contained in a business’sdatabase. To avoid the possible problems that mobile devices can present, whilereaping the numerous benefits that they provide, such devices have to be securedin the following three areas.

Access to the device

Because of their small size, mobile devices are easily lost or stolen. According toexperts, when it comes to security threats against data on mobile devices,malware, viruses, and worms still don’t come close to loss and theft. Therefore, itis imperative that proper preventative measures are taken to ensure that in theevent of an unauthorized user gaining access to a mobile device, they are unableto use that device in any malicious way.

In this area, the primary focus falls on implementing strong and conservativeauthentication procedures to protect a mobile device against unauthorizedaccess:

♦ Operating system power-on passwords This is a feature that is availablein most mobile operating systems today. This is the most basic form of mobiledevice security, but it is also one of the most effective. Contemporary operatingsystems also have built-in punishment features if a system password is enteredincorrectly, such as Windows Mobile increasing the delay between successivepassword entries, or Blackberries erasing all data on the device after 10 suchunsuccessful attempts.

♦ Remote device management This refers to the ability of networkadministrators to change the security options on mobile devices remotelywithout user intervention. Not implementing this feature could result in somemobile devices having less stringent security policies than the rest of theorganization.

♦ Application-level security Although a mobile device should have a system,power-on password, it is highly recommended that execution of all crucialapplications be password protected as well (if such an option is available).

6

Page 8: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Certificates Mobile devices today usually support the storage of certificatesfor authentication purposes. This can be extremely useful when you are addingand removing the login privileges of a certain user or group of users remotely.

♦ Non-traditional authentication In recent years a number ofnon-text-password options have surfaced, particularly because of the growingmobile sector and the more realistic appreciation of the dangers facing mobileauthentication. These methods can either replace or work in tandem withtraditional password practices to increase the security quotient of a mobiledevice. They include: signature authentication, picture-based passwords,fingerprint authentication, and Smart Card/SecurID Card authentication.

Access to the data stored on the device

Although securing device accessibility is an important step to preventingunauthorized access, the use of removable media such as flash or USB drivesmakes it vitally important to protect the data contained on the device itself. Thisbecomes the only defense if the authentication protection of the device itself iscircumvented (via password cracking or stealing) or is non-existent.

Securing access to data primarily involves data encryption. SQL Anywhereincludes strong encryption capabilities to protect the data it stores. In general,however, it is also recommended that you encrypt other files on the mobile devicefor increased protection. This includes encrypting the data on storage mediums,as well as data stored in RAM during normal operation to prevent data snooping.

Access to the company network

Having strong security policies for network access is also an importantconsideration. This area has two facets: securing access to the corporatenetwork and securing communication with the corporate network.

Any corporate network should have security features in place to ensure that onlydevices that are deemed friendly are allowed to connect to it. This preventsemployees from connecting their personal devices to the network and alsodecreases the chance of corporate espionage (for example, someone hiding amobile device that can connect to the network and gather data automatically). Youcan restrict access to the company network through such measures as dial-uppasswords, network authentication protocols for secure web sites, and VPNauthentication.

It is also vital that, after successful network authentication, all traffic between thedevice and the network be encrypted. SQL Anywhere provides transport-layersecurity (TLS) by encrypting communications using approved industry standardalgorithms that are extremely difficult and time consuming to decrypt givenexisting technology. Although the business data communication between mobileand consolidated deployments of SQL Anywhere can be considered secure,network and system administrators have to make sure that all othercommunication with a mobile device is also protected. Therefore, all criticalapplications should support native encryption of communication data. If the

7

Page 9: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

mobile device is able to connect to a VPN, all communication should be encryptedwith industry-standard, proven encryption techniques.

iAnywhere Afaria

When considering mobile device security, iAnywhere Afaria can help resolvemany of the abovementioned issues. Afaria is the industry leading total mobiledevice management solution that covers all of the security areas discussedabove, from patch management and security management, to remote control andnetwork security. Afaria assists the enterprise in the following areas of mobile ITmanagement:

♦ Security Afaria provides the following features to increase device security:• Patch management Afaria provides precise control over which patches

are deployed and where they are deployed. Patch distribution is automaticand exact logs are kept.

• Security management Afaria provides full disk encryption combined withthe ability to set power-on passwords, automatic certificate rollout, secure fullsystem data deletion, remote reset capabilities, and so on.

• Data backup Afaria provides automatic backup and restoration of data,profiles, and configurations for remote devices.

♦ Process automation Afaria automates and schedules processes, such asfile transfers and hard disk checks.

♦ Data and content management Afaria allows for easy and securedocument distribution and control, as well as synchronizing to and from variousdocument formats.

♦ Systems management extensions Afaria lets you control the softwaresettings on all mobile devices from company headquarters, using a singleconsole.

♦ Software and inventory management Afaria provides comprehensivecapabilities for managing software installations, licensing, updates, rollbacks,and remote control.

IT policies and procedures regarding mobile devices

Besides securing access rights to mobile devices and their data, an IT departmentshould have a solid set of policies and procedures in place to manage their mobileinventory, and to make sure that all users are educated on their responsibilitieswith regard to hardware assigned to them. Implementing policies and procedureslike the following ultimately benefits the security of the organization as a whole:

♦ Maintain an inventory of all company mobile devices and who currently haspossession of them.

♦ Implement remote patch management procedures. This will allow you to patchdevices in groups, reducing the risk that a device is left without the necessarysecurity bug fixes.

8

Page 10: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Establish procedures to disable the remote access rights of any mobile devicethat is lost or stolen. These should also include measures to erase all userauthentication information that the device contained (such as passwords).

♦ Erase all data from mobile devices that are not in use or when such deviceschange ownership, or are lost or stolen. This minimizes the amount of data thatcould be compromised if the device is stolen.

♦ Use the services of third-party companies that specialize in the retrieval of lostmobile devices.

♦ Standardize the software applications installed on company mobile devicesand restrict the user’s ability to install additional software.

Database access and permissionsThis section outlines how database accounts should be configured for securedatabase operations.

User accounts and permissions

User IDs should be created for every unique user (given a small number of users)or role (if a large number of people are connecting to the database). This allowsthe DBA to fine tune the permissions that each user ID has in order to restrictwhat that user can do in the database. Having unique user IDs also simplifies theprocess of determining which user was responsible for a certain action. See“Database auditing” on page 18.

In order to secure a SQL Anywhere database server, the following issues must beaddressed:

♦ Restrict DBA authority Users with DBA authority have the power to doanything on a database server. DBA authority is generally not needed fornormal user activity and poses a security threat if it is assigned carelessly.Also, the DBA login credentials should be kept very safe, known to only ahandful of people who have legal obligation not to divulge such information.

♦ Starting databases By default, any user can start a database on a runningdatabase server. Use the -gd option to set the permissions required to startand stop databases.

☞ For more information, see the -gd server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-gd-database-dbengine.html.

♦ Creating databases By default, any user can create a database with theCREATE DATABASE statement. Use the -gu option to set permissionsrequired to create databases.

☞ For more information, see the -gu server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-gu-database-dbengine.html.

9

Page 11: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Stopping the database server By default, any user can use the dbstoputility to shut down a database server. Use the -gk option set the permissionsrequired to stop the database server.

☞ For more information, see the -gk server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-gk-database-dbengine.html.

♦ Loading and unloading data The LOAD TABLE, UNLOAD TABLE, andUNLOAD statements all access the underlying file system of the server. Thiscould potentially be a security issue, and it is recommended that access to theabove statements is restricted using the -gl command.

☞ For more information, see the -gl server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-gl-database-dbengine.html.

♦ Revoke all non-crucial permissions Using the GRANT and REVOKEstatements, do not give users and groups permissions which they do not needfor their normal day-to-day work.

☞ For more information, see GRANT statement and REVOKE statement inSQL Anywhere Server - SQL Reference, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbrfen10/rf-grant-statement.html.

Integrated logins

Integrated logins allow users to use a single login name and password to log on toboth your Windows operating system and onto a database. An external loginname (or user group) is associated with a database user ID.

Integrated user IDs can bring a number of security advantages. First, if a user IDis integrated into SQL Anywhere, that user does not need remember a databaseuser ID and password. Besides the obvious ease-of-use for the user, the usernever knows an ID and password combination that can be used to compromisethe database (intentionally or accidentally). This also allows the DBA to grant orremove a user’s database access permissions very quickly. Moreover, since awhole group of Windows users could be configured to log in with a singledatabase user ID and password, user account administration becomes easier forthe DBA.

You need to take some precautions when using integrated logins to minimizesecurity problems in Microsoft Windows. First, the Guest user account inWindows should be disabled. The Guest user account has no password, and ifthe integrated logins are not configured properly, a malicious user could gaindatabase administrator access rights to the database server. Also, if the Windowsoperating system is compromised and user login information is stolen, a malicioususer could gain unrestricted access to a database.

☞ For more information about integrated logins, see “Using Integrated Logins” inSQL Anywhere Server - Database Administration, or

10

Page 12: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

http://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-using-an-integrated-login.html.

Kerberos authentication

SQL Anywhere supports Kerberos authentication. Kerberos is a networkauthentication protocol that provides strong authentication and encryption usingsecret-key cryptography. SQL Anywhere can use Kerberos for authentication in amanner similar to Windows integrated logins. Users who have already logged into Kerberos can connect to a database without providing a user ID or password.Kerberos logins offer the convenience of a single security system, but there areimportant security implications that database administrators should be familiarwith (such as a single point of failure and clock synchronization).

☞ For more information about Kerberos authentication logins, see “UsingKerberos Authentication” in SQL Anywhere Server - Database Administration, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-connect-s-5294913.html.

Directory services

SQL Anywhere has built-in LDAP support, allowing the querying of LDAPdirectory services to find database servers. Client databases can use the ServerLocation utility (dblocate) to query a directory service to find a consolidateddatabase without knowing its exact network address. For example:

dblocate customerDatabaseServer

One reason directory services with LDAP access have become commonplace intoday’s enterprises is because of the increased security they provide. Directoryservices allow for easier user, resource, and security policy management, as wellas the ability to effectively hide the network IP information of a database server.

Although finding databases with the dblocate utility has a number of advantagesfrom a management perspective, sometimes it is preferable to hide a databaseserver from being discovered by the utility. For this, use the -sb option whenstarting the database server.

☞ For more information, see the -sb server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-sb-database-dbserver.html.

User password policies

Weak passwords are often referred to as the Achilles heel of many computersystems. When it comes to the passwords used to access a database server, theplace containing vital data for the survival of a business, a password that is easyto guess could bring about disastrous consequences. The following techniquescan help improve password security:

11

Page 13: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Minimum password lengths The longer a password is, the more difficult itbecomes to crack it using computer-based password guessing programsbecause of the increasing number of possible character combinations. You canset the minimum password size using the min_password_length option. Forexample, the following sets the minimum password length to 8 characters:

SET OPTION PUBLIC.min_password_length = 8

♦ Enforce password management policies All users should be made awareof a company’s acceptable password policies (such as complexity andrandomness) and such policies should be strictly enforced. You can use thepassword verification option verify_password_function to make sure that userpasswords conform to safe standards.

☞ For more information about choosing secure password guidelines, see“Appendix B: Guidelines for strong passwords” on page 36.

☞ For a sample password verification function, see “Appendix D: Samplepassword verification function” on page 39.

♦ User password expiration You can also use the verify_password_functionoption to specify a time period after which a password becomes invalid. Thisincreases database security in the event that an old password, alreadyautomatically disabled, is compromised.

☞ For an example of such an implementation, see “Appendix D: Samplepassword verification function” on page 39.

♦ Change the default DBA password The default password for the databaseDBA (administrator) account is sql . This should be changed immediately afterdatabase creation, and before a database server is set up to acceptconnections over the network. To maximize security, a new user ID should becreated with DBA permissions (and a sufficiently strong password), and thebuilt-in DBA account should be disabled.

♦ Do not include passwords in ODBC data sources When you create anODBC data source, you are given the option to store the data sourcepassword. Avoid storing such passwords to achieve greater security.

♦ Limit the number of failed login attempts You can leverage features suchas login procedures to limit the number of unsuccessful login attempts for auser. Once that number is reached, the user account should be locked out andan administrator contacted to address the problem.

Using a custom login procedure

To develop more detailed control over login permissions to the database server,you can create a stored procedure that is called automatically whenever a userattempts to log in. This is done using the login_procedure option and can helpfurther secure a SQL Anywhere database server.

☞ For more information about setting up a custom login stored procedure, seethe login_procedure option in SQL Anywhere Server - Database Administration,

12

Page 14: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

or go to http://www.ianywhere.com/developer/product_manuals/-sqlanywhere/1000/en/html/dbdaen10/da-login-procedure.html.

The following SQL example shows how you can disallow a connection bysignaling an INVALID_LOGON error:

CREATE PROCEDURE DBA.login_check()BEGIN

DECLARE INVALID_LOGON EXCEPTION FOR SQLSTATE ’28000’;// Allow a maximum of 3 concurrent connectionsIF( DB_PROPERTY(’ConnCount’) > 3 ) THEN

SIGNAL INVALID_LOGON;ELSE

CALL sp_login_environment;END IF;

ENDgo

GRANT EXECUTE ON DBA.login_check TO PUBLICgo

SET OPTION PUBLIC.login_procedure=’DBA.login_check’go

Disabling database features

If certain features are not needed in the database server in your environment, usethe -sf server option to disable them. Once disabled, these features are notavailable to client applications, stored procedures, triggers, or database events.These features can be enabled again at runtime if the -sk option is used to startthe server. You can disable specific features, or groups of features, as describedin the documentation. For maximum security, it is recommended that you considerdisabling the following groups of features using the -sk option when starting theserver:

♦ local_call Disables all features that provide the ability to execute code that isnot directly part of the database server and is not controlled by the databaseserver. This set consists of the cmdshell, external_procedure, and Javafeatures.

♦ local_db Disables all features related to database files. This set consists ofthe backup, restore, database, and dbspace features. In this case, backupscould be performed when the database is offline.

♦ local_io Disables all features that allow direct access to files and theircontents. This set consists of the xp_read_file, xp_write_file, directory,load_table, and unload features.

♦ local_log Disables all logging features that result in creating or writing datadirectly to a file on disk. This set consists of the request_log and log_filefeatures.

When disabling features with the -sf option, be sure to use the -sk option tospecify a key to enable some of these features later on if needed.

13

Page 15: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

☞ For more information and the complete list of detailed features and groups offeatures that can be disabled, see the -sf server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-dbserver-s-3752812.html.

Securing access to SQL Anywhere utilities

The SQL Anywhere utilities are downloadable, and so must be consideredavailable to any user who wants them. It is important to consider the potentialeffects these utilities can have in relation to the security of your database.

The following utilities require a database connection with elevated permissions.By restricting user permissions, you can limit the potential security problems youcould have with them.

Utility Security concern

dbbackup The Backup utility could allow a malicious user to create abackup copy of the database, which could allow them to crackthe encryption key at their leisure.

dbinfo The Information utility shows information about a database.This information could aid an attacker in breaking the securitymeasures that have been put in place.

dbinit The Initialization utility could allow a malicious user to createa database, which could potentially be loaded on a runningserver and result in increased resource usage and less diskspace.

dbstop The Stop Database utility could allow a malicious user to stopa database, resulting in unnecessary downtime.

dbunload The Unload utility allows one to save database schema anddata in comma-delimited (.csv ) format. This could exposeimportant data to a malicious user.

dbconsole The SQL Anywhere Console utility could provide an attackerwith information about database connections and properties.Such information could be used to compromise a databaseserver.

dbisql The Interactive SQL utility (GUI or command line) could allow apotential attacker to execute arbitrary SQL statements againstthe database with negative consequences.

Sybase Central Sybase Central is a GUI management tool that allows accessto all aspects of a database, including wizards designed toprovide the same functionality of the abovementioned utilities.A user who gains access to login credentials could use this toolto view and alter any part of the database.

14

Page 16: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

The following utilities require no database permissions. Access to the databasefile is all that is required to use them. In a server environment, securing thephysical server and database file is the best way to prevent compromising yourdata. In a mobile environment, different considerations must be made. Forexample, dbtran is a key utility that does not require a user ID or password toaccess it. Using this utility, a user can translate to SQL all statements containedwithin that transaction log file. There are some options that can be used (possiblyin combination) to prevent this:

♦ Encrypt the database file An encrypted database file requires the to userknow the encryption key to translate the transaction log file.

♦ Use frequent backups Design your backup procedure to back up andtruncate the transaction log frequently. This keeps the transaction log files in aseparate directory and limits the size of the live transaction log file. The backupdirectory should be encrypted using file system encryption to further protectthem from dbtran.

♦ Truncate the log at checkpoint Use the -m option on the database server.This truncates the transaction log when a checkpoint occurs, limiting theamount of data in the log file. This option limits recoverability, and it is notrecommended.

♦ Manage your mobile devices Use IT policies and procedures to manageremote data. For example, tools like iAnywhere Afaria can be used to removedata remotely to limit what a malicious user can do.

Utility Security concern

dbdsn The Data Source utility could allow a malicious user to locateother SQL Anywhere databases on the network easily. Sucha user could also modify or delete existing data sources, thuscreating problems in the application layer.

dberase The Erase Database utility could allow a malicious user todelete vital database files, which can result in data loss.

dblog The Transaction Log utility could be used to change the nameof the transaction log file associated with a database or disablethe transaction log altogether. This could lead to data lossand/or performance degradation.

dbtran The Log Translation utility could allow a malicious user togenerate SQL statements to recreate a database, basedon a transaction log file of the database. This is especiallydangerous if the transaction log files are not encrypted.

The following utilities do not require access to the database file at all. All theyrequire is network connectivity to run. Malicious use of these utilities simplyinvolves finding and identifying potential targets for attack.

15

Page 17: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

Utility Security concern

dblocate The Server Enumeration utility could allow a malicious user tofind other database servers in the immediate network.

dbns10 The DBNS Broadcast Repeater utility could give a potentialattacker information about additional database servers presenton the same and different subnets.

☞ For more information on these tools, see “Administration utilities overview” inSQL Anywhere Server - Database Administration, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-sql-anywhere-components-overview.html.

Debugging database activity

SQL Anywhere provides a number of features for debugging database activity.These can be useful in determining the status of the database server and whatSQL statements were passed to it. Although providing useful functionality, youhave to be careful with these features because they could be exploited to gainaccess to important information.

Database request log

The SQL Anywhere request log records all requests made to the database server.Logged information includes such things as timestamps, connection IDs, andrequest type. For queries, it also includes isolation level, number of rows fetched,and cursor type. For INSERT, UPDATE, and DELETE statements, it includes thenumber of rows affected and the number of triggers fired. Sensitive information,such as login data, is not logged in the request level log. DBA authority on adatabase running on the server is required to turn on request logging on arunning server, but any user can start a new database server with request loggingenabled.

The request log should only be used when trying to diagnose a database-relatedproblem because it cannot be encrypted and records all information in plain text.This could allow a potential intruder to determine the exact calls an applicationmakes to a database, and they could then exploit this information to gainunauthorized access.

When the request log is in use, the following recommendations should befollowed:

♦ Delete all request logs as soon as they are no longer needed.

♦ Specify a maximum size for the request log to minimize the amount of datacompromised in the event of a security breach. The size of the request log fileis limited using the -zs option.

☞ For more information, see the -zs server option in SQL Anywhere Server -Database Administration, or go tohttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-zs-database-dbengine.html.

16

Page 18: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Take advantage of application profiling, which allows you to store request logoutput in a different, tracing database. This is a new feature in SQL Anywhere10 and provides additional security by allowing the tracing database data to beencrypted (whereas if request log information is saved to a file, that file is notencrypted).

☞ For more information, see “Tracing session data” in SQL Anywhere Server- Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbugen10/ug-perform-s-3238494.html.

Server Messages window

The Server Messages window displays status information about a SQL Anywheredatabase server. On Windows computers, the icon in the system tray is the onlyvisible indication that the database server is running.

For maximum security, you should disable the Server Messages window whenstarting the database server by specifying the -qw option. Then, there is no visibleindication that the database server is running, which might fool a potentialattacker.

☞ For more information, see the -qw server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-dbserver-s-6270173.html.

Securing SQL Anywhere configuration files

The security of the database server’s configuration files should also beconsidered. If a malicious user is able to get a copy of these files, they coulddetermine a weakness that could later be used to exploit the server.

With SQL Anywhere, configuration files can be used to simplify database serverstartup by saving all required options and parameters in a file that is later passedto the database server with the @data option. This can simplify server startup(especially when multiple parameters are needed) and store importantinformation. Since you can store sensitive information in configuration files, it is

17

Page 19: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

important to use the File Obfuscation utility (dbfhide) to disguise the contents ofsuch configuration files. Using dbfhide uses simple encryption methods to make itmore difficult to understand what information is stored in the file. Simpleencryption is an internally developed encryption method that is equivalent toobfuscation. It is not as secure as industry standard strong encryption algorithmssuch as AES.

You should not store sensitive information (such as encryption keys) inconfiguration files, even if dbfhide is used. Access to configuration files shouldalso be secured via operating system user permissions to administrator usersonly.

Database auditing

Auditing is a way of keeping track of the activity performed on a database. Therecord of activities stays in the transaction log. The SQL Anywhere databaseserver keeps a transaction log for each database, which records all transactionswhich modify the database. This is used to ensure data integrity andrecoverability. When database auditing is enabled, the server addssecurity-related information to the transaction log, which can be examined at anytime. Auditing information can help identify malicious behavior by logginginformation about when a user attempted unauthorized access to the database. Inthe case where the user (or user group) did not actually attempt the unauthorizedaccess, this could signify a breach of database credentials and should beaddressed immediately.

By turning auditing on, the database increases the amount of data saved in thetransaction log to include the following:

♦ All login attempts (successful and failed), including their IP addresses.

♦ Accurate timestamps of all events (to a resolution of milliseconds).

♦ All permissions checks (successful and failed), including the object on whichthe permission was checked (if applicable).

♦ All actions that require DBA authority.

Auditing is off by default, and has to be turned on explicitly by issuing the followingcommand:

SET OPTION PUBLIC.auditing = ’On’

After this, auditing remains on until it is turned off.

You can retrieve database audit information by using the Log Translation utility(dbtran) that comes with SQL Anywhere. It can be used to extract auditinformation while the database server is operational or from a specific transactionlog. If the log file is not encrypted, a malicious user could use it to generate all theSQL statements needed to create a complete copy of the database. See“Securing access to SQL Anywhere utilities” on page 14 for information aboutprotecting your data from unauthorized access by the SQL Anywhere utilities.

18

Page 20: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

Performance analysis of database auditing

Enabling database auditing impacts performance because it can cause extralogging information to be generated whenever the user accesses the database.When comparing the performance of databases with and without auditingenabled, the following was found:

During insertion of data, databases with auditing disabled performed about 14%faster than databases with logging enabled. This test was based on an insertionsimulation where 200000 rows were inserted into a single table on a Pentium 42.4 GHz system with 1024 MB RAM.

During retrieval of data, databases with auditing disabled performed about 14%faster than databases with logging enabled. This is based on a retrieval simulationwhere 200000 rows were retrieved from a single table on a Pentium 4 2.4 GHzsystem with 1024 MB RAM.

Securing backups

The security of database backups is often overlooked, with most security effortschanneled towards the live database. Backups, however, are just as crucial sincethey contain most, if not all, of the same data as the production database. Ifbackup security is overlooked, a malicious individual can bypass the expensivesecurity measures that might be in place to protect the live database by justobtaining a copy of a backup. This section outlines a number of backup securityissues that need to be considered.

Physical protection

When it comes to the physical security of a backup system or backup records(such as tapes), the same level of care should be in place as with the productiondatabase system. Moreover, if an off-site backup location is used, that locationshould be protected 24 hours a day, 7 days a week by professional securitypersonnel. If the data is transported manually (that is, not over a network), thetransport method should be secured proportionally to the value of the data beingtransported. For crucial enterprise data, it is recommended that a security servicebe brought in to provide industry-grade transport vehicles andprofessionally-trained personnel.

Network backup procedures

Network backups can made by a simple copy of the database files, the dbbackuputility, the dbbackup API, or the BACKUP DATABASE SQL statement. Using theprovided backup utilities provides a key benefit with regards to security. Thebackup utilities are executed over a standard database connection, and so TLS(transport layer security) can be used to protect the data in transit over thenetwork.

Moving backup copies of the database files over the network requires a differentset of precautions. Ideally, if the data is strongly encrypted in SQL Anywhere

19

Page 21: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

(which is recommended), it should first be decrypted and then extracted from thedatabase. It should then be compressed (for faster transport) and re-encrypted forthe duration of the data movement. Upon arrival at the backup system, the datamust then be decrypted and encrypted again using the backup encryption key(which should be different from the live database encryption key) before finallybeing saved to the backup storage medium.

Backup encryption

The stored backup copies should be kept in an encrypted state, with a specialbackup encryption key that is used for that purpose only. Given the rare (whencompared to a live database) usage of backed up data, the backup copies couldbe encrypted with more complex algorithms and longer and more complexencryption keys. The data could further be doubly-encrypted, (which is impracticalfor production systems), but is appropriate in this situation.

Securing web services

SQL Anywhere includes a built-in HTTP server that can be used by clientapplications to access web services stored in the database. This simplifies userrequests for data, as a standard HTTP call returns the necessary information,while also removing the need for a direct connection with the database (such asan ODBC connection). Access to data via web services needs to be secured,otherwise, anyone can to connect to a web service and see the data it returns.The following things are important to consider if you are using web services in thedatabase:

♦ Authentication When accessing a web service over HTTP, users should notbe required to supply database login information, because this information issent in the clear. For example, the following HTTP URL would log in the userwith user ID DBA and password sql into service serviceName:

http://DBA:sql@localhost:8080/serviceName

Any malicious user listening would see the user ID and password in the clear inthe URL when it is sent and database security would be compromised.

If user authentication is required for access to the web service, HTTPS shouldbe used in place of HTTP to ensure all of the URL information is encrypted.

SQL Anywhere gives you the option to run all service queries as a specifieduser after a user logs in (regardless of the actual user access permissions).Care should be taken when using this feature, as it may result in additionaldata loss if a user account is compromised.

♦ Use secure connections SQL Anywhere web services support both HTTPand secure HTTPS connections. For maximum security, especially when datais sent over the Internet, it is highly recommended that your web services useHTTPS connections.

♦ Parameters SQL Anywhere allows you to pass parameters to your webservices to provide additional information necessary for the execution of the

20

Page 22: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

SQL query associated with the service. Proper security measures have to bein place to avoid possible malicious attacks. See “SQL injections” on page 32for more details.

To avoid these attacks, all parameters have to be strongly typed and allparameter values should be checked for correctness before being used in SQLqueries against the database server.

Data protection with encryptionSQL Anywhere allows the data contained within its databases to be encrypted toprevent unauthorized users from viewing that data by using external tools (suchas hex editors). While it is recommended that you encrypt any non-trivial datawithin the database, it is up to the DBA to determine if encryption is required, andthe degree to which data is encrypted. Performance overhead of encryption canvary (as described below), and a balance should be achieved between securityand operational performance.

Encryption types

SQL Anywhere supports two types of data encryption: simple encryption andstrong encryption.

Simple encryption secures the data by applying an obfuscating algorithm to it.Although not as secure as strong encryption, simple encryption will preventsomeone who is using a disk utility from easily deciphering the data in thedatabase. Simple encryption has one advantage over strongencryption—performance. Simple encryption adds minimal overhead tounencrypted data retrieval and insertion.

Strong encryption within SQL Anywhere is based on the Advanced EncryptionStandard (AES) algorithm for block ciphers chosen by the National Institute ofStandards and Technology (NIST). It uses a user-specified key to encrypt the datain the database and transaction log such that if the original key is not provided,the data cannot be decrypted. Strong encryption in SQL Anywhere is alsoavailable on some platforms using a Federal Information Processing Standards(FIPS) approved implementation of the AES algorithm. In order to encryptdatabases with AES_FIPS, a separately licensed component must be obtained.

☞ For more information, see Keeping Your Data Secure in SQL AnywhereServer - Database Administration, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-encrypting-security-database.html.

Strong encryption keys and algorithms

When it comes to choosing secure encryption keys, the same principles apply aswith selecting secure passwords (see “Appendix B: Guidelines for strongpasswords” on page 36). Once a key is chosen, a copy of it should be kept in aphysically-protected location because if it is lost, the data in the database, the

21

Page 23: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

database log files, and the database mirror files (if available) are completelyinaccessible. Starting an encrypted database requires the entry of the encryptionkey, so it is recommended that only one person (the DBA) is able to start thedatabase. This avoids multiple people having knowledge of the encryption keyand decreases the chance of a security breach (for example, due to socialengineering methods). In addition, the encryption key should not be specified onthe database server command line. Most operating systems provide ways ofviewing the command line of running processes, and so your key could easily becompromised. Instead, start the database server and connect to the utilitydatabase, and then use the start database command to start your database,specifying the key in the start database command.

For embedded applications, if you do not want to share the encryption key withyour users, there are a few options that you can consider for hiding the key:

♦ Store the key embedded in the application somewhere This is notusually recommended due to the ease of finding the key, but it is very easy toimplement and would prevent an average user from finding it.

♦ Come up with an algorithm that can be used to derive the key at runtimeThe key does not have to be stored on the machine, but the key generationalgorithm must be protected. The algorithm should generate a different key foreach machine, user, database, and so on, where the database is kept

♦ Hide the key in INI files or the registry on Windows This also isn’trecommended since it is easy to snoop these values with operating systemutilities. However, it is easy to set up and can be effective for deterring averageusers.

♦ Use a web service to retrieve the key If the application requires Internetaccess, or if Internet access is always available, an HTTPS web service couldbe written that the application could call to retrieve the key before starting thedatabase.

♦ Use a built-in encryption API On Windows, consider using the built-inencryption APIs like CryptProtectData and CryptUnProtectData to store anencrypted form of the database key.

☞ For more information about social engineering, see “Appendix C: Socialengineering” on page 38.

Encryption options for creating databases

The following command line options are used to enable database and tableencryption when creating your database using the Initialization utility (dbinit):

♦ -e This option is used to create a database with simple encryption(obfuscation).

♦ -ek key This option is used at database creation time to specify that fulldatabase encryption will be used, and is followed by the encryption key. Thisparameter is also used to specify the database encryption key when startingan encrypted database.

22

Page 24: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ -ep This option is used at database creation time to specify that fulldatabase encryption will be used, and that the user should be prompted with adialog box for the encryption key. The user can be prompted for the encryptionkey both at database creation and at database server start-up.

♦ -et This option is used at database creation time to enable individual tableencryption within the database. If used alone it specifies simple encryption. Iffollowed by -ek or -ep, strong encryption is used on the encrypted tables.

☞ For more information, see “Creating databases (SQL)” in SQL AnywhereServer - SQL Usage, or http://www.ianywhere.com/developer/product_manuals/-sqlanywhere/1000/en/html/dbugen10/ug-creatingdbs-sql.html.

Full database encryption

Databases that are fully encrypted (meaning all database tables and the databasetransaction log are encrypted) are recommended from a security standpoint.Databases can be encrypted using either simple or strong encryption.

Simple encryption

Encrypted databases can be created using dbinit, the CREATE DATABASE SQLstatement, or the Sybase Central Create Database wizard. For example, adatabase with simple encryption can be created from a command prompt byexecuting the following:

dbinit -e database-file

Strong encryption

Strongly encrypted databases can be created via the command line utilities, withSQL statements, or by using Sybase Central. When using SQL statements, youmust include the ENCRYPTED ON KEY clause in the CREATE DATABASEstatement.

☞ For more information, see “Creating databases (SQL)” in SQL AnywhereServer - SQL Usage, or http://www.ianywhere.com/developer/product_manuals/-sqlanywhere/1000/en/html/dbugen10/ug-creatingdbs-sql.html.

On the command line, use the dbinit utility with the -ek (encryption key specifiedon command line) or -ep (user prompted for encryption key via a dialog)parameter. The -ep parameter is recommended because using the dialog masksthe key instead of having the user enter it in plain text on the command line.

☞ For more information, see -ep server option in SQL Anywhere Server -Database Administration, or http://www.ianywhere.com/developer/product_-manuals/sqlanywhere/1000/en/html/dbdaen10/da-ep-option.html.

23

Page 25: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

To encrypt a database after it has already been created, use the CREATEENCRYPTED FILE statement. The CREATE ENCRYPTED FILE statement canalso be used to change the encryption key of a database.

☞ For more information, see CREATE ENCRYPTED FILE in SQL AnywhereServer - SQL Reference, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbrfen10/rf-create-encrypted-file-statement.html.

Table encryption

Table encryption is similar to database encryption in that tables are fullyencrypted with either simple or strong encryption, but the difference is that fortable encryption, only specified tables are encrypted. This method allows you toencrypt tables with sensitive data, but avoids the possible performance impactassociated with encrypting the entire database. If database encryption is enabled,you cannot encrypt individual tables.

Simple encryption

♦ SQL The following SQL statement creates a database with simple tableencryption:

CREATE DATABASEdatabase-file-name ENCRYPTED TABLE

♦ Command prompt The following command uses the dbinit utility to create adatabase with simple table encryption:

dbinit database-file-name -et

Strong encryption

♦ SQL The following SQL statement creates a database with strong tableencryption, using the key abc and the AES encryption algorithm:

CREATE DATABASEdatabase-file-nameENCRYPTED TABLEKEY ’abc’ALGORITHM AES

♦ Command prompt The following command creates the same database asthe above SQL statement, but using the dbinit utility:

dbinit database-file-name -et -ek abc -ea AES

24

Page 26: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

It is recommended that instead of having users enter the encryption key on thecommand line, that they be prompted to enter the key in a dialog (where it ismasked and not displayed in plain text). This is done as follows:

dbinit database-file-name -et -ep -ea AES

After a database with table level encryption has been created, you can createencrypted tables by adding the ENCRYPTED clause to the CREATE TABLEstatement. For example:

CREATE TABLE Customers(MemberID CHAR( 40 ),CardNumber VARCHAR( 30 ) )ENCRYPTED;

Encrypting individual values in a table

In SQL Anywhere, you can encrypt any data within a table by using the ENCRYPTfunction. This requires no special parameters at database creation, but thedrawback is that the encryption key must be entered for every INSERT orSELECT. Using the ENCRYPT function uses strong AES encryption.

Using the ENCRYPT function, one can encrypt a single column (such as apassword column), but not any other data in the table. In this situation, it is usefulto create triggers to encrypt inserts automatically, and to create a hidden view todecrypt the column automatically for SELECT statements.

☞ For more information, see “Encrypting portions of a database” in SQLAnywhere Server - Database Administration, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-security-s-4649816.html.

Mobile data encryption policies

Mobile devices running SQL Anywhere support the same data encryptionfunctionality available on desktop computers. When using a mobile installation ofSQL Anywhere, it is also recommended that you encrypt the data.

25

Page 27: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

To reduce the chance of security threats, if a consolidated database in a SQLAnywhere database network is encrypted using a key X, before data is sent tomobile devices it is first decrypted using that key. This allows the database on themobile device to be encrypted only if desired. If data in the mobile databases isencrypted (using key Y), key Y should under no circumstances be the same askey X. This prevents the chance of unauthorized access to all company data if theencryption key on a single mobile device is compromised. Moreover, a databasemanagement procedure should be in place that regularly invalidates the keysused to encrypt mobile database instances (forcing data to be re-encrypted with anew key), so that even if the encryption on a mobile device is compromised, thekey will not be useful to the malicious user.

Performance analysis

Performance is only slightly impacted when data is encrypted because SQLAnywhere is very efficient in encrypting/decrypting data. In lab tests, whendatabases are encrypted with AES or AES_FIPS, the performance decrease isbetween 2-3% on data retrievals and as much as 5% on data insertion. Theseresults are based on the insertion/retrieval of 2.5 million rows to and from a singletable on a Pentium 4 2.4 GHz system with 1024 MB RAM.

26

Page 28: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

Communication encryptionSQL Anywhere is a market leader in the development of front line databases,designed to provide crucial business information regardless of where the user islocated. Sending business data outside of the enterprise can become a securityissue if no care is taken to encrypt and protect that data from maliciousindividuals. SQL Anywhere comes with built-in security mechanisms to allow formaximum protection, while allowing employees in the field to perform their workwith ease. Although SQL Anywhere does support unencrypted communicationsbetween databases (requiring only a user ID and password for the database), thissection focuses on transport-layer security.

Introduction

Communication encryption in SQL Anywhere is done using transport-layersecurity (TLS). TLS, the successor to SSL, is a cryptographic protocol designedto provide communication encryption over TCP/IP. TLS is an Internet EngineeringTask Force (IETF) standard protocol, which secures client/server communicationsusing digital certificates and public-key cryptography. SQL Anywhere supportsserver authentication, where the database server creates public and identitycertificates and a client application can use those certificates to verify the identityof the central database server. Note that regardless of whether or notcommunications encryption is in use, the login packet that the client applicationsends to connect to the database server is always encrypted.

The TLS protocol uses a combination of public-key and symmetric key encryptionto improve communication performance. Public-key encryption provides betterauthentication techniques, but is computationally intensive. Once a secureconnection is established, the client and server use a highly-efficient symmetriccipher with 128-bit key size for the rest of their communication.

Digital certificates

Transport-layer security is based on the exchange of digital certificates amongstinterested parties. Before communication begins, each party generates an identitycertificate, which is created by concatenating a public certificate with a private key.

27

Page 29: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

public information

and

public key

digital signature

private key

public information

and

public key

digital signature

private key

Public certificate

Private key

Identity certificate

A server or client identity certificate is

created by concatenating a public

certificate and the matching private key.

An important feature of the public certificate is the digital signature. Digitalsignatures are used to maintain data integrity during transmission and to detecttampering. Digital signatures are generated by creating a unique hash valuebased on a certificate, and signing or encrypting that hash value with a signatureprivate key. It is very important to protect the signature private key because if it iscompromised, a malicious user can mask a dangerous data transmission aslegitimate and fool the database server. There are three ways in which the signingof certificates can be approached:

♦ Self-signed certificates Self-signed server or client certificates can be usedfor simple setups (one central database server and few remote databases). Inthis scenario, the private key used to sign public certificates is stored in thecentral database server (for server authentication) or with the remotedatabases (client authentication).

☞ For more information, see “Self-signed root certificates” in SQL AnywhereServer - Database Administration, orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-ml-tls-s-3595952.html.

28

Page 30: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Enterprise root certificates This approach helps improve data integrity andextensibility in a multi-server and/or multi-client deployment. A specific serveris designated as the certificate authority and contains a private key used tosign all the certificates needed in the database system. This has theadvantage of extensibility, as additional servers can be added without the needto reconfigure clients, and vice versa.

☞ For more information, see “Enterprise root certificates” in SQL AnywhereServer - Database Administration, or go tohttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-ml-tls-s-3393696.html.

29

Page 31: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ Commercial (global) certificate authorities When a commercialcertificate authority is used (such as VeriSign), the certification procedures arevery similar to the enterprise root certificates approach, except that the privatesignature key is never stored locally. This has a number of advantages over theother approaches. First, commercial authorities specialize in the signing ofcertificates and have first-class systems to handle such requests. This includeselaborate physical and virtual security implementations. Global certificateauthorities are also useful when two different organizations want to exchangedata. Trusting certificates signed by the same third party can greatly speed upsuch a process. When using globally-signed certificates, each client or servermust verify the certificate values (such as Organization, Common name, andso on) to avoid trusting certificates that the certificate authority has signed forothers.

☞ For more information, see “Globally-signed certificates” in SQL AnywhereServer - Database Administration orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-ml-tls-s-4135725.html.

Enabling communications encryption

In order to enable communications encryption, first you need to decide whichencryption method you want to use: ECC or RSA. If you require a FIPS compliantapplication, you must use RSA_FIPS security. Once you have chosen, you needto do the following to enable communications encryption between the client andserver.

♦ Create digital certificates The identity certificate needs to be created andshould be stored securely on the server. The client certificate should begenerated and distributed to client applications. SQL Anywhere ships a utilitycalled gencert.exe to aid in the generation and signing of RSA or ECC

30

Page 32: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

certificates. In addition, a utility called readcert.exe is provided to readcertificates.

The following example uses the gencert -r option to generate an RSAself-signed server certificate.

gencert -rCertificate Generation ToolChoose certificate type ((R)SA or (E)CC): REnter key length (512-2048): 1024Generating key pair...Country: CAState/Province: ONLocality: WaterlooOrganization: Sybase, Inc.Organizational Unit: IASCommon Name: MobiLinkSerial Number: 123Certificate valid for how many years: 12Enter password to protect private key: mypwd123Enter file path to save certificate: public_cert.crtEnter file path to save private key: server_key.priEnter file path to save server identity: server_cert.crt

♦ Start database Server Start the server with encryption enabled by using the-ec option. This option allows you to specify the type of security and the servercertificate information. The following example uses the -ec server option tospecify ECC security, the server certificate, and the password protecting theserver’s private key:

dbsrv10 -ec tls(tls_type=ecc;certificate=c: \test \serv1_ecc.crt; certificate_password=mypwd) -x tcpip c: \test \secure.db

♦ Configure client applications To set up client applications to usetransport-layer security, deploy the certificates generated above with yourapplication. Then use the Encryption [ENC] connection parameter in yourconnection string.

The following example connection string uses the trusted_certificatesencryption connection parameter to specify the public certificate,public_cert.crt.

"UID=DBA;PWD=sql;ENG=myeng;LINKS=tcpip;ENC=tls(tls_type=ecc;trusted_certificates=public_cert.crt)"

☞ For more information on setting up communications encryption, see“Transport-Layer Security” in SQL Anywhere Server - Database Administration orhttp://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/-html/dbdaen10/da-ml-tls.html.

Performance analysis

Communication encryption has a significant impact on the performance ofdatabase communications, due to the overhead involved in encrypting alloutgoing and decrypting all incoming communications traffic. In general, RSA is

31

Page 33: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

faster than ECC, and ECC is faster than RSA_FIPS. All tests were performed onstandard off-the-shelf hardware with no modifications.

Database fetch When fetching data over an encrypted communication channel,RSA encrypted communication is 50% slower than unencrypted communication.These results are based on a retrieval test of 2.5 million rows on a Pentium 4 2.4GHz system with 1024 MB RAM..

Database insert When data is inserted, encrypted communications againperform slower than unencrypted ones, but the difference is not as pronounced aswith the database fetch results. When inserting data, the performance differencebetween RSA and unencrypted inserts is 40%. These results are based on aninsert test of 2.5 million rows on a Pentium 4 2.4 GHz system with 1024 MB RAM.

SQL injectionsSQL injections are security vulnerabilities that can occur whendynamically-generated SQL statements are passed for processing to a databaseserver from the application layer. These vulnerabilities occur when, duringdynamic SQL statement generation, the user-provided values are not escapedproperly, thus making it possible for the user to gain access to unauthorized databy entering his/her own SQL code. Because of the growth of the Internet, themost common targets of SQL injection attacks have become commercial websites, as those can be exploited to retrieve large amounts of sensitive information.Because of their simple nature, SQL injections are often overlooked anddismissed as a security threat, and prevention efforts are focused on other areasof the enterprise.

Examples

The following code generates a SQL statement that, when passed to thedatabase, authenticates a user login (if the return data set is empty, the login wasincorrect):

String statement = "SELECT * FROM users WHEREuserId = ’" + _userId + "’ AND password = ’" + _password + "’;"

;

What would happen if the user, instead of entering a proper password, typesanyUser into the username form box, and the following into the password box?

password’ OR ’’=’

The dynamically-generated SQL statement would look like this:

SELECT * FROM USERS WHERE uid = ’anyUser’ AND password =’password’ OR ’’=’’;

The result of executing this statement is unintended. The database would returnall users, which might result in the malicious user gaining unauthorized accessrights to the system.

If the malicious user wants to specifically damage the data in the database, they

32

Page 34: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

could have entered the following in the password field:

password’; DROP TABLE accounts; SELECT * FROM users WHERE uid =’admin

This would result in the deletion of the accounts table, which might havedisastrous consequences.

Preventing SQL injections

Because SQL injections look completely legitimate to a database server, most ofthe preventative measures for this problem are related to the application layer andhow the application invokes SQL execution from the database.

Preventing SQL injections in the application layer

Modifying an application to secure it from being vulnerable to SQL injectionattacks has been simplified in recent years because most programminglanguages and data access APIs include tools designed to combat such attacks.

Escape characters

Some languages provide specific functions (such as Perl DBI::quote) that accepta string value and check it to see if it contains special escape characters.Although such methods do not detect SQL code, they can remove escapecharacters (such as ones that terminate a string), causing the database server toreturn a SQL syntax error, so it does not execute the statement.

Value placeholders

A better way to prevent injection attacks is to use value placeholders whenbuilding a query. This technique is more useful for detecting SQL code in valuesthat should have none (such as a password variable). The following is a C# codesample:

string commandText = "SELECT * FROM Customers WHERECountry=@CountryName";

SqlCommand cmd = new SqlCommand(commandText, conn);cmd.Parameters.Add("@CountryName",countryName);

In this case, because ADO.NET provides strong type checking, C# flags an errorif countryName contains anything more than just a character or numeric value.Placeholder availability depends on the provision of such features from the DBMSitself or from the data access API used (such as ADO.NET in the above example).

You can also make use of host variables instead of building SQL queriesdynamically.

Stored procedures

The most effective method for combating injection attacks is by using databasestored procedures. The stored procedure method is similar to the valueplaceholders method, but has a number of key differences. First, storedprocedures are contained within the database and are only invoked by the

33

Page 35: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

application code with the necessary parameters passed in. With proper databasesecurity settings (see “Prevention in the database layer” on page 34), theapplication is informed that the stored procedure failed, without exposing any ofthe internal workings of the procedure itself.

Secondly, stored procedures enforce type checking. If a stored procedure expectsan INTEGER variable, anything but a valid integer causes a server error. Also ifthe procedure takes in a VARCHAR variable of size 10, it is difficult to inject anycode into it without causing database server errors. Stored procedures, whenimplemented properly, can be of great help in eliminating the chance of SQLinjections. You have to keep in mind, though, that variable values should still bechecked for possible injection code on the application side, as this providesadditional protection.

Prevention in the database layer

Although SQL injection attacks are legitimate SQL statements and it is impossiblefor the database server to identify malicious code, it is possible to tighten thesecurity of the database to limit the danger of such code.

In a normal production deployment, there should always be a separate useraccount that is used strictly by the application. To prevent a malicious user fromusing statements such as DROP TABLE, the application user’s permissionsshould be limited to:

♦ Only the SQL functions that it would need during normal operations.

♦ Only the tables that contain necessary information.

♦ If stored procedures are used, the application user should only be givenpermissions to execute the ones it needs.

Auditing can also help identify instances of successful SQL injection attacks andreverse the possible damage done to the system.

Injections in the URL

It is important to be aware of URL stuffing when talking about SQL injections. Thisrefers to an exploit that is possible when the web site exposes SQL statements inthe URLs for its web pages (for example when building up a SQL statement overthe course of a number of pages). This practice should be avoided. ExposingSQL code, or the parameters used to build up an SQL statement, in the URLshould be considered an unacceptable breach of security. Even a novice userwith basic SQL knowledge could exploit the system and cause damage.

ConclusionIn today’s world, the value of information is continually increasing in organizations,and database security is a critical issue. Every organization should take databasesecurity as seriously as they do their end of year financial statements. If a

34

Page 36: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

company’s data is compromised, the costs incurred can be prohibitive, both froma financial and a public relations perspective.

SQL Anywhere 10 provides an organization with the tools needed to make surethat its data is secure. This document has outlined the key areas of concern andprovided the steps necessary to ensure that your company’s data is safe andsecure while it is stored in a SQL Anywhere database and wherever it is sent toover the network.

Appendix A: SQL Anywhere securitychecklist

♦ Database server machine is in a secure environment with adequate protection

♦ The necessary network security measures have been put in place

♦ All unnecessary operating system services and daemons have been disabled

♦ Stringent operating system user account policies have been implemented, withfew users able to login to the database server machine

♦ When using integrated logins, the Windows guest user account is disabled,and all other user logins have strong passwords

♦ Mobile device security measures are in place

♦ Access to device is secured with passwords, certificates or non-traditionalauthentication methods

♦ Application-level security is in place• Remote device and patch management is available

• Data on the mobile device is encrypted using strong encryption

• Communication of mobile devices with the corporate network is secure

• Only company-owned devices are allowed to connect to the corporatenetwork

• Proper IT policies and procedures are in place, as discussed earlier

♦ DBA authority is restricted to as fewer users as possible

♦ Permissions to start, stop, create, load and unload databases are restricted toDBA users

♦ Security measures are in place regarding database user passwords:• A custom login procedure has been implemented

• Passwords have a minimum length

• Passwords must meet a minimum level of complexity

• The default DBA account password (“sql”) has been changed, or preferably,the DBA account is disabled and replaced with another account with DBAprivileges

35

Page 37: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

• Passwords are not included in ODBC data sources

• The number of unsuccessful login attempts is limited

♦ Unnecessary SQL Anywhere utilities are not present on the server, andmeasures have been taken to prevent the utilities from compromising security

♦ The database request log is not enabled by default and when needed it isdeleted immediately after use

♦ The database server message window is disabled

♦ Database auditing is enabled and access to the dbtran utility is restricted

♦ All backups and backup procedures are properly secured

♦ All database web services are secured using HTTPS and require userauthentication

♦ Strong database or table encryption is used

♦ Encryption keys are strong

♦ Users are prompted to enter the database encryption key using a dialog boxupon starting the database

♦ Communication with mobile/consolidated databases is secured usingtransport-layer security

♦ When possible, stored procedures with strong type checking are used toprevent unauthorized execution of code and SQL injections

♦ Adequate security training and information is made available to employees tofamiliarize them with proper information security procedures and practices

Appendix B: Guidelines for strongpasswords

Passwords are the standard way of securing computer systems today. Thisincludes anything from a desktop workstation to a critical database that storescustomer credit information. Regardless of the purpose a specific password has,it is imperative that such a password is secure avoid weak links in anorganization’s network.

Weak passwords remain one of the biggest problems facing security systemstoday. This is because people often, unless specifically forced not to, choosepasswords that are easy to remember—their names, names of objects, importantdates, and so on. Such passwords are easily broken using techniques such asdictionary attacks, where an attacker uses a very large number of common wordsto guess a user’s password. This is done by either making continuous loginattempts, or by obtaining the encrypted version of the password storing file andcomparing its values to millions of pre-encrypted dictionary words. This process

36

Page 38: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

can be extremely fast—two dual-processor workstations can break hundreds ofpasswords in just a few minutes using a 100000 word dictionary file.

Qualities of a strong password

♦ it is at least eight (8) characters long

♦ it has at least one number

♦ it has at least one lowercase letter

♦ it has at least one uppercase letter

♦ it has at least one symbol (!,@,#,$,^)

The following should never be used as passwords:

♦ user name

♦ employee numbers

♦ given names

♦ names of family members, friends, or co-workers

♦ nicknames

♦ social security or social insurance numbers

♦ driver’s license numbers

♦ birthdays

♦ license plate numbers

♦ addresses or street names

♦ phone numbers

♦ names of towns, cities, countries

♦ names of companies, departments, or divisions

♦ computer terms, commands, web sites, hardware items, or software names

♦ common terms and acronyms

♦ words and number patterns (aaddoo22, a1s2d3f4, and so on)

♦ makes and models of vehicles, planes, or boats

♦ slang words and phrases

♦ obscenities

♦ school names, school mascot names

♦ favorite foods, sports, TV channels, beverages, and so on

♦ dictionary words

37

Page 39: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

♦ any of the above, but in reverse

♦ passwords used on public web sites

♦ often used passwords

Appendix C: Social engineeringAll computer security systems are different with respect to what they are securingand how their respective security measures are implemented. Nonetheless, allsecurity systems share a common weak link that can easily be exploited to bringthem down entirely—the human factor. No matter how secure a system is, amalicious user can gain access to it by carefully manipulating the people thatinteract with such a system on a daily basis. The practice of obtaining confidentialinformation by social means in order to gain unauthorized access to a computersystem is referred to as social engineering .

Social engineering with respect to computer systems relies on the trust that mostpeople naturally show towards any other person. A social engineer manipulatessuch trust to gain access to privileged information, which in most cases refers tolearning the user IDs/passwords of people who have access to restricted data. Acommon example of such a use includes calling company employees pretendingto be a system administrator. Given the high likelihood that employees are notfamiliar with most of the personnel in IT, if they are asked for their password inorder to reset a system, there is a high chance that they will give out thatpassword.

Social engineering work is most commonly done over the phone, e-mail, or instantmessaging, and sometimes in person.

There are a number of procedures that can help an organization decrease itsvulnerability to social engineering attacks:

♦ Schedule security training sessions and explain to all employees what socialengineering is, what methods social engineers use to gain access toinformation and what preventative measures could be taken to prevent suchattacks. One of the biggest reasons why social engineering works is that thegeneral workforce is not aware the problem even exists. Therefore, trainingsessions will decrease the susceptibility of employees to such attacks. Thefollowing topics should be addressed:• What a social engineer is and how they attempts to earn a victim’s trust.

• List a number of common warning signs that could indicate that a caller is asocial engineer.

• Employees should know what information has value with respect to thecompany’s business and should be protected at all costs.

• Password policy should be explained. It should also be reinforced thatpasswords are personal and they should not be given out to anyone.

• The necessity to protect company lingo, names and positions of personnel,server names, and so on, as all of these could be used to plan a successfulsocial engineering attack on a different employee.

38

Page 40: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

• Exercising caution when opening strange emails from unknown peoplecontaining potentially harmful attachments, such as executable files.

♦ Clearly explain to employees the company security policies and make sure thatsuch policies are enforced.

♦ Create a process for ongoing reminders to employees with regard to thecompany’s security policies.

♦ Create a centralized security log. Employees should update the log every timethey receive a suspicious phone call or meet a suspicious individual who wasvery interested in the intricate details of the business. Such a log could provideearly-warning signs that a social engineering attacks is taking place, promptingan increase in security measures.

♦ Have a set of custom security questions to verify the identity of an employee.These could include personal details about the employee and bogus questions.

Appendix D: Sample password verificationfunction

This example defines a number of procedures and functions which togetherimplement advanced password rules including requiring certain types ofcharacters in the password, disallowing password reuse and expiring passwords.These procedures and functions are called by the server using theverify_password_function and login_procedure options when a User ID is createdor a password is changed, and when a user connects. The application may callthe procedure specified by the post_login_procedure to report that the passwordshould be changed before it expires.

-- only DBA should have permissions on this tableCREATE TABLE DBA.t_pwd_history(

pk INT DEFAULT AUTOINCREMENT PRIMARY KEY,change_date TIMESTAMP DEFAULT CURRENT TIMESTAMP,

-- when pwd setgrace_date DATE, -- a day after password expires to

-- allow user to log inuser_name CHAR(128), -- the user whose password is setpwd_hash CHAR(32) ); -- hash of password value to detect

-- duplicate passwords

39

Page 41: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

-- called on every GRANT CONNECT TO ... IDENTIFIED BY ...-- statement to verify that the password conforms to

-- the password rulesCREATE FUNCTION DBA.f_verify_pwd( uid VARCHAR(128),

new_pwd VARCHAR(255) )RETURNS VARCHAR(255)BEGIN

-- a table with one row per character in new_pwdDECLARE local temporary table pwd_chars(

pos INT PRIMARY KEY, -- index of c in new_pwdc CHAR( 1 CHAR ) ) NOT TRANSACTIONAL; --

character-- new_pwd with non-alpha characters removedDECLARE pwd_alpha_only CHAR(255);DECLARE num_lower_chars INT;

-- enforce minimum length (can also be done with-- min_password_length option)IF length( new_pwd ) < 6 THEN

RETURN ’password must be at least 6 characters long’;END IF;

-- break new_pwd into one row per characterINSERT INTO pwd_chars SELECT row_num, substr(

new_pwd, row_num, 1 )FROM dbo.RowGeneratorWHERE row_num <= length( new_pwd );

-- copy of new_pwd containing alpha-only charactersSELECT LIST( c, ’’ ORDER BY pos ) INTO pwd_alpha_only

FROM pwd_chars WHERE c BETWEEN ’a’ AND ’z’ OR c BETWEEN’A’ AND ’Z’;

-- number of lower case characters IN new_pwdSELECT COUNT(* ) INTO num_lower_chars

FROM pwd_chars WHERE CAST( c AS BINARY ) BETWEEN ’a’ AND’z’;

-- enforce rules based on characters contained in new_pwdIF ( SELECT count( * ) FROM pwd_chars WHERE c BETWEEN ’0’ AND

’9’ )< 1 THEN

RETURN ’password must contain at least one numericdigit’;

ELSEIF length( pwd_alpha_only ) < 2 THENRETURN ’password must contain at least two letters’;

ELSEIF num_lower_chars = 0OR length( pwd_alpha_only ) - num_lower_chars = 0

THENRETURN ’password must contain both upper- and lowercase

characters’;END IF;

40

Page 42: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

-- not the same as any user name-- (this could be modified to check against

-- a disallowed words table)IF EXISTS( SELECT * FROM SYS.SYSUSER

WHERE lower( user_name ) IN ( lower( pwd_alpha_only ),

lower( new_pwd) ) ) THEN

RETURN ’password or only alphabetic characters inpassword ’ ||

’must not match any user name’;END IF;

-- not the same as any previous password for this userIF EXISTS( SELECT * FROM DBA.t_pwd_history

WHERE user_name = uidAND pwd_hash = hash( uid || new_pwd, ’md5’

) ) THENRETURN ’previous passwords cannot be reused’;

END IF;

-- save the new passwordINSERT INTO DBA.t_pwd_history( user_name, pwd_hash )

VALUES( uid, hash( uid || new_pwd, ’md5’ ) );

RETURN( NULL );END;

ALTER FUNCTION DBA.f_verify_pwd SET HIDDEN;GRANT EXECUTE ON DBA.f_verify_pwd TO PUBLIC;SET OPTION PUBLIC.verify_password_function = ’DBA.f_verify_pwd’;

-- called on every connection to check for password expiryCREATE PROCEDURE DBA.p_login_check()BEGIN

DECLARE uid CHAR(128);DECLARE INVALID_LOGON EXCEPTION FOR SQLSTATE ’28000’;DECLARE last_pwd_change DATE;DECLARE grace_date DATE;DECLARE is_dba CHAR;DECLARE msg_str CHAR(255);

41

Page 43: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

SET uid = connection_property( ’Userid’ );IF ( EXISTS( SELECT * FROM DBA.t_pwd_history WHERE user_name

= uid ) ) THENSELECT FIRST t.change_date, t.grace_date

INTO last_pwd_change, grace_dateFROM t_pwd_history t WHERE t.user_name = uidORDER BY t.change_date DESC;

END IF;IF last_pwd_change IS NULL THEN

-- no password change, so create one now.INSERT INTO DBA.t_pwd_history( user_name, pwd_hash )

VALUES( uid, ’unknown’ );COMMIT WORK;

ELSEIF EXISTS( SELECT * FROM SYS.SYSUSERAUTHORITY a,

SYS.SYSUSER uWHERE u.user_name = uid AND u.user_id =

a.user_id ANDa.auth = ’DBA’ ) THEN

SET is_dba = ’Y’;ELSE

SET is_dba = ’N’;END IF;

-- remove any locks on t_pwd_history andSYSUSERAUTHORITY

ROLLBACK WORK;-- was last password change > five months agoIF CURRENT DATE > dateadd( month, 5, last_pwd_change )

THEN-- Never expire DBA accounts so that the database-- does not get locked out by all users.IF CURRENT DATE < dateadd( month, 6, last_pwd_change

) ORis_dba = ’Y’ OR( grace_date IS NOT NULL AND grace_date = CURRENT

DATE ) THENSET msg_str = ’The password for user ’ || uid ||

’ expires on ’ ||CAST( dateadd( month, 6, last_pwd_

change )AS DATE ) ||

’. Please change it before itexpires.’;

MESSAGE msg_str TO CONSOLE;

42

Page 44: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

-- The post_login_procedure option is set to-- p_post_login_check, which will cause a dialog

-- to bedisplayed notifying the user their-- password willexpire soon. dbisql and

dbisqlc-- will

display this dialog, and user applications-- can call

the post_login_procedure and display-- this dialog.

-- May want touse xp_send_mail to notify user

-- and/or administrator.ELSEIF grace_date IS NULL THEN

-- Allow one grace login day. The first login on-- the grace day fails to ensure the user knows-- their password has expired

UPDATE DBA.t_pwd_history t SET t.grace_date =CURRENT DATE

WHERE t.grace_date IS NULL AND t.user_name =uid;

COMMIT WORK;SET msg_str = ’The password for user ’ || uid ||

’ has expired, but future loginswill ’ ||

’be allowed today only so that thepassword ’ ||

’can be changed.’;MESSAGE msg_str TO CONSOLE;RAISERROR 28000 msg_str;RETURN;

ELSESET msg_str = ’The password for user ’ || uid ||

’ has expired and must be reset byyour DBA.’;

MESSAGE msg_str;-- may want to use xp_send_mail to notify

administrator.RAISERROR 28000 msg_str;RETURN;

END IF;END IF;

END IF;

CALL dbo.sp_login_environment;END;

GRANT EXECUTE ON DBA.p_login_check TO PUBLIC;SET OPTION PUBLIC.login_procedure = ’DBA.p_login_check’;

43

Page 45: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

-- called by dbisql, dbisqlc and some user applications on everysuccessful

-- connection to check for warnings which should be displayedCREATE PROCEDURE DBA.p_post_login_check()RESULT( warning_text VARCHAR(255), warning_action INT )BEGIN

DECLARE uid CHAR(128);DECLARE last_pwd_change DATE;DECLARE warning_text CHAR(255);DECLARE warning_action INT;

SET uid = connection_property( ’Userid’ );SELECT FIRST t.change_date

INTO last_pwd_changeFROM DBA.t_pwd_history t WHERE t.user_name = uidORDER BY t.change_date DESC;

IF CURRENT DATE > dateadd( month, 5, last_pwd_change ) THENSET warning_text = ’Your password expires on ’ ||

CAST( dateadd( month, 6, last_pwd_change )

AS DATE ) ||’. Please change it before it

expires.’;SET warning_action = 1;

ELSE-- There is no warningSET warning_text = NULL;SET warning_action = 0;

END IF;-- Return the warning (if any) through this result setSELECT warning_text, warning_action;

END;

GRANT EXECUTE ON DBA.p_post_login_check TO PUBLIC;SET OPTION PUBLIC.post_login_procedure = ’DBA.p_post_login_

check’;

44

Page 46: Securing SQL Anywhere Server 10

Copyright © 2006 iAnywhere Solutions, Inc.

Legal NoticeCopyright © 2006 iAnywhere Solutions, Inc. All rights reserved. Sybase, theSybase logo, iAnywhere Solutions, the iAnywhere Solutions logo, AdaptiveServer, MobiLink, and SQL Anywhere are trademarks of Sybase, Inc. or itssubsidiaries. All other trademarks are property of their respective owners.

The information, advice, recommendations, software, documentation, data,services, logos, trademarks, artwork, text, pictures, and other materials(collectively, “Materials”) contained in this document are owned by Sybase, Inc.and/or its suppliers and are protected by copyright and trademark laws andinternational treaties. Any such Materials may also be the subject of otherintellectual property rights of Sybase and/or its suppliers all of which rights arereserved by Sybase and its suppliers.

Nothing in the Materials shall be construed as conferring any license in anySybase intellectual property or modifying any existing license agreement.

The Materials are provided “AS IS”, without warranties of any kind. SYBASEEXPRESSLY DISCLAIMS ALL REPRESENTATIONS AND WARRANTIESRELATING TO THE MATERIALS, INCLUDING WITHOUT LIMITATION, ANYIMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULARPURPOSE AND NON-INFRINGEMENT. Sybase makes no warranty,representation, or guaranty as to the content, sequence, accuracy, timeliness, orcompleteness of the Materials or that the Materials may be relied upon for anyreason.

Sybase makes no warranty, representation or guaranty that the Materials will beuninterrupted or error free or that any defects can be corrected. For purposes ofthis section, ‘Sybase’ shall include Sybase, Inc., and its divisions, subsidiaries,successors, parent companies, and their employees, partners, principals, agentsand representatives, and any third-party providers or sources of Materials.

Contact Us

iAnywhere Solutions Worldwide Headquarters One Sybase Drive, Dublin,CA, 94568 USA

Phone 1-800-801-2069 (in US and Canada)

Fax 1-519-747-4971

World Wide Web http://www.ianywhere.com

Email [email protected]

45


Recommended