软件安全不是安全软件。此处我们关注的主题包括身份验证、Access Control、机密性、加密和权限管理。
URL url = new URL("https://myserver.org");
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
URLConnection
所使用的基础 SSLSocketFactory
未更改,它将使用信任 Android 默认密钥库中存在的所有 CA 的默认项。
val url = URL("https://myserver.org")
val data = url.readBytes()
URLConnection
所使用的基础 SSLSocketFactory
未更改,它将使用信任 Android 默认密钥库中存在的所有 CA 的默认项。
NSString* requestString = @"https://myserver.org";
NSURL* requestUrl = [NSURL URLWithString:requestString];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0f];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLConnectionDelegate
方法来处理证书验证,它将使用信任 iOS 默认密钥库中存在的所有 CA 的系统方法。
let requestString = NSURL(string: "https://myserver.org")
let requestUrl : NSURL = NSURL(string:requestString)!;
let request : NSURLRequest = NSURLRequest(URL:requestUrl);
let connection : NSURLConnection = NSURLConnection(request:request, delegate:self)!;
NSURLConnectionDelegate
方法来处理证书验证,它将使用信任 iOS 默认密钥库中存在的所有 CA 的系统方法。
...
private bool CertificateCheck(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
...
return true;
}
...
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create("https://www.myTrustedSite.com");
webRequest.ServerCertificateValidationCallback = CertificateCheck;
WebResponse response = webRequest.GetResponse();
...
...
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback);
...
...
config := &tls.Config{
// Set InsecureSkipVerify to skip the default validation
InsecureSkipVerify: true,
...
}
conn, err := tls.Dial("tcp", "example.com:443", conf)
..
...
Email email = new SimpleEmail();
email.setHostName("smtp.servermail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setSSLOnConnect(true);
email.setFrom("user@gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("foo@bar.com");
email.send();
...
smtp.mailserver.com:465
时,此应用程序会随时接受颁发给“hackedserver.com
”的证书。此时,当服务器被黑客攻击发生 SSL 连接中断时,应用程序可能会泄漏用户敏感信息。
...
var options = {
key : fs.readFileSync('my-server-key.pem'),
cert : fs.readFileSync('server-cert.pem'),
requestCert: true,
...
}
https.createServer(options);
...
https.Server
对象时,requestCert
设置会指定为 true
,但未设置 rejectUnauthorized
,其默认设置为 false
。这意味着尽管服务器是为了通过 SSL 验证客户端而创建,但即使未使用提供的 CA 列表对证书进行授权,也仍然会接受连接。
var tls = require('tls');
...
tls.connect({
host: 'https://www.hackersite.com',
port: '443',
...
rejectUnauthorized: false,
...
});
rejectUnauthorized
设置为 false,这意味着将接受未经授权的证书,并且仍然会与无法识别的服务器建立安全连接。此时,当服务器被黑客攻击发生 SSL 连接中断时,应用程序可能会泄漏用户敏感信息。NSURLConnectionDelegate
配置为接受任意 HTTPS 证书:
implementation NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
return YES;
}
@end
Example 1
中的 NSURLRequest
实现方式连接到受 SSL 保护的服务器时,如果所请求服务器的证书为自签名证书(进而未经验证),则不会出现警告或错误。因此,应用程序现在可能会通过断开的 SSL 连接泄漏敏感的用户信息。
...
import ssl
ssl_sock = ssl.wrap_socket(s)
...
require 'openssl'
...
ctx = OpenSSL::SSL::SSLContext.new
ctx.verify_mode=OpenSSL::SSL::VERIFY_NONE
...
NSURLConnectionDelegate
配置为接受任意 HTTPS 证书:
class Delegate: NSObject, NSURLConnectionDelegate {
...
func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool {
return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust
}
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
challenge.sender?.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
challenge.sender?.continueWithoutCredentialForAuthenticationChallenge(challenge)
}
}
Example 1
中的 NSURLConnectionDelegate
实现方式连接到受 SSL 保护的服务器时,如果所请求服务器的证书为自签名证书(进而未经验证),则不会出现警告或错误。因此,应用程序现在可能会通过断开的 SSL 连接泄漏敏感的用户信息。NSURLSession
类中,SSL/TLS 链验证由您的应用程序的身份验证代理方法进行处理,但是您的应用程序并未向服务器提供用于验证用户或应用程序的凭据,而是检查服务器在 SSL/TLS 握手期间提供的凭据,然后告诉 URL 加载系统是应接受还是应拒绝这些凭据。以下代码显示的 NSURLSessionDelgate
直接将接收到的质询中的 proposedCredential
作为会话凭据传回,从而成功绕过了服务器验证:
class MySessionDelegate : NSObject, NSURLSessionDelegate {
...
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
...
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, challenge.proposedCredential)
...
}
...
}
...
FINAL(client) = cl_apc_tcp_client_manager=>create(
i_host = ip_adress
i_port = port
i_frame = VALUE apc_tcp_frame(
frame_type =
if_apc_tcp_frame_types=>co_frame_type_terminator
terminator =
terminator )
i_event_handler = event_handler ).
...
client
对象和远程服务器之间的通信很容易受到攻击,因为它是通过未加密和未经身份验证的通道传输的。
...
HttpRequest req = new HttpRequest();
req.setEndpoint('http://example.com');
HTTPResponse res = new Http().send(req);
...
HttpResponse
对象 res
通过未加密和未经验证的通道传输,因而可能受到危害。
var account = new CloudStorageAccount(storageCredentials, false);
...
String url = 'http://10.0.2.2:11005/v1/key';
Response response = await get(url, headers: headers);
...
response
通过未加密和未经验证的通道传输,因而可能受到危害。
helloHandler := func(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "Hello, world!\n")
}
http.HandleFunc("/hello", helloHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
...
}
instream
通过未加密和未验证的通道传输,因而可能受到危害。
var http = require('http');
...
http.request(options, function(res){
...
});
...
http.IncomingMessage
对象 res
通过未加密和未经验证的通道传输,因而可能存在安全隐患。
NSString * const USER_URL = @"http://localhost:8080/igoat/user";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:USER_URL]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
...
stream_socket_enable_crypto($fp, false);
...
require 'net/http'
conn = Net::HTTP.new(URI("http://www.website.com/"))
in = conn.get('/index.html')
...
in
通过未加密和未验证的通道传输,因而可能受到危害。
val url = Uri.from(scheme = "http", host = "192.0.2.16", port = 80, path = "/")
val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = url))
responseFuture
通过未加密和未经验证的通道传输,因而可能受到危害。
let USER_URL = "http://localhost:8080/igoat/user"
let request : NSMutableURLRequest = NSMutableURLRequest(URL:NSURL(string:USER_URL))
let conn : NSURLConnection = NSURLConnection(request:request, delegate:self)
Config.PreferServerCipherSuites
字段控制服务器是使用客户端还是服务器的首选密码套件。如果所选密码套件存在已知缺陷,则使用客户端首选密码套件可能会引入安全漏洞。PreferServerCipherSuites
字段设置为 false
。
conf := &tls.Config{
PreferServerCipherSuites: false,
}
client = SSHClient()
algorithms_to_disable = { "ciphers": untrusted_user_input }
client.connect(host, port, "user", "password", disabled_algorithms=algorithms_to_disable)
SSHClient.connect(...)
使用较弱的算法 3DES-CBC。
...
Using(SqlConnection DBconn = new SqlConnection("Data Source=210.10.20.10,1433; Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;"))
{
...
}
...
...
insecure_config = {
'user': username,
'password': retrievedPassword,
'host': databaseHost,
'port': "3306",
'ssl_disabled': True
}
mysql.connector.connect(**insecure_config)
...
NSURLSession
、NSURLConnection
或 CFURL
时默认启用 App Transport Security (ATS),强制应用程序使用 HTTPS
和 TLS 1.2
开展与后端服务器的所有网络通信。Info.plist
中的以下条目将完全禁用 App Transport Security:示例 2:应用程序
<key>NSAppTransportSecurity</key>
<dict>
<!--Include to allow all connections (DANGER)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Info.plist
中的以下条目将为 yourserver.com
禁用 App Transport Security:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourserver.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Allow plain HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Downgrades TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
<a href="http://www.example.com/index.html"/>
www.example.com
来加载自己的网页。
...
using var channel = GrpcChannel.ForAddress("https://grpcserver.com", new GrpcChannelOptions {
Credentials = ChannelCredentials.Insecure
});
...
...
ManagedChannel channel = Grpc.newChannelBuilder("hostname", InsecureChannelCredentials.create()).build();
...
None
。使用不安全的通道凭据设置发送的数据不受信任。root_certificates
参数的值将被设置为 None
,private_key
参数的值将被设置为 None
,certificate_chain
参数的值将被设置为 None
。
...
channel_creds = grpc.ssl_channel_credentials()
...
...
Server server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create())
...
None
或 False
。通过具有不安全的服务器凭据设置的服务器发送和接收的数据不受信任。
...
pk_cert_chain = your_organization.securelyGetPrivateKeyCertificateChainPairs()
server_creds = grpc.ssl_server_credentials(pk_cert_chain)
...
HSTS
) 标头,但未能将此保护应用于子域,从而使攻击者能够通过执行 HTTPS Stripping 攻击从子域连接窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头所指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 连接。
<http auto-config="true">
...
<headers>
...
<hsts include-sub-domains="false" />
</headers>
</http>
HSTS
) 头文件,但未能将此保护应用于子域,从而使攻击者能够通过执行 HTTPS stripping 攻击从子域连接窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头自身指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 版本。HSTS
) 标头。这样会让攻击者能够用普通 HTTP 连接替换 SSL/TLS 连接,并通过执行 HTTPS Stripping 攻击来窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头所指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 连接。
<http auto-config="true">
...
<headers>
...
<hsts disabled="true" />
</headers>
</http>
HSTS
) 标头,这使得攻击者能够将 SSL/TLS 连接替换为普通 HTTP 连接,并通过执行 HTTPS Stripping 攻击来窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头自身指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 版本。HSTS
) 头文件,这使得攻击者能够通过执行 HTTPS stripping 攻击使用普通 HTTP 连接替换 SSL/TLS 连接并窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头自身指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 版本。modp2
组初始化 Diffie-Hellman 密钥交换协议(该协议使用 1024 位素数):
const dh = getDiffieHellman('modp2');
dh.generateKeys();
...
HSTS
) 标头。这样会让攻击者能够用普通 HTTP 连接替换 HTTPS 连接,并通过执行 HTTPS Stripping 攻击来窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头所指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 连接。
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
...
http.headers(headers ->
headers.httpStrictTransportSecurity(hstsConfig ->
hstsConfig.maxAgeInSeconds(300)
)
);
...
}
HSTS
) 头文件,这使得攻击者能够通过执行 HTTPS stripping 攻击使用普通 HTTP 连接替换 HTTPS 连接并窃取敏感信息。HSTS
) 是一种安全标头,它指示浏览器在标头自身指定的期间始终连接到通过 SSL/TLS 返回 HSTS 标头的站点。即使用户在浏览器 URL 栏中输入了 http://
,通过 HTTP 到服务器的连接还是将自动替换为 HTTPS 版本。SmtpClient
的配置不正确,未使用 SSL/TLS 与 SMTP 服务器进行通信:
string to = "bob@acme.com";
string from = "alice@acme.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "SMTP client.";
message.Body = @"You can send an email message from an application very easily.";
SmtpClient client = new SmtpClient("smtp.acme.com");
client.UseDefaultCredentials = true;
client.Send(message);
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.acme.com" />
<property name="port" value="25" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
session = smtplib.SMTP(smtp_server, smtp_port)
session.ehlo()
session.login(username, password)
session.sendmail(frm, to, content)
device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
...
var options = {
port: 443,
path: '/',
key : fs.readFileSync('my-server-key.pem'),
cert : fs.readFileSync('server-cert.pem'),
...
}
https.createServer(options);
...
secureProtocol
的默认值设置为 SSLv23_method
,因此,在未专门覆盖 secureProtocol
时,服务器本身就并不安全。
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
[configuration setTLSMinimumSupportedProtocol = kSSLProtocol3];
NSURLSession *mySession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:operationQueue];
let configuration : NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let mySession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)
...
encryptionKey = "".
...
...
var encryptionKey:String = "";
var key:ByteArray = Hex.toArray(Hex.fromString(encryptionKey));
...
var aes.ICipher = Crypto.getCipher("aes-cbc", key, padding);
...
...
char encryptionKey[] = "";
...
...
<cfset encryptionKey = "" />
<cfset encryptedMsg = encrypt(msg, encryptionKey, 'AES', 'Hex') />
...
...
key := []byte("");
block, err := aes.NewCipher(key)
...
...
private static String encryptionKey = "";
byte[] keyBytes = encryptionKey.getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher encryptCipher = Cipher.getInstance("AES");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
...
...
var crypto = require('crypto');
var encryptionKey = "";
var algorithm = 'aes-256-ctr';
var cipher = crypto.createCipher(algorithm, encryptionKey);
...
...
CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
"",
0,
iv,
plaintext,
sizeof(plaintext),
ciphertext,
sizeof(ciphertext),
&numBytesEncrypted);
...
...
$encryption_key = '';
$filter = new Zend_Filter_Encrypt($encryption_key);
$filter->setVector('myIV');
$encrypted = $filter->filter('text_to_be_encrypted');
print $encrypted;
...
...
from Crypto.Ciphers import AES
cipher = AES.new("", AES.MODE_CFB, iv)
msg = iv + cipher.encrypt(b'Attack at dawn')
...
require 'openssl'
...
dk = OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, 100000, 0) # returns an empty string
...
...
CCCrypt(UInt32(kCCEncrypt),
UInt32(kCCAlgorithmAES128),
UInt32(kCCOptionPKCS7Padding),
"",
0,
iv,
plaintext,
plaintext.length,
ciphertext.mutableBytes,
ciphertext.length,
&numBytesEncrypted)
...
...
Dim encryptionKey As String
Set encryptionKey = ""
Dim AES As New System.Security.Cryptography.RijndaelManaged
On Error GoTo ErrorHandler
AES.Key = System.Text.Encoding.ASCII.GetBytes(encryptionKey)
...
Exit Sub
...