Thursday, 30 July 2015

Uncontrolled format string

Uncontrolled format string[1] is a type of software vulnerability, discovered around 1999, that can be used in security exploits. Previously thought harmless, format string exploits can be used to crash a program or to execute harmful code. The problem stems from the use of unchecked user input as the format string parameter in certain C functions that perform formatting, such as printf(). A malicious user may use the %s and %x format tokens, among others, to print data from the call stack or possibly other locations in memory. One may also write arbitrary data to arbitrary locations using the %n format token, which commands printf() and similar functions to write the number of bytes formatted to an address stored on the stack.

In the example below allow user to input a buffer conaining "% n" will crash the program without
providing a actual variable it's expecting.

#include "stdafx.h"
#include <stdio.h>
#include <stdarg.h>

char bad_buffer[] = "this is a bad formatted string 10% n \n";

void Error(const char* format, ...);

void Error(const char* format, ...)
    char dest[1024 * 16] = "";
    va_list argptr;
    va_start(argptr, format);
    vsprintf_s(dest, format, argptr);

int _tmain(int argc, _TCHAR* argv[])
    return 0;

Sunday, 19 July 2015

How to config tomcat with https

1>download tomcat
2>download java jdk (jre won't cut it), set JAVA_HOME to jdk folder
3>generate a keypair and store it in a keystore(jks) file, say c:\myCer\mycer.jks
either use keytool or use keystore explorer, i have used the latter.

4>pointing tomcat's configuration conf\server.xml :

    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" keystoreFile="C:\myCer\mycer.jks" keystorePass="changeit" />

5>restart tomcat

connect to tomcat via https://localhost:8443/

You can see chrome doesn't like it because the keystore and keypair are generated my myself, means its self signed, not trusted by any public CA...

But  if you click on "Proceed to localhost (unsafe)", you will see the tomcat page:

this way any communication will be encrypted (like username/password) 

Ref link and link.

Saturday, 18 July 2015

Truststore and Keystore Definitions


What's the difference between a keystore and a truststore?


A keystore contains private keys, and the certificates with their corresponding public keys.
A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.
In SSL handshake purpose of trustStore is to verify credentials and purpose of keyStore is to provide credential
 keyStore in Java stores private key and certificates corresponding to there public keys and require if you are SSL Server or SSL requires client authentication.

TrustStore stores certificates from third party, your Java application communicate or certificates signed by CA(certificate authorities like Verisign, Thawte, Geotrust or GoDaddy) which can be used to identify third party.

TrustManager determines whether remote connection should be trusted or not i.e. whether remote party is who it claims to and KeyManager decides which authentication credentials should be sent to the remote host for authentication during SSL handshake.

If you are an SSL Server you will use private key during key exchange algorithm and send certificates corresponding to your public keys to client, this certificate is acquired from keyStore. On SSL client side, if its written in Java, it will use certificates stored in trustStore to verify identity of Server. SSL certificates are most commonly comes as .cer file which is added into keyStore or trustStore by using any key management utility e.g. keytool.
1)First and major difference between trustStore and keyStore is that trustStore is used by TrustManager and keyStore is used by KeyManager class in Java. KeyManager and TrustManager performs different job in Java, TrustManager determines whether remote connection should be trusted or not i.e. whether remote party is who it claims to and KeyManager decides which authentication credentials should be sent to the remote host for authentication during SSL handshake. if you are an SSL Server you will use private key during key exchange algorithm and send certificates corresponding to your public keys to client, this certificate is acquired from keyStore. On SSL client side, if its written in Java, it will use certificates stored in trustStore to verify identity of Server. SSL certificates are most commonly comes as .cer file which is added into keyStore or trustStore by using any key management utility e.g. keytool. See my post How to add certificates into trustStore for step by step guide on adding certificates into keyStore or trustStore in Java.
2) Another difference between trustStore and keyStore in rather simple terms is that keyStore contains private keys and required only if you are running a Server in SSL connection or you have enabled client authentication on server side. On the other hand trustStore stores public key or certificates from CA (Certificate Authorities) which is used to trust remote party or SSL connection.
3)One more difference between trustStore vs KeyStore is that we use to specify path for keyStore and to specify path for trustStore in Java.
4) Another difference between trustStore and keyStore is that, If you store your personal certificate along with signer certificate in trustStore,  you can use same file as both trustStore and keyStore. By the way its good idea to separate personal certificate and signer certificates in keyStore and trustStore for better management.
5) One more API level difference between keyStore and trustStore is that  password of keyStore is provided using and password of trustStore is provided using
That’s all on difference between trustStore and keyStore in Java. You can still use same file as trustStore and keyStore in Java to avoid maintaining two separate files, but its good idea to segregate public keys and private keys in two different files, its more verbose and self explanatory that which one holds CA certificates to trust server and which contains client's private keys.


When generating SSH authentication keys on a Unix/Linux system with ssh-keygen, you're given the choice of creating a RSA or DSA key pair (using -t type).
What is the difference between RSA and DSA keys? What would lead someone to choose one over the other?

When generate keypair via java keytool or keystore explorer, you are given choice of
RSA and DSA, which one should I choose ?

Short answer: just use RSA 2048 +.

Lone one:

RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)
RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms creates a 320 bit signature, but with 512-1024 bit security security again rests on difficulty of computing discrete logarithms has been quite widely accepted

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h1
then each user chooses a private key and computes their public key:
choose x compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.
DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures
DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

And see "What is better for GPG keys - RSA or DSA?" @ SuperUser : )
Also note that DSA can only be used for signing/verification, whereas RSA can be used for encryption/decrypt as well.

X.509 keytool 学习笔记详解

X.509 and keytool

注: 证书更改操作(导入,删除等),都必需重启WEB应用.否则证书库的缓存无法清除.一般客户端的证书不需吊销,也没意义,直接让其无法登陆就行.
spring security3 的X.509配置在双向认证中,可直接登录,即网银中使用U盾就可以不用输入用户名和密码直接登录系统.
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" requires-channel="https"/>
    <intercept-url pattern="/**" access="ROLE_USER"  requires-channel="https"/>
    <x509 subject-principal-regex="CN=(.*?)," user-service-ref="userService"/>
<user-service id="userService">
    <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
    <user name="user" password="user" authorities="ROLE_USER" />

要获得数字证书,我们需要使用数字证书管理工具(如KeyTool和OpenSSL)构建CSR(Certificate Signing Request,数字证书签发申请),交由CA机构签发,
truststore:双向认证中是必须的,如果没有显式的指定,默认指定为$JAVA_HOME/lib/security/cacerts 这个文件。
双向SSL认证,服务器必须要信任客户端证书,因此,必须把客户端证书添加为服务器的信任认证中心,即$JAVA_HOME/lib/security/cacerts 这个文件
1)KeyStore: 其中保存服务端的私钥
2)Trust KeyStore:其中保存客户端的授权证书

1.keystore 文件
(1)密钥实体(Key entity): 密钥(secret key)又或者是私钥和配对公钥(采用非对称加密)
(2)可信任的证书实体(trusted certificate entries): 也可称为公钥.

-genkey  创建证书库.
-import      将已签名数字证书导入密钥库  keytool -import -alias sage -keystore sagely -file sagely.crt
             导入已签名数字证书用keytool -list -v 以后可以明显发现多了认证链长度,并且把整个CA链全部打印出来。
-delete 删除指定别名的条目(密钥及证书)
-trustcacerts 表示将数字证书导入信任库。
-alias 密钥别名(任意不重复).证书实体关联着密钥实体,可通过别名删除整个条目(证书).
-dname 表示密钥的Distinguished Names,
        CN=commonName  即对于服端证书时为网站域名,客户端则任意.通常使用域名或带有通配符“*”的泛域名,如“*”标识用户身份。
Distinguished Names表明了密钥的发行者身份
-keyalg   指定密钥的加密算法,支持RSA(通常)和DSA共2种算法,默认算法为DSA。
-keypass 密钥的密码
-keystore 指定keystore文件及路径(产生的信息存在.keystore文件中)
在Wnidows下,文件的位置为:C:\Documents and Settings\ALGZ\.keystore
-storepass 访问keystore(密钥库)的密码,这个密码提供系统从mykeystore文件中将信息取出
-validity 该密钥的有效期,以天为单位
-keysize     指定密钥长度,以位为单位.
-file        参数指定导出证书的文件名.
-sigalg 指定数字签名算法,这里指定为SHA1withRSA算法,通常不用设置。
-rfc 指定以Base64编码格式输出,通常不设置。

 keytool -genkey -alias bogus -keysize 512 -validity 3650 -keyalg RSA -dname ", OU=XXX CA, O=Bogus Inc, L=Stockholm, S=Stockholm,
C=SE" -keypass boguspw -storepass boguspw -keystore sean.cert
例如:keytool -export -keystore monitor.keystore -alias monitor -file monitor.cer
将把证书库 monitor.keystore 中的别名为 monitor 的证书导出到 monitor.cer 证书文件中.它包含证书主体的信息及证书的公钥,不包括私钥,可以公开。
keytool -export -keystore d2aApplet.keystore -alias RapaServer -file Rapa.cert -storetype IAIKKeystore
这里向Java默认的证书 cacerts导入Rapa.cert
keytool -import -alias RapaServer -keystore cacerts -file Rapa.cert
通常该命令用以导入来自CA中心的证书(Importing a Certificate for the CA)
keytool -delete -alias RapaServer -keystore d2aApplet.keystore ,这条命令将 d2aApplet.keystore 中的 RapaServer 这一条证书删除了。
使用 -keypasswd 参数,如:keytool -keypasswd -alias RapaServer -keystore d2aApplet.keystore,可以以交互的方式修改 d2aApplet.keystore证书库中的条目
为 RapaServer 的证书。
Keytool -keypasswd -alias RapaServer -keypass 654321 -new 123456 -storepass 888888 -keystore d2aApplet.keystore这一行命令以非交互式的方式修改库
中别名为 RapaServer 的证书的密码为新密码 654321,行中的 123456 是指该条证书的原密码, 888888 是指证书库的密码。
6. 导出证书到新的TrustStore(信任的证书库)
 keytool -import -alias 别名 -file 文件名 -keystore truststore
7.    查看Keystore文件内容
keytool -list -keystore C:\keystore.jks -storepass password
 -v              显示密钥库中的证书详细信息
cacerts证书文件(The cacerts Certificates File)
CA证书的导入(Importing Certificates)
keytool -import -alias joe -file jcertfile.cer
通常该命令用以导入来自CA中心的证书(Importing a Certificate for the CA)
导入被CA中心授权的证书(Importing the Certificate Reply from the CA)
keytool -import -trustcacerts -file VSMarkJ.cer

证书的导出(Exporting Certificates)
keytool -export -alias jane -file janecertfile.cer



我使用的JDK版本为JDK6,使用的的Tomcat版本为6;配置Tomcat下的HTTPS其实很简单,只需要完成两步工作就可以 了;SSL认证分双向认证和单向认证,如

x:\>keytool -genkey -keyalg RSA -dname "cn=localhost,ou=sango,o=none,l=china,st=beijing,c=cn"
-alias server -keypass password -keystore d:\server.jks -storepass password -validity 3650
X:\>keytool -genkey -keyalg RSA -dname “cn=sango,ou=sango,o=none,l=china,st=beijing,c=cn”
-alias custom -storetype PKCS12 -keypass password -keystore d:\custom.p12
-storepass password -validity 3650  
X:\>keytool -export -alias custom -file d:\custom.cer -keystore  d:\custom.p12 -storepass password -storetype PKCS12 -rfc  
X:\>keytool -import -v -alias custom -file d:\custom.cer -keystore  d:\server.jks -storepass password  
keytool -list -v -keystore d:\server.jks -storepass password  
5、配置tomcat service.xml文件
<Connector port=“8443″ protocol=“HTTP/1.1″ SSLEnabled=“true”  maxThreads=“150″ scheme=“https” secure=“true” 
clientAuth=“true” sslProtocol=“TLS” 
keystoreFile="D:/server.jks" keystorePass="password"
truststoreFile="D:/server.jks" truststorePass="password"  /> 
X:\>keytool -genkey -keyalg RSA -dname “cn=localhost,ou=sango,o=none,l=china,st=beijing,c=cn”
-alias server -keypass password -keystore d:\server.jks -storepass password -validity 3650  
2、由于是单向认证,没有必要生成客户端的证书,直接进入配置tomcat service.xml文件,Xml代码
<Connector port=”8443″ protocol=”HTTP/1.1″ SSLEnabled=”true”
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS”
keystoreFile=”D:/server.jks” keystorePass=”password”/>
clientAuth=”false”表示单向认证,同时去掉服务端的可信任认证,即:truststoreFile=”D:/server.jks” truststorePass=”password”这2个属性 .
2.如果将tomcat的 server.xml 的8443 更改为 443,注意本机的443是否开启。
3.如果你的tomcat 使用了http://localhost:8080,测试网址也是https://localhost:8443
其它:当使用https访问某一域名时,浏览器默认访问服务器的443端口。内部处理后,再转向80处理。所以ssl 全称Security Socket Layer, 加密套接字协议层 名

参考文档:  终极武器—数字证书

Total visitors since Jan 2012

World Visitor Map