Saturday, August 25, 2012

Configuring Tomcat for SSL

Setting the server certificate


  • Create a server certificate for Tomcat and setup in the server.  Refer my earlier post for details on how a certificate can be obtained.
  • Double check whether the Root cert needs to be imported in trustcacerts. it might be safe to do:
    • keytool -import -trustcacerts -alias <ca-cert-alias> -file <ca-cert-filename> 

Tomcat Connector configuration in server.xml.

      <Connector
        executor="tomcatThreadPool"
        port="9443"
        protocol="HTTP/1.1"
        connectionTimeout="20000"
        redirectPort="8443"
        acceptCount="100"
        maxKeepAliveRequests="15"
        keystoreFile="eclipse-workspace/security-utils/resources/manojkeystore.jks"
        keystorePass=""
        keyAlias="manojscepcertificate"
        keyPass=""
        SSLEnabled="true"
        scheme="https"
        secure="true"/>

  • Some of the attributes are the same as those of the basic HTTP connector, such as executor, protocol, connectionTimeout, maxKeepAliveRequests, and acceptCount. Note that although this connector will be used for HTTPS connections, you still set protocol to HTTP/1.1; other attributes will specify that this is an SSL-enabled connection.
  • The TCP/IP port that users specify as the secure connection port is 9443. Be sure that you set the value of the redirectPort attribute of your non-SSL connectors to this value to ensure that users that require a secure connection are redirected to the secure port, even if they initially start at the non-secure port.
  • The SSLEnabled attribute specifies that SSL is enabled for this connector.
  • The secure attribute ensures that a call to request.isSecure() from the connecting client always returns true. The default value of this attribute is false.
  • The scheme attribute ensures that a call to request.getScheme() from the connecting client always returns https when clients use this connector. The default value of this attribute is http.
  • The keystoreFile attribute specifies the name of the file that contains the server's private key and public certificate used in the SSL handshake, encryption, and decryption. You use an alias and password to access this information. 
  • The keyAlias and keystorePass attributes specify the alias (and password) used to access the keystore specified by the keystoreFile attribute.
  • keyPass specified the password for the key entry in the JKS. Usually this is not set or set to be the same as the keystore password. 
    • If the key entry was set programmatically then this password is set and has to be specified.

Limiting SSL Usage

    Enabling SSL in Tomcat's server.xml file causes all files to be run both as secure and insecure pages, which can cause unnecessary server load.  You can choose which applications offer SSL connections on a per-application basis by adding the following <security-constraint> element to the application's WEB-INF/web.xml file:

      <security-constraint>
      <web-resource-collection>
      <web-resource-name>YourAppsName</web-resource-name>
      <url-pattern>/*</url-pattern>
      </web-resource-collection>
      <user-data-constraint>
      <transport-guarantee>CONFIDENTIAL</transport-guarantee>
      </user-data-constraint>
      </security-constraint>

        • This configuration allows you to set SSL options for all an application's pages in one place.  For example, to disable SSL for all your application's pages, change "CONFIDENTIAL" to "NONE".

          Specifying Implementation

          If you have configured connectors for both APR and JSSE, Tomcat will use APR by default if you have installed the native libraries.  You can force it to use JSSE by modifying a Connector's "protocol" attribute as follows:

          <Connector protocol="org.apache.coyote.http11.HTTP11NioProtocol">

          If you want to force APR, you can do so with a similar edit:

          <Connector protocol="org.apache.coyote.http11.Http11AprProtocol">


          Verification


          Verify if tomcat is now showing the SSL cert. On my local server, the url is https://localhost:9443/SampleApp/services/SampleWebServiceImplPort?wsdl

          SSL Cipher Strength

          <TODO> Add more details about Cipher strengths and testing etc. Maybe another blog post about tools.


          Note 
          Note: Using name-based virtual hosts on a secured connection can be problematic. This is a design limitation of the SSL protocol itself. The SSL handshake, where the client browser accepts the server certificate, must occur before the HTTP request is accessed. As a result, the request information containing the virtual host name cannot be determined prior to authentication, and it is therefore not possible to assign multiple certificates to a single IP address. If all virtual hosts on a single IP address need to authenticate against the same certificate, the addition of multiple virtual hosts should not interfere with normal SSL operations on the server. Be aware, however, that most client browsers will compare the server's domain name against the domain name listed in the certificate, if any (applicable primarily to official, CA-signed certificates). If the domain names do not match, these browsers will display a warning to the client user. In general, only address-based virtual hosts are commonly used with SSL in a production environment.

          Setting Up a Server Certificate
          Tomcat SSL configuration


          Resources






          Saturday, August 18, 2012

          Security: SQL Injection

          SQL Injection flaws are introduced when dynamic database queries utilize user supplied input in some form.

          Most of the current web applications follow an MVC architecture where the Model typically represents a relational database. The flaws within this design are easily exploitable and could cause data loss, privacy and potential financial loss.


          SQL injection is a code injection technique that exploits a security vulnerability in a website's software. Code Injection is the general name for a lot of types of attacks which depend on inserting code, which is interprated by the application. 


          Simple Example:

          Let's say we have the below query to retrieve the users from accounts table:
          select name, salary from accounts where userid='inputdata' and accessid='123';

          Now if the inputdata is sent as is without an validation, a malicious user could send the value as
          :
          someuser' OR 1=1 --

          This would generate the below query:
          select name, salary from accounts where userid='someuser' OR 1=1 -- and accessid='123';

          This effectively subverts all our checks and the query would end up returning the names and salaries of all the users in the accounts table. Definitely not ideal !



          • For Select statements, the injection is usually after the where clause but could be used at ORDER by or names of tables and columns.


          • For INSERT statement, since the parameters values and types are unknown, we can keep adding fields to the VALUES clause until it works:
            • INSERT INTO users (username, password, ID, privs) VALUES ('ddd','pwd', 1111, 1)
            • Example:
              • junk')--
              • junk', 1)--
              • junk', 1, 1)--
              • junk', 1, 1, 1)--
            • An integer is implicitly casted to a string and 2000 to a date so we can use these at each position.
          • It's possible that a field in the Select clause that is vulnerable to SQL injection is also used in subsequent UPDATE statements and this could cause problems downstream. So any SQL Injection verification should keep that in mind.
            • UPDATE accounts SET password='newpwd' WHERE user = 'me' and password= 'pwd'
            • As described for select statements, update and DELETE statements are equally vulnerable to SQL Injection.
          Quick steps to verify if an application is vulnerable:
          • Verify if the app is interacting with a backend DB by submitting "%" in a search parameter to see if additional results are being returned.
          • Try with single and two single quotes in user supplied data to see how the application responds. Single quote normally results in a a SQL error and you can study the error message.  two single quotes are treated by the DB as a literal single quote so the error might disappear and indicate that the DB processed this as valid input. This might signal SQL Injection vulnerability.
          • While testing for SQl Injection vulnerability(especially without using an intercepting proxy), we may need to encode the params to pass them to the DB layer.
            • If you fail to encode problem characters correctly, you may inval-idate the entire request or submit data you did not intend to.
          • User input values that are used in table or column names or ORDER by clauses don't need a single quote.
          • If SQL injection vulnerability occurs in a SELECT statement, you can often employ the UNION operator to perform a second query, and combine the results with those of the first. 
            • But the two result sets must have the same structure. i.e. they must contain the same number of columns, which have the same or compatible data types, appearing in the same order.
            • A persistent attacker can first figure out the number of columns by using "SELECT NULL" and then try different data types.
          • Database metadata can be used to further gather information about the tables and columns:
            • information_schema table can be used for MS-SQL, MySQL etc
            • all_tab_columns can be used for Oracle.
          • It is possible to bypass filters at the application level by using ASCII codes for characters ( if single quote is being blocked). If comment is blocked then we can construct in a way to avoid breaking the syntax.
          • It is also possible to bypass blacklist based validations by using null charater etc.
          •  You can check if t


          Fingerprinting the Database: The below shows how the string services could be constructed on the common types of database:
          • Oracle: ‘serv’?‘ices’  ( send '||'London as a String parameter and the result is same)
          • MS-SQL: ‘serv’+‘ices’ ( send '+'London as a String parameter and the result is same)
          • MySQL: ‘serv’ ‘ices’ (note the space)
          Second-Order SQL Injection<TODO>
          Many applications handle data safely when it is first inserted into the database. Once data is stored in the database, it may later be processed in unsafe ways, either by the application itself or by other back-end processes. 

          Advanced Exploitation<TODO>

          attacker could turn off an MS-SQL database with the shutdown command:

          ' shutdown --


          Beyond SQL Injection: Escalating the Database Attack


          MS-SQL
          Perhaps the most notorious piece of database functionality that an attacker can misuse is the xp_cmdshell stored procedure, which is built into MS-SQL by default. This stored procedure allows users with DBA permissions to execute operating system commands in the same way as the cmd.exe command prompt. For example:master..xp_cmdshell 'ipconfig > foo.txt'
          The opportunity for an attacker to misuse this functionality is huge. He can perform arbitrary commands, pipe the results to local files, and read them back. He can open out-of-band network connections back to himself and create a backdoor command and communications channel. Because MS-SQL runs by default as Localsystem, the attacker typically can fully compromise the underlying operating system, performing arbitrary actions. MS-SQL contains a wealth of other extended stored procedures, such as xp_regread and xp_regwrite, that can be used to perform powerful actions within the registry of the Windows operating system.

          <TODO>


          Preventing SQL Injection

          Despite the complex and dangerous attacks that can be mounted by SQL injection, it is in general one of the easier vulnerabilities to prevent. 

          But merely, escaping single quotation marks by doubling them will not prevent SQL Injection. It fails in the below two situations:
          • If numeric user-supplied data is being embedded into SQL queries, this is not usually encapsulated within single quotation marks. Hence, an attacker can break out of the data context and begin entering arbitrary SQL without the need to supply a single quotation mark.
          • In second-order SQL injection attacks, data that has been safely escaped when initially inserted into the database is subsequently read from the database and then passed back to it again. Quotation marks that were doubled initially return to their original form when the data is reused.
          Escaping Dynamic Queries
          • One can use escaping routines for specific database:
            • ESAPI.encoder().encodeForSQL( new OracleCodec(), queryparam );
          • encodeForSQL
            • Encode input for use in a SQL query, according to the selected codec (appropriate codecs include the MySQLCodec and OracleCodec). This method is not recommended. The use of the PreparedStatement interface is the preferred approach. However, if for some reason this is impossible, then this method is provided as a weaker alternative. The best approach is to make sure any single-quotes are double-quoted. Another possible approach is to use the {escape} syntax described in the JDBC specification in section 1.5.6. However, this syntax does not work with all drivers, and requires modification of all queries.

          While stored procedure can have security and performance benefits, it doesn't prevent SQL Injection in all cases. Consider:
          • A SP invoked in an unsafe way using user-supplied input.
            • exec sp_createUser 'johm', 'pwd'
            • This statement may be just as vulnerable as a simple INSERT statement. For example, an attacker may supply the following password:
            • abc'; exec some_malicious --
            • which causes the application to perform the batch query
          How about parameterized Queries?
          In the case of Parameterized Queries, the query structure has already been defined, the relevant API handles any type of placeholder data in a safe manner, so it is always interpreted as data rather than part of the statement's structure.

          A few things to keep in mind though:
          • Be consistent and use PQs all throughout the application.
          • Don't use any parameter concatenation to construct a PQ. 
          • (Rare but possible). Some applications accept parameters for table and column names. Ensure white list validation is done, along with length and whitespace restrictions and also allowing only alphanumeric characters.
          • Parameter placeholders cannot be used for any other parts of the query, such as the ASC or DESC keywords that appear within an ORDER BY clause, or any other SQL keyword, since these form part of the query structure. 
          Defense in Depth
          • lowest possible level of privileges when accessing the database. An application can even use multiple accounts i.e. one for read only and one for read write. This mitigates risks that a sql injection flaws.
          • Unnecessary database functions should be removed/disabled. A skilled and determined attacker may be able to recreate some required functions but this is not usually straightforward,
          • All vendor-issued security patches should be applied in a timely way (They should be tested first).


          TIPS
          • Use SET DEFINE OFF or SET SCAN OFF to ensure that automatic character replacement is turned off. 
            • If this character replacement is turned on, the & character will be treated like a SQLPlus variable prefix that could allow an attacker to retrieve private data.
            • But It will also disable variables (  & is used for variables as well). Best option is to:
            • You need SET DEFINE ON to make variables work
            • And SET ESCAPE ON to escape uses of &.

          Questions/Answers
          1.You are trying to exploit a SQL injection flaw by performing a UNION attack to retrieve data. You do not know how many columns the original query returns. How can you find this out?
          2.You have located a SQL injection vulnerability in a string parameter. You believe the database is either MS-SQL or Oracle, but you can't retrieve any data or an error message to confirm which database is running. How can you find this out?
          3.You have submitted a single quotation mark at numerous locations throughout the application. From the resulting error messages you have diagnosed several potential SQL injection flaws. Which one of the following would be the safest location to test whether more crafted input has an effect on the application's processing?

          Registering a new user

          Updating your personal details

          Unsubscribing from the service
          4.You have found a SQL injection vulnerability in a login function, and you try to use the input ‘ or 1=1— to bypass the login. Your attack fails, and the resulting error message indicates that the -- characters are being stripped by the application's input filters. How could you circumvent this problem?

          5.You have found a SQL injection vulnerability but have been unable to carry out any useful attacks, because the application rejects any input containing whitespace. How can you work around this restriction?
          6.The application is doubling up all single quotation marks within user input before these are incorporated into SQL queries. You have found a SQL injection vulnerability in a numeric field, but you need to use a string value in one of your attack payloads. How can you place a string in your query without using any quotation marks?
          7.In some rare situations, applications construct dynamic SQL queries from user-supplied input in a way that cannot be made safe using parameterized queries. When does this occur?
          8.You have escalated privileges within an application such that you now have full administrative access. You discover a SQL injection vulnerability within a user administration function. How can you leverage this vulnerability to further advance your attack?
          9.You are attacking an application that holds no sensitive data and contains no authentication or access control mechanisms. In this situation, how should you rank the significance of the following vulnerabilities?

          SQL injection

          XPath injection

          OS command injection
          You are probing an application function that enables you to search personnel details. You suspect that the function is accessing either a database or an Active Directory back end. How could you try to determine which of these is the case?

          ======================================================================================
          1.You can determine the number of columns in two easy ways. First, you can SELECT the type-neutral value NULL from each column, increasing the number of columns until the application returns data, indicating that the correct number of columns were specified, for example:

          ' UNION SELECT NULL--

          ' UNION SELECT NULL, NULL--

          ' UNION SELECT NULL, NULL, NULL--

          Note that on Oracle you will need to add FROM DUAL after the final NULL in each case.

          Second, you can inject ORDER BY clauses and increment the specified column until an error occurs, indicating that an invalid column was requested:

          ' ORDER BY 1--

          ' ORDER BY 2--

          ' ORDER BY 3-- 

          2.An easy way to confirm the database type is to use database-specific string concatenation syntax to construct some benign input within the query you control. For example, if the original value of the parameter is London you can submit the following items in turn:

          '||'London

          '+'London

          If the first results in the same behavior as the original, the database is probably Oracle. If the second results in the same behavior, the database is probably MS-SQL. 

          3.While it may seem counterintuitive, the user registration function is probably the safest. Registration functions normally use INSERT statements, which are unlikely to affect other records if you modify them. A function to update personal records is probably using conditional UPDATE statements. If you inject a payload like ' or 1=1-- you may cause all records in the table to be modified. Similarly, the function to unsubscribe is probably using conditional DELETE statements, and could impact on other users if you are not careful.

          That said, it is impossible to be completely certain in advance which statements are being carried out by any kind of functionality, and you should advise the application owner of the risks before you perform the test. 

          4.An easy way to achieve the same effect without using comment characters is with the input ' or 'a'='a. 
          5.You can SQL comment characters to separate keywords and other items in your injected payloads, for example:

          '/**/UNION/**/SELECT/**/username,password/**/FROM/**/users-- 

          6.You can use the CHAR command to return a string value from a numeric ASCII character code. For example, on Oracle the string FOO can be represented as:

          CHAR(70)||CHAR(79)||CHAR(79) 

          7.This situation arises where user-supplied input is being placed into other elements of a query, such as table and column names, rather than the query’s parameters. A parameterized query cannot be precompiled with placeholders for these items, so a different solution needs to be used, probably based on very stringent input validation. 

          8.Because you already have administrative access, it is likely that you can retrieve any data you desire using the application itself, meaning that a SQL injection attack to retrieve the application’s own data may be redundant. However, you can still leverage the attack to access any data relating to other applications that is held within the same database, or to escalate privileges within the database or the underlying operating system, to compromise the database server and extend your attack into the wider internal network. 

          9.XPath injection can only be used to retrieve data from the targeted XML file. Hence, if the application contains no sensitive data this is likely to be a low impact issue. Similarly, SQL injection flaws may not enable you to extract any sensitive data from the database. However, they can sometimes be leveraged to escalate privileges within the database and develop your attack in other ways. Depending on the situation, SQL injection may be a more significant vulnerability. OS command injection, on the other hand, is almost always a high impact vulnerability, because it usually enables you to directly compromise the underlying server and use it as the launch point for further attacks against internal systems. 

          10.If the function is accessing a database, then submitting the SQL wildcard % as the search query is likely to return a large number of records. Similarly, if the function is accessing an Active Directory, then submitting the wildcard * is likely to return a large number of records. Neither wildcard should have the same effect on the other system. 


          Saturday, July 28, 2012

          Security Conferences that I find interesting - 2012



          OWASP AppSec USA 2012 — LASCON Edition, TX


          Austin, TX at the Hyatt Regency Hotel Downtown
          Training: October 23rd-24th — Conference Sessions: October 25th-26th

          OWASP AppSec conferences bring together industry, government, security researchers, and practitioners to discuss the state of the art in application security.


          RSA Conference 

          is helping drive the information security agenda worldwide with annual industry events in the U.S., Europe and Asia. Throughout its history, RSA Conference has consistently attracted the world's best and brightest in the field, creating opportunities for conference attendees to learn about IT security's most important issues through first-hand interactions with peers, luminaries and emerging and established companies. As the IT security field continues to grow in importance and influence, RSA Conference plays an integral role in keeping security professionals across the globe connected and educated.
          RSA developed the RSA Conference in 1991 as a forum for cryptographers to gather and share the latest knowledge and advancements in the area of Internet security. Today, the RSA Conference and related, RSA Conference branded activities, are still managed by RSA, the Security Division of EMC, with the support of the industry. RSA Conference event programming is judged and developed by information security practitioners and other related professionals.


          Save the date for 2013: February 25 to March 1 in San Francisco!


          Refer this for 2012 Sessions


          Information System Security Consortium Congress: 

          https://www.isc2.org/Conferences.aspx


          http://www.hackerhalted.com

          Has courses for learning etc:


          SNCourse TitleBefore May 31Before Aug 31Starts Sept 1

          1.
          Certified Ethical Hacker (CEH) v7
          $2999
          $3399
          $3599
          2.
          Certified Security Analyst / Licensed Penetration Tester (ECSA/LPT)
          $2799
          $3199
          $3399
          3.
          Computer Forensics Hacking Investigator (CHFI)
          $2799
          $3199
          $3399
          4.Certified Incident Handler (ECIH) [2 days]$2299$2699  $2899
          5.
          CAST 611 – Advanced Penetration Testing [3 days]
          $2799
          $3199
          $3399
          6.CAST 612 – Advanced Mobile Hacking & Forensics [3 days] $2799$3199  $3399
          7.
          CAST 614 – Advanced Network Defense [3 days]
          $2799
          $3199
          $3399
          8.
          Wireless & Bluetooth Hacking 101 [2 days]
          $2299
          $2699
          $2899
          9.SAP Security In Depth [2 days] $2299$2699$2899
          10.
          Certified Information Systems Security Professional (CISSP)
          $2799
          $3199
          $3399
          11.Crimeware Attribution [2 days] $2299$2699$2899
          12.
          The Web Application Hacker’s Handbook 2nd Edition Live - [3 days]
          $2799
          $3199
          $3399
          13.
          PMP (Project Management Professional)
          $2799
          $3199
          $3399


          Conference Pass   

          SNCategoryBefore May 31Before Aug 31Starts Sept 1

          1.
          EC-Council Member*
          $899
          $1199
          $1399
          2.
          Public
          $1299
          $1599
          $1799
          3.
          Academic Pass**
          $399
          $599
          $699
          4.Press & MediaPlease email info@hackerhalted.com for more information 
          5.Group RegistrationsPlease email info@hackerhalted.com for more information


          Blackhat

          July 21-26, 2012 | Las Vegas, NV



          ISACA's World Congress

             
          25-27 June 2012 | San Francisco, CA, USA
          A leadership forum for business and IT professionals.


          BSidesDFW 2012

          Event details:

          When: Saturday, November 3, 2012
          Where: CTREC Hilton Academy (1605 LBJ Freeway, Dallas, TX 75234)
          Cost: Free (as always!) Donations are always welcome Donate Here!
          Doors open at: 8:30 am - 5:30 pm


          InfoSec World Conference & Expo 2013

          April 15-17, 2013
          Walt Disney World Swan and Dolphin
          Orlando, FL


          Here are resources in case you want to look at all available conferences:





          Sunday, July 15, 2012

          Creating an X509v3 Certificate


          There are three options to generate a certificate and some of the steps are common between the first two options.


          Option1: Create a self signed certificate
          We can use the keytool supplied as part of JDK to create this. For example:

          • Step1: Creating a Certificate

          jdk1.7.0_04\bin>keytool -genkey -keyalg RSA -alias manojdefaultcert  -keystore manojkeystore.jks

          • Step 2: generating a CSR( Certificate Signing Request). 

          The CSR contains the public key and the name of the server, in a format defined by the PKCS#10 standard (typically given the filename extension .p10 or .csr)
          jdk1.7.0_04\bin>keytool -certreq -sigalg MD5withRSA -alias manojdefaultcert -file manojdefaultcert-csr.pem  -keystore manojkeystore.jks

          • Step3: Generate certificate from above CSR.

          jdk1.7.0_04\bin>keytool -gencert -infile manojdefaultcert-csr.pem -outf
          ile manojdefaultcert.cert -alias manojdefaultcert -keystore manojkeystore.jks

          Don't recall if I had to do anything with the certificate generated in manojdefaultcert.cert file. Probably the PrivateKey entry in the keytool becomes ready for use.
          Maybe we can  use this certificate and provide it to clients that want to trust this self signed certificate.

          Option2: Create a Certificate signed by a CA

          Steps 1 and 2 are similar to the ones for option 1. Once we have the CSR, we can get the CSR signed by a CA. Refer the  EJB CA post to see how EJBCA was setup as a CA and how we can get the cert signed by EJBCA.
          • Just to summarize, navigate to https://localhost:8443/ejbca/enrol/server.jsp  and select the CSR file and the user id to create against. 
            • User id should match the subject in "CN=subject". 
            • Output in pkcs#7 format.
          • Note: Remember to accept the return in pkcs#7 format from the CA and then import that file into the keystore. For some reason pem format didn't work in EJBCA. maybe because it didn't have the full chain. 
          • Step 3: Import the output file( CA Reply or CSR Reply) from the CA in keystore: 
            • This is typically given as an X.509 Certificate file (.cer, .crt, .pem, or .der) or as a PKCS#7 file (.p7b). In our case it is .p7b.
              • Each certificate in the chain must imported into the keystore(starting first with the root cert). If the CA Reply does not include the chain certificates, they must be added to the keystore manually before the CA reply. 
              • In our case .p7b includes the cert chain.
            • The command is:
              • keytool -importcert -alias testkeytoolcert -keystore testkey.jks -file "Manoj Test-testkeytoolcert-AdminCA1.pkcs7"
            • Basically we are trying to import the certificate returned from the CA using the same alias that was used to generate the PrivateKey entry. Keytool will assign the certificate chain to the PrivateKey and record the reply from the CA.

          Option 3: Import an existing certificate ( in pkcs#12 format).

          Basically, the certificate and keys were generated using a different tool or process or by an  internal company process. The cert and key information has to be combined into a single pkcs#12 format by using openSSL:
          • openssl pkcs12 -export -in cert.crt -inkey key.key -out exported.p12 -name tomcat -CAfile myCA.crt -caname root -chain

          This certificate can then in imported in JKS keystore. 

          Option 4: Programmatically create a Certificate signed by a CA using SCEP

          This will be the subject of another blog post...
          <TODO: insert link to blog post on SCEP Enrollment>


          Resources



          Free GUI replacement for the Java command-line utilities keytool, jarsigner and jadtool. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.

            • Free but not open source. Cannot redistribute.
            • Allows exporting of the PrivateKey.
            • Refer a utility in security-utils project for importing a private key and certs.

          • Importing private keys into a Java keystore using keytool

          We need to convert our existing certificate and key into a PKCS12 file, and then use the keytool functionality to merge one keystore with another one. Java 6 can treat a PKCS12 file as a keystore so putting this together we get this:
            • keytool -importkeystore -deststorepass pwd -destkeypass pwd -destkeystore dest-keystore.jks -srckeystore src-certs-priv-key.p12 -srcstoretype PKCS12 -srcstorepass key-password -alias 1

          The alias of 1 is required to choose the certificate in the source PKCS12 file, keytool isn't clever enough to figure out which certificate you want in a store containing one certificate.


          Saturday, June 30, 2012

          PKI: Setting up and using a Certificate Authority using EJBCA

          In the post we will walk through the setup and configuration of EJBCA used as a CA.

          Setting up EJBCA

          Installation

          Refer http://ejbca.org/installation.html for details. Here are a few tips:


          1. Copied unlimited strength policy files to jre/lib/security
          2. Refer  <EJBCA>/conf/ejbca.properties for detailed setup of EJBCA and other properties. I modified  the file to set the following:
            1. appserver.home=jboss-5.1.0.GA
            2. ca.keystorepass=mypass
              1. Had to setup this entry correctly in to avoid token errors. Also verify that CA token is online in the Admin UI otherwise we run into issues while enrolling certificates.
          3. We are using the default hsqldb that comes with Jboss. I modified the  <EJBCA>/conf/database properties to set blank password for hsqldb. Changing the password in this file will require ant deploy to be executed again. Might be safer to use ant clean first.hsqldb-ds.xml has properties that can be enabled to allow tcp communication to the database. It is disabled by default.
            1. database.password=
          4. Verify that  jboss-5.1.0.GA/server/default/deploy/ejbca-ds.xml and hsqldb-ds.xml have the correct database properties/values. 
          5. Refer  <EJBCA>/conf/install.properties for detailed setup of the CA properties. To name a few properties:
            1. ca.name=AdminCA1
            2. ca.dn=CN=AdminCA1,O=EJBCA Sample,C=SE
            3. One can also specify a configuration file here which defines key name, password and key alias for the HSM used.
              1. ca.tokenproperties=/home/ejbca/ejbca/conf/catoken.properties
            4. ca.signaturealgorithm=SHA1WithRSA ( need to change this and try with a better one).
          6. Added bouncy castle jars from ejbca/lib to jboss/server/default/lib
          7. Run:
            1.  ant bootstrap
              1. Files modified/copied include:
                1. deploy/ejbca-ds.xml
                2. deploy/ejbca-mail-service.xml
                3. deploy/ejbca.ear
            2.  ant install ( all default properties except passwords)
            3. ant deploy
              1. conf/keystore/keystore.jks
              2. conf/keystore/truststore.jks
              3. deploy/jboss-web.deployer/server.xml
          8. Known issues
            1. On JBoss 5.1.x (not on JBoss 6.0.x) the WSDL location gets incorrectly generated by default. 
              1. To fix this (see JBoss settings during install) edit: APPSRV_HOME/server/default/deployers/jbossws.deployer/META-INF/jboss-beans.xml and comment out the line: <property name="webServiceHost">${jboss.bind.address}</property> to force the location to be generated with info from the WSDL request. 
              2. If this is not done you will get "HTTP 302 Moved Temporarily" errors when running the WS client.
            2. If you are using Oracle's JDK and JBoss 5.1.x you need to copy EJBCA_HOME/lib/bc*.jar to JBOSS_HOME/server/default/lib/. Remember this when it's time for upgrades! This is a bug tracked by JBoss as JBAS-7882. OpenJDK works just fine though, such as the OpenJDK distributed with RedHat, Ubuntu, Debian etc.
            3. See installation link for other known issues with 5.1 and other Jboss versions.

          Sample Output

          Here are a few excerpts from the console:

          Output 1:

          Initializing CA
               [java] Generating rootCA keystore:
               [java] CA name: AdminCA1
               [java] SuperAdmin CN: SuperAdmin
               [java] DN: CN=AdminCA1,O=EJBCA Sample,C=SE
               [java] CA token type: soft
               [java] CA token password: hidden
               [java] Keytype: RSA
               [java] Keyspec: 2048
               [java] Validity (days): 3650
               [java] Policy ID: null
               [java] Signature alg: SHA1WithRSA
               [java] Certificate profile: ROOTCA
               [java] CA token properties: null
               [java] Signed by: self signed
               [java] Initalizing Temporary Authorization Module with caid=-xxxx and
           superadmin CN 'SuperAdmin'.
               [java] Creating CA...
               [java] CAId for created CA: -xxxx
               [java] -Created and published initial CRL.
               [java] CA initialized

          Output 2a

          Trying to add user:
          Username: tomcat
               [java] Password: <password hidden>
               [java] DN: CN=localhost,O=EJBCA Sample,C=SE
               [java] CA Name: AdminCA1
          ...
          Generating keys in directory <EJBCA>/p12.
          Generating keys for tomcat.
               [java] Created Keystore for 'tomcat'.
               [java] New user generated successfully - tomcat.

          Output 2b

          Trying to add user:
               [java] Username: superadmin
               [java] Password: <password hidden>
               [java] DN: CN=SuperAdmin
               [java] CA Name: AdminCA1

          Generating keys in directory C:worldsecurityejbca_4_0_9p12.
               [java] Generating keys for superadmin.
               [java] Created Keystore for 'superadmin'.
               [java] New user generated successfully - superadmin.

          Output 3

          Wrote Root CA certificate to '<Local>\Temp/rootca.der' using DER encoding.
               [echo] Adding to or creating keystore: <EJBCA>/p12/truststore.jks



          Files Generated in <EJBCA>/p12

          • superadmin.p12

            • Copy this file to admin desktop machine and import in web browser. AdminUI uses client authentication and won't work without this. This is the super administrators certificate used to access the admin GUI. Other administrators with specific privileges can be created later on. The default password for superadmin.p12 is ejbca, and is configured in web.properties.
            • For creating other CAs or expired CAs...
              • ant -Dca.name="My CA Name" javatruststore
              • This adds the CA certificate to p12/truststore.jks and copies this file to JBOSS_HOME/server/default/conf/keystore, where the SSL keystores are located.

          • tomcat.jks

            • This is for the servlet container in Jboss (tomcat ofcourse) and doesn't have to be tampered with. Here is a sample output of the keys(password is default pass used):
                             <EJBCA>\p12>keytool -list -keystore tomcat.jks
                           cacert, Jun 1, 2012, trustedCertEntry, Certificate fingerprint (SHA1): 33:DA...
                             localhost, Jun 1, 2012, PrivateKeyEntry, 
                            Certificate fingerprint (SHA1): F8:4...

              • truststore.jks
                      This is for the servlet container in Jboss (tomcat ofcourse) and doesn't have to be    tampered with.


              Accessing EJBCA

              Access EJBCA to verify the install. 

              Start Jboss

              jboss-5.1.0.GA\bin>run.bat > c:\jboss.log

              Access Admin UI



                               Name: manojscepcertificate
                              Password: manojscepcertificate
                              CN=manojscepcertificate


                • Also, if the certificate is intended for Tomcat, then the below properties should be set correctly under the "Main Certificate Data" section:
                  • Certificate Profile:             SERVER
                  • CA:                                  AdminCA1
                  • Token:                             User Generated


              • Note: Double check if Token needs to be set to P12 for the enrollment to work correctly?
                • For instance the "tomcat" user that was created as part of install, has a generated certificate and the token is set to jks. So most probably the token should have an impact on what is returned from the server. Setting it to user defined might work as well since the (SCEP) client can dictate this.
              • You can search and edit the entities as well.

              EJBCA UI

              Access the UI via https://localhost:8443/ejbca/index.jsp 
              This UI allows enrolling for new certificates, getting the certificates and CRLs and links to Administration.

              Certificate Enrollment

              Click on "Create Certificate from CSR" in the UI or navigate to https://localhost:8443/ejbca/enrol/server.jsp and provide the below details:

              • Username ( entity created in admin UI)
              • Password ( entity created in admin UI)
              • Request file.
                • This corresponds to the CSR file that can be created by using the Keytool supplied with JDK. One can also use openSSL or any other tool for creating this as well.
                • Refer my blog post on how to create a certificate.
                • The CSR can be PEM- or DER-formated file. One can also paste the PEM formatted contents directly into the textbox as well. 
                • A PEM-formatted request is a BASE64 encoded certificate request starting with
                  • -----BEGIN CERTIFICATE REQUEST-----
                  • and ending with
                  • -----END CERTIFICATE REQUEST-----
              • The result type should be set to "PKCS#7" to get a single file with the Reply and the certificate chain. 
              • This returned reply can be imported in the keystore to complete the Certificate generation and signing process. Again, refer my blog post on how to create a certificate to get details on the import process.

              Certificate Enrollment Using SCEP

              This is the subject of another blog post. <TODO: insert link to blog post on SCEP enrollment>

              References

              Saturday, June 9, 2012

              Security: Information Security, threats, risks



              Vulnerability is software, hardware, procedural, or human weakness that may provide an attacker the open door he is looking for to enter a computer or network and have unauthorized access to resources within the environment. A vulnerability characterizes the absence or weakness of a safeguard that could be exploited.

              Threat is any potential danger to information or systems. The threat is that someone, or something, will identify a specific vulnerability and use it against the company or individual. The entity that takes advantage of a vulnerability is referred to as a threat agent.

              Risk is the likelihood of a threat agent taking advantage of a vulnerability and the corresponding business impact. If a firewall has several ports open, there is a higher likelihood that an intruder will use one to access the network in an unauthorized method.

              An exposure is an instance of being exposed to losses from a threat agent.

              A countermeasure, or safeguard, is put into place to mitigate the potential risk. A countermeasure may be a software configuration, a hardware device, or a procedure that eliminates a vulnerability or that reduces the likelihood a threat agent will be able to exploit a vulnerability.


              Typical Threat Agents:
              • Accidental discovery
              • Automated malware
              • curious attacker
              • Script kiddie
              • motivated attacker ( or disgruntled employee)
              • Organized crime.

              Security model

              Security Principles
              • Minimize attack surface
              • secure defaults
              • principle of least privilege
              • defense in depth
              • Fail securely
              • External systems are insecure.
              • separation of duties
                • It ensures no single person has total control over an activity or task.
                • Split knowledge and dual control are two aspects of separation of duties.
              • Do not trust security through obscurity
              • simplicity
              • fix security issues correctly
              Security planning
              Has various layers, but it also has different types of goals to accomplish in different time frames.
              • Strategic planning is the plans that fall in line with the business and information technology goals.
              • Tactical planning refers to the initiatives and other support that must be implemented to reach the broader goals that have been put forth by the strategic planning
              • operational planning deals with very specific plans, their deadlines, and goals.
              This approach to planning is called the planning horizon.

              Security Frameworks


              The Control Objectives for Information and related Technology (CobiT) was created by the Information Systems Audit and Control Association (ISACA) to provide specific guidance for creating and assessing IT controls. It is a framework and set of best practices developed by the Information Systems Audit and Control Association (ISACA) and the IT Governance Institute (ITGI). It defines goals for the controls that should be used to properly manage IT and to ensure that IT maps to business needs. 
              CobiT is broken down into four domains(34 IT processes, ranging from strategic planning to implementation, production support and monitoring):

              • Plan and Organize, 
              • Acquire and Implement, 
              • Deliver and Support, and 
              • Monitor and Evaluate.

              CobiT

              CobiT is a framework that defines goals for the controls that should be used to properly manage IT and to ensure that IT maps to business needs.

              Derived from the COSO framework, developed by the Committee of Sponsoring Organizations (COSO) of the Treadway Commission in 1985 to deal with fraudulent financial activities and reporting. The COSO framework is made up of the following components:

              • Control environment

               - Management's philosophy and operating style
               - Company culture as it pertains to ethics and fraud

              • Risk assessment

               - Establishment of risk objectives
               - Ability to manage internal and external change

              • Control activities

               - Policies, procedures, and practices put in place to mitigate risk

              • Information and communication

               - Structure that ensures that the right people get the right information at the right time

              • Monitoring

               - Detecting and responding to control deficiencies

              COSO is a Model for corporate governance and CobiT is a model for IT governance. COSO deals more at the strategic level, while CobiT focuses more at the operational level. You can think of CobiT as a way to meet many of the COSO objectives, but only from the IT perspective. COSO deals with non-IT items also, as in company culture, financial accounting principles, board of director responsibility, and internal communication structures. COSO was formed to provide sponsorship for the National Commission on Fraudulent Financial Reporting, an organization that studies deceptive financial reports and what elements lead to them.

              COBIT information security topics
              • Security Policy
                  A policy would typically address a specific topic such as acceptable use of company e-mail, or wireless communications.
              • Security Standards
              For example, the Benchmark provided by the Center for Internet Security (CIS). This benchmark provides specific guidance for configuring security on a Windows 2000 server.
              • Access and Authentication
              In addition to AA,   Includes user and account mgmt.
              • Network Security
               firewalls, intrusion detection systems (IDS), encryption, certificates.
               - antivirus is mandatory.
               - use ethical hacking or penetration testing to test systems.
              • Monitoring
              invalid logins, port scans, invalid authorization requests,  use analysis tools if appt.
              • Segregation of Duties
              • Physical Security

              The Information Technology Governance Institute (ITGI) is a group created to assist corporations with governing their IT and ensuring IT efficiently supports business mission and goals. ITGI has used COSO and COBIT to create a set of specific IT control objectives for SOX.

              Security Standards

              Guidelines are recommendations and general approaches that provide advice and flexibility. 

              There are standards and industry best practices, which provide the guidance and recipe for how to set up and implement a full security program.

              A standard specifies how hardware and software are to be used. Standards are compulsory. 

              The most common standard used to be ISO 17799, which was derived from the British Standard 7799
              (BS7799). It is an internationally recognized Information Security Management (ISM) Standard that provides high-level conceptual recommendations on enterprise security. The British Standard actually has two parts:

              • - BS7799 Part 1: outlines control objectives and a range of controls to meet those objectives; and 
              • - BS7799 Part 2, which outlines how a security program can be set up and maintained. 


              BS7799 Part 2 also served as a baseline that organizations could be certified against. To become certified against the ISO 17799, an authorized third party would evaluate the organization against the requirements in ISO 17799 Part 2. The organization could be certified against all or just a portion of ISO 17799 Part 2.

              ISO/IEC 27000


              ISO 9000 series comprises many standards that deal with quality control for business processes. A new series, ISO/IEC 27000, is used for assurance and security standards. ISO has overhauled the 17799 standards to correspond with their current numbering format. Following are the ISO/IEC series that are used as blueprints for organizations to follow when developing their security program:

              • ISO/IEC 27001 Based on British Standard BS7799 Part 2, which is establishment, implementation, control, and improvement of the Information Security Management System
                • It is the standard for the establishment, implementation, control, and improvement of the Information Security Management System.
              • ISO/IEC 27002 Code of practice providing good practice advice on ISMS (previously known as ISO 17799 part 1), itself based on British Standard BS 7799 Part 1
                • It is a comprehensive set of controls comprising best practices in information security and provides guidelines on how to set up and maintain security programs.
              • ISO/IEC 27004 A standard for information security management measurements
              • ISO/IEC 27005 Designed to assist the satisfactory implementation of information security based on a risk management approach
              • ISO/IEC 27006 A guide to the certification/registration process
              • ISO/IEC 27799 A guide to illustrate how to protect personal health information
              The ISO/IEC 27002 (formerly ISO 17799) domains are as follows:
              • Information security policy for the organization
              • Creation of information security infrastructure
              • Asset classification and control
              • Personnel security
              • Physical and environmental security
              • Communications and operations management
              • Access control
              • System development and maintenance
              • Business continuity management
              • Compliance

              ITIL 

              Where CobiT defines IT goals, ITIL provides the steps at the process level on how to achieve those goals. Although ITIL has a component that deals with security, its focus is more toward internal service level agreements between the IT department and the "customers" it serves. The customers are usually internal departments.

              Security Governance

              Security governance is all of the tools, personnel, and business processes necessary to ensure that the security implemented meets the organization's specific needs.

              Governance is the set of responsibilities and practices exercised by the board and executive management with the goal of providing strategic direction, ensuring that objectives are achieved, ascertaining that risks are managed appropriately, and verifying that the enterprise's resources are used responsibly.

              Security Program Development

              It is important to understand that a security program has a life cycle that is always continuing, because it should be constantly evaluated and improved upon.  The security program should be integrated with current business objectives and goals.

              The life cycle of any process can be described in different ways.

              1.     Plan and Organize
              • Establish management commitment.
              • Establish oversight steering committee.
              • Assess business drivers.
              • Carry out a threat profile on the organization.
              • Carry out a risk assessment.
              • Develop security architectures at an organizational, application, network, and component level.
              • Identify solutions per architecture level.
              • Obtain management approval to move forward.
              2.     Implement
              • Assign roles and responsibilities.
              •  Develop and implement security policies, procedures, standards, baselines, and guidelines.
              •  Identify sensitive data at rest and in transit.
              •  Implement the following blueprints:
              •  Asset identification and management
              •  Risk management
              •  Vulnerability management
              •  Compliance
              •  Identity management and access control
              •  Change control
              •  Software development life cycle
              •  Business continuity planning
              •  Awareness and training
              •  Physical security
              •  Incident response
              •  Implement solutions (administrative, technical, physical) per blueprint.
              •  Develop auditing and monitoring solutions per blueprint.
              •  Establish goals, service level agreements (SLAs), and metrics per blueprint.
              3.     Operate and Maintain
              •  Follow procedures to ensure all baselines are met
              •  Carry out internal and external audits.
              •  Carry out tasks outlined per blueprint.
              •  Manage service level agreements
              4.     Monitor and Evaluate
              •  Review logs, audit results, collected metric values, and SLAs per blueprint.
              •  Assess goal accomplishments
              • quarterly meetings
              •  improvement steps and integrate into the Plan and Organize phase.

              Information risk management (IRM) 

              IRM is the process of identifying, assessing, and reducing risk to an acceptable level and implementing the right mechanisms to maintain that level of risk.

              Proper risk management requires a strong commitment from senior management, a documented process that supports the organization's mission, an IRM policy, and a delegated IRM team.

              The risk management team should include individuals from different departments within the organization, not just technical personnel.

              Threats must be identified, classified by category, and evaluated to calculate their damage potential to the company. Real risk is hard to measure, but prioritizing the potential risks in order of which ones must be addressed first is possible.

              Risk analysis

              which is really a tool for risk management, is a method of identifying vulnerabilities and threats and assessing the possible impacts to determine where to implement security safeguards. Risk analysis is used to ensure that security is cost-effective, relevant, timely, and responsive to threats.

              Identifying Threats

              Illogical processing and cascading errors would mean invalid results are passed
              on to another process. Risks have loss potential, meaning what the company would lose if a threat agent were actually to exploit a vulnerability. Must look at delayed loss when assessing the damages that can occur

              Methodologies for Risk Assessment

              • NIST SP 800-30 and 800-66 are methodologies that can be used by the general public, but the initial creation of 800-66 was designed to be implemented in the healthcare field and other regulated industries. While 800-66 was designed to be used by HIPAA clients, it can also be readily adopted and used by other regulated industries. The NIST approach is specific to IT threats and is commonly used by security consultants, security officers and internal IT departments, and focuses mainly on computer systems

              ·        FRAP

              Which stands for Facilitated Risk Analysis Process. It is designed to explore a qualitative risk assessment process in a manner that allows for tests to be conducted on different aspects and variations of the methodology. This will allow, through the use of a prescreening process, users to determine the areas that really demand and need risk analysis within an organization. 
              • OCTAVE (Operationally Critical Threat, Asset, and Vulnerability Evaluation) was created by Carnegie Mellon University's Software Engineering Institute. It is a methodology that is intended to be used in situations where people manage and direct the risk evaluation for information security within their company. 
                       The limitations of OCTAVE are:
              1. OCTAVE is incompatible with AS/NZS 4360, as it mandates Likelihood = 1 (i.e., It assumes a threat will always occur)
              2. Consisting of 18 volumes, OCTAVE is large and complex, with many worksheets and practices to implement.
              3. It does not provide a list of “out of the box” practices for assessing and mitigating web application security risks.
              4. Because of these issues and not considering, OWASP does not anticipate that OCTAVE will be used at large by application designers or developers

              • AS/NZS 4360: While both the NIST and OCTAVE methodologies focus on IT threats and information security risks, AS/NZS 4360 takes a much broader approach to risk management. This methodology can be used to understand a company's financial, capital, human safety, and business decisions risks. Although it can be used to analyze security risks, it was not created specifically for this purpose.
              o   The advantages of AS/NZS 4360:
                  • AS/NZS 4360 works well as a risk management methodology for organizations requiring Sarbanes-Oxley compliance.
                  • AS/NZS 4360 works well for organizations that prefer to manage risks in a traditional way, such as just using likelihood and consequence to determine an overall risk.
                  • AS/NZS 4360 is familiar to most risk managers worldwide, and your organization may already have implemented an AS/NZS 4360 compatible approach.
                  • You are an Australian organization, and may be required to use it if you are audited on a regular basis, or to justify why you aren’t using it. Luckily, the STRIDE/DREAD model discussed earlier is AS/NZS 4360 compatible.
                • The limitations of AS/NZS 4360:
                  • The AS/NZS 4360 approach works best for business or systemic risks than for technical risks.
                  • AS/NZS 4360 does not define the methodology to perform a structured threat risk modeling exercise.
                  • As AS/NZS 4360 is a generic framework for managing risk, it does not provide any structured method to enumerate web application security risks.
                            Although AS/NZS 4360 may be used to rank risks for security reviews, the lack of structured methods of enumerating threats for web applications makes it less desirable than other methodologies described earlier.
              • CVSS: The US Department of Homeland Security (DHS) established the NIAC Vulnerability Disclosure Working Group, which incorporates input from Cisco Systems, Symantec, ISS, Qualys, Microsoft, CERT/CC, and eBay. One of the group’s outputs is the Common Vulnerability Scoring System (CVSS).
              • Failure Modes and Effect Analysis (FMEA) is a method for determining functions, identifying functional failures, and assessing the causes of failure and their failure effects through a structured process. While FMEA is most useful as a survey method to identify major failure modes in a given system, the method is not as useful in discovering complex failure modes that may be involved in multiple systems or subsystems. 
              • A fault tree analysis usually proves to be a more useful approach to identifying failures that can take place within more complex environments and systems.

              Quantitative risk analysis 

              attempts to assign real and meaningful numbers to all elements of the risk analysis process. These elements may include safeguard costs, asset value, business impact, threat frequency, safeguard effectiveness, exploit probabilities, and so on. Purely quantitative risk analysis is not possible because the method attempts to quantify qualitative items, and there are always uncertainties in quantitative values

              Note Quantitative analysis uses risk calculations that attempt to predict the level of monetary losses and the probability for each type of threat. Qualitative analysis does not use calculations. Instead, it is more opinion-and scenario based.

              The Single loss expectancy is a dollar amount that is assigned to a single event that represents the company's potential loss amount if a specific threat were to take place:
              •             SLE = asset value × exposure factor (EF)
              exposure factor (EF) represents the percentage of loss a realized threat could have on a certain asset
              • annualized loss expectancy (ALE) = SLE × annualized rate of occurrence (ARO)

              annualized rate of occurrence (ARO) is the value that represents the estimated frequency of a specific threat taking place within a one-year timeframe.

              Qualitative Risk Analysis

              Does not assign numbers and monetary values to components and
              losses. Instead, qualitative methods walk through different scenarios of risk possibilities and rank the seriousness of the threats and the validity of the different possible countermeasures based on opinions.

              A qualitative rating would be expressed in high, medium, or low, or on a scale of 1 to 5 or 1 to 10. A quantitative result would be expressed in dollar amounts and percentages. 

                   In risk analysis, uncertainty refers to the degree to which you lack confidence in an estimate.

              The Delphi technique is a group decision method used to ensure that each member gives an honest opinion of what he or she thinks the result of a particular threat will be.

              Advantages of Qualitative

              Requires no calculations 
              Provides general areas and indications of risk 
              Provides the opinions of the individuals who know the processes best.


              Advantages of Quantitative.

              Uses independently verifiable and objective metrics
              Is easier to automate and evaluate
              Very less guesswork 
              Provides credible cost/benefit analysis 
              Used in risk management performance tracking 

              A security countermeasure, sometimes called a safeguard, must make good business sense, meaning it is cost-effective (its benefit outweighs its cost). This requires another type of analysis: a cost/benefit analysis. A commonly used cost/benefit calculation for a given safeguard is
              (ALE before implementing safeguard) - (ALE after implementing safeguard) - (annual cost of safeguard) = value of safeguard to the company

              Total Risk vs. Residual Risk

              • threats × vulnerability × asset value = total risk
              • (threats × vulnerability × asset value) × controls gap = residual risk

              Handling Risk

              Project sizing, which means to understand and document the scope of the project, must be done before a risk analysis is performed.

              The main goals of risk analysis are the following: identify assets and assign values to them, identify vulnerabilities and threats, quantify the impact of potential threats, and provide an economic balance between the impact of the risk and the cost of the safeguards.

              Steps of a Risk Analysis
              • Step 1: Assign Value to Assets
                • When determining the value of information, the following issues must be considered: the cost to acquire and develop data; the cost to maintain and protect data; the value of the data to owners, users, and adversaries; the cost of replacement if the data is lost; the price others are willing to pay for the data; lost opportunities; and the usefulness of the data
              • Step 2: Estimate Potential Loss Per Threat (including SLE)
              • Step 3: Perform a Threat Analysis
              • Step 4: Derive the Overall Annual Loss Potential Per Threat
              • Step 5: Reduce, Transfer, Avoid, or Accept the Risk

              3 Main steps for Risk Analysis:

              • Asset and Information value assignment
              • Risk Analysis and assessment
              • countermeasure selection and implementation
              Risk Management could take the input from Planning and collecting information and defining the recommendations. It can then handle the risk as:
              • Risk transfer
              • Risk Avoidance
              • Risk Mitigation
              • Risk Acceptance
              Automated risk analysis tools reduce the amount of manual work involved in the analysis. They can be used to estimate future expected losses and calculate the benefits of different security measures. 

              Security Policy

              A security policy is a statement by management dictating the role security plays in the organization. A security policy can be an organizational policy, an issue-specific policy, or a system-specific policy.



              Due diligence is an understanding of the current threats and risks, and due care is implementing countermeasures to provide protection from those threats. If a company does not practice due care and due diligence pertaining to the security of its assets, it can be legally charged with negligence and held accountable for any ramifications of that negligence. 

              Other regulations also call out requirements of boards of directors, as in the Gramm-Leach-Bliley Act (GLBA). But SOX is a regulation that holds the members of the board personally responsible, thus they can each be fined or go to jail.

              Principles of Federal Prosecution of Business Organizations

              The Department of Justice provides the following guidelines for attorneys when attempting to prosecute corporate wrongdoings:
              Do the corporation's directors exercise independent review over proposed corporate actions rather than unquestioningly ratifying officers' recommendations; are the directors provided with information sufficient to enable the exercise of independent judgment; are internal audit functions conducted at a level sufficient to ensure their independence and accuracy; and have the directors established an information and reporting system in the organization reasonably designed to provide management and the board of directors with timely and accurate information sufficient to allow them to reach an informed decision regarding the organization's compliance with the law.

              International Requirements

              If the organization is exchanging data with European entities, it may need to adhere to the safe harbor requirements. outlines how any entity that is going to move privacy data to and from Europe must go about protecting it.
              Global organizations that move data across other country boundaries must also be aware of and follow the
              Organisation for Economic Co-operation and Development (OECD) Guidelines and transborder information flow rules.

              Summary: Security management 

              A security program should address issues from a strategic, tactical, and operational view.

              A key element during the initial security planning process is to define reporting relationships.

              Security management embodies the administrative and procedural activities necessary to support and protect information and company assets throughout the enterprise. 
              • Management must define the scope and purpose of security management, provide support, appoint a security team, delegate responsibility, and review the team's findings.
              • It includes development and enforcement of security policies and their supporting mechanisms: procedures, standards, baselines, and guidelines. 
              • It encompasses risk management, security awareness training, and proper countermeasure selection and implementation. 
              • Personnel (hiring, terminating, training, and management structure) and operational (job rotation and separation of duties) activities must also be conducted properly to ensure a secure environment. 
              • Management must understand the legal and ethical responsibilities it is required to respect and uphold.
              • Security management should work from the top down (from senior management down to the staff).
              Summary
              • The objectives of security are to provide availability, integrity, and confidentiality protection to data and resources.
              • Security components can be technical (firewalls, encryption, and access control lists) or nontechnical (security policy, procedures, and compliance enforcement).
              • Asset identification should include tangible assets (facilities and hardware) and intangible assets (corporate data and reputation).
              • Assurance is a degree of confidence that a certain security level is being provided.
              • Procedures are detailed step-by-step actions that should be followed to achieve a certain task.
              • A baseline is a minimum level of security. 
              • Job rotation is a control to detect fraud.
              • Mandatory vacations are a control type that can help detect fraudulent activities. 
              • Data is classified to assign priorities to data and ensure the appropriate level of protection is provided.
              • Data owners specify the classification of data.
              • Security has functional requirements, which define the expected behavior from a product or system, and assurance requirements, which establish confidence in the implemented products or systems overall.
              • Safeguards should default to least privilege, and have fail-safe defaults and override capabilities.
              • Safeguards should be imposed uniformly so everyone has the same restrictions and functionality.
              • The data custodian (information custodian) is responsible for maintaining and protecting data.
              • A security analyst works at a strategic level and helps develop policies, standards, and guidelines, and also sets various baselines.
              • Application owners are responsible for dictating who can and cannot access their applications, as well as the level of protection these applications provide for the data they process and for the company.

              Appendix A: Microsoft Threat Modelling


              Should fit alongside the "methodologies for Risk assessment" above.

              STRIDE

              STRIDE is a classification scheme for characterizing known threats according to the kinds of exploit that are used (or motivation of the attacker). 
              Spoofing Identity “Identity spoofing” is a key risk for applications that have many users but provide a single execution context at the application and database level. 
              Tampering with Data Users can potentially change data delivered to them, return it, and thereby potentially manipulate client-side validation, GET and POST results, cookies, HTTP headers, and so forth. 
              Repudiation Users may dispute transactions if there is insufficient auditing or recordkeeping of their activity. 
              Information Disclosure. Therefore, applications must include strong controls to prevent user ID tampering and abuse, particularly if they use a single context to run the entire application.
              Denial of Service Application designers should be aware that their applications may be subject to a denial of service attack.
              Elevation of Privilege If an application provides distinct user and administrative roles, then it is vital to ensure that the user cannot elevate his/her role to a higher privilege one.

              DREAD

              DREAD is a classification scheme for quantifying, comparing and prioritizing the amount of risk presented by each evaluated threat. T
              Risk_DREAD = (DAMAGE + REPRODUCIBILITY + EXPLOITABILITY + AFFECTED USERS + DISCOVERABILITY) / 5
              The calculation always produces a number between 0 and 10; the higher the number, the more serious the risk.

              Threat Modeling Process

              • Identify assets.
              • Create an architecture overview.
                • Identify what the application does.
                • Create an architecture diagram.
                • Identify the technologies.
              • Decompose the application.
                •  
                • Identify trust boundaries.
                • Identify data flow.
                • Identify entry points.
                • Identify privileged code.
                • Document the security profile.
              • Identify the threats(you can use STRIDE).
                •  
                • Identify network threats.
                • Identity host threats.
                • Identify application threats.
                  •  
                  • Using Attack Trees and Attack Patterns
                    • An attack tree is a way of collecting and documenting the potential attacks on your system in a structured and hierarchical manner. The tree structure gives you a descriptive breakdown of various attacks that the attacker uses to compromise the system.
                  • Attack Patterns
                    • Attack patterns are generic representations of commonly occurring attacks that can occur in a variety of different contexts. 
              • Document the threats.
              • Rate the threats.
                • You can  use the DREAD model to rate the threats or use a quantitative approach.
              For more details on alternative Threat modeling systems refer: 



              These are my notes collected from various sources and this is not claimed as original content.