Trust afs filters ошибка

Короткий ответ — нет, вы никак не можете это увидеть.

Более длинный ответ:

От: https://nmap.org/book/man-port-scanning-basics.html

«Отфильтрованный Nmap не может определить, открыт ли порт, потому что фильтрация пакетов препятствует тому, чтобы его датчики достигли порта. Фильтрация могла быть от специального устройства брандмауэра, правил маршрутизатора или программного обеспечения брандмауэра на основе хоста. Эти порты расстраивают злоумышленников, потому что они предоставляют так мало Иногда они отвечают сообщениями об ошибках ICMP, такими как код 13 типа 3 (пункт назначения недоступен: связь административно запрещена), но фильтры, которые просто отбрасывают зонды без ответа, встречаются гораздо чаще. Это заставляет Nmap повторить попытку несколько раз на тот случай, если проба была сбрасывается из-за перегрузки сети, а не из-за фильтрации. Это значительно замедляет сканирование «.

Вы можете попытаться обнаружить топологию сети с помощью таких инструментов, как traceroute. Обычно порты фильтруются на самом хосте (то есть на ip-таблицах), на граничном маршрутизаторе целевой сети, на маршрутизаторе ядра целевой сети или на верхней панели коммутатора L3 стойки.

Если вы находитесь в той же подсети, что и целевой хост, то почти наверняка брандмауэр находится на целевой машине.

CS-Cart Forums

Loading

Hi all. Today I will share with you some steps to help you troubleshoot TLS version mismatch that break the trust between Web Application Proxy and AD FS servers.

Note: In this demonstration, I will use AD FS version 2019. It’s possible to have a different event ID if you are running another AD FS version. In case of doubt, use this link to match the correct event ID to your AD FS version: https://adfshelp.microsoft.com/AdfsEventViewer/GetAdfsEventList

If your WAP and AD FS servers cannot establish a TLS communication properly, the trust will break and you might start having problems to authenticate users from the internet. Some errors you might face when trying to reestablish the trust are mentioned below:

Error: The federation server proxy configuration could not be updated with the latest configuration on the federation service.
Event Logs:

AD FS/Admin
Log Name: AD FS/Admin
Source: AD FS
Event ID: 1130
Task Category: None
Level: Error
Keywords: AD FS
Description: There was an error establishing or renewing the proxy trust. Ensure the STS and proxy servers have the same TLS version enabled.

Log Name: AD FS/Admin
Source: AD FS
Event ID: 224
Task Category: None
Level: Error
Keywords: AD FS
Description:
The federation server proxy configuration could not be updated with the latest configuration on the federation service.
Additional Data
Error: Retrieval of proxy configuration data from the Federation Server using trust certificate with thumbprint ‘THUMBPRINT’ failed with status code ‘InternalServerError’.

AD FS Tracing/Debug
Log Name: AD FS Tracing/Debug
Source: AD FS Tracing
Event ID: 996
Task Category: None
Level: Error
Keywords: ADFSDiagnostics
Description:
Data in the original trace event ‘STSErrorTraceEvent’ is logged individually in this event to prevent potential loss of data.
Original Event : STSErrorTraceEvent
Mode details: Data Error: Exception: An error occurred when attempting to establish a trust relationship with the federation service. Error: The underlying connection was closed: An unexpected error occurred on a send. StackTrace: at Microsoft.IdentityServer.Management.Proxy.Providers.ProxyTrustProvider.EstablishTrustWithSts(ICredentials credentials, String thumbprint) at Microsoft.IdentityServer.Deployment.Core.Tasks.ConfigurationTaskBase.Execute(IDeploymentContext context, IProgressReporter progressReporter) Exception: The underlying connection was closed: An unexpected error occurred on a send. StackTrace: at System.Net.HttpWebRequest.GetResponse() at Microsoft.IdentityServer.Management.Proxy.Providers.ProxyTrustProvider.EstablishTrustWithSts(ICredentials credentials, String thumbprint) Exception: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Why TLS handshake?

The Transport Layer Security (TLS) Handshake Protocol is responsible for the authentication and key exchange necessary to establish or resume secure sessions and is used by the Web Application Proxy service to establish secure communication to the federation server before establishing the trust. More information about the TLS handshake, please check this link: https://docs.microsoft.com/en-us/windows/win32/secauthn/tls-handshake-protocol

Investigating TLS version

In order to investigate if the communication between WAP and AD FS servers over TLS is working correctly, follow steps below:

Step 1

  • Install network monitor in the WAP server to collect a network trace while configuring the trust.
  • Use filter TLS to see the TLS handshake between client (WAP) and server (AD FS).
  • Expand TLS parameter and check which TLS version is used by the WAP server to communicate with AD FS server.

Step 2

Run the commands below on AD FS servers to see if the respective TLS version above is enabled.

Example: As TLS 1.0 is used by WAP server in this demonstration, run commands below to check if TLS 1.0 is Enabled in the AD FS server.

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client' | Select Enabled,DisabledByDefault

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server' | Select Enabled,DisabledByDefault

Expected Output:

Cause:
Many customers are considering the option to disable TLS 1.0 and RC4 protocol on AD FS, and replace it with TLS 1.1 or a later version.
You might have more information about this in this document: https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/disable-and-replace-tls-1dot0#summary

Fix:
If TLS 1.0 is disabled in AD FS, guarantee that all WAP and AD FS servers use the latest TLS version following steps below:

Step 1:
Enable TLS 1.2 on WAP servers running commands below:

New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -Force | Out-Null
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'Enabled' -value '1' -PropertyType 'DWord' -Force | Out-Null
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server' -name 'DisabledByDefault' -value 0 -PropertyType 'DWord' -Force | Out-Null
New-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -Force | Out-Null
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'Enabled' -value '1' -PropertyType 'DWord' -Force | Out-Null
New-ItemProperty -path 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client' -name 'DisabledByDefault' -value 0 -PropertyType 'DWord' -Force | Out-Null

Enabling Strong Authentication for .NET applications

The .NET Framework 3.5/4.0/4.5.x applications can switch the default protocol to TLS 1.2 by enabling the SchUseStrongCrypto registry key. This registry key will force .NET applications to use TLS 1.2.

Starting with AD FS on Windows Server versions 2012 R2 and 2016, you need to use the .NET Framework 4.0/4.5.x key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319

For the .NET Framework 4.0/4.5.x use the following command:

New-ItemProperty -path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -name 'SchUseStrongCrypto' -value '1' -PropertyType 'DWord' -Force | Out-Null

Restart all servers that had the TLS registry keys updated to take effect.

Run command Install-WebApplicationProxy again to re-establish the trust between WAP and AD FS:

Check event 245 on AD FS Admin logs on WAP server:

Log Name: AD FS/Admin
Source: AD FS
Event ID: 245
Task Category: None
Level: Information
Keywords: AD FS
Description:
The federation server proxy successfully retrieved and updated its configuration from the Federation Service ‘sts.contoso.com’.

Confirming client TLS version with network trace

With TLS 1.2 configured as the preferred method on WAP servers, we see TLS handshake completed successfully and confirm that WAP is now using TLS 1.2 on Network trace.

Summary

In this article, we covered some steps to troubleshoot errors related to TLS version mismatch when establishing trust between WAP and AD FS.

I hope you have enjoyed reading this article and it helps you when administering your AD FS environment.

Enjoyed the article? Like and share. 🙂

In case you have any suggestion or feedback, please leave a comment.

[ ]’s

Ulysses Neves

nmap -p 7000-7020 10.1.1.1

Will output all the filtered ports

Starting Nmap 6.40 ( http://nmap.org ) at 2015-03-04 12:18 EET
Nmap scan report for 10.1.1.1
Host is up (0.00091s latency).
PORT     STATE    SERVICE
7000/tcp filtered afs3-fileserver
7001/tcp filtered afs3-callback
7002/tcp filtered afs3-prserver
7003/tcp filtered afs3-vlserver
7004/tcp filtered afs3-kaserver
7005/tcp filtered afs3-volser
7006/tcp filtered afs3-errors
7007/tcp filtered afs3-bos
7008/tcp filtered afs3-update
7009/tcp filtered afs3-rmtsys
7010/tcp filtered ups-onlinet
7011/tcp filtered unknown
7012/tcp filtered unknown
7013/tcp filtered unknown
7014/tcp filtered unknown
7015/tcp filtered unknown
7016/tcp filtered unknown
7017/tcp filtered unknown
7018/tcp filtered unknown
7019/tcp filtered unknown
7020/tcp filtered unknown

Nmap done: 1 IP address (1 host up) scanned in 2.78 seconds

Is there a way that I can see what exactly is filtering those ports?

asked Mar 4, 2015 at 10:33

Eduard Florinescu's user avatar

This is what the nmap docs say about the filtered state

filtered
Nmap cannot determine whether the port is open because packet filtering prevents its probes from reaching the port. The filtering could be from a dedicated firewall device, router rules, or host-based firewall software…

The only way to find out what is doing the filtering is to know what ‘machines’ are between you and the remote target.

This can be achieved using a route trace utility, which attempts to determine hosts between you and the target using special TCP packets. In your case the command might look something like:

traceroute 10.1.1.1

Once you know the machines between you and the target, you investigate the configuration of each to find out if it is filtering and if so how.

Community's user avatar

answered Mar 4, 2015 at 10:45

user9517's user avatar

4

Nmap provides several ways to get more information about what is causing the filtering:

  • The --reason option will show the type of response that caused the «filtered» port state. This could be «no-response» or «admin-prohibited» or something else.
  • The TTL of response packets is reported in the XML output as the reason_ttl attribute of the state element for the port. If the TTL for a filtered port is different from (usually greater than) the TTL for open ports, then the difference between the TTLs is the network distance between the target and the filtering device. There are exceptions, such as targets which use different initial TTLs for ICMP vs TCP packets, or a filtering device that falsifies or overwrites TTL information.
  • The --traceroute function will show information about hops along your route, any of which could be filtering your traffic. In some cases, the reverse DNS name for one of the hops will even be something like «firewall1.example.com»
  • The firewalk NSE script will send packets with initial TTLs that will time out at different hops along the route in an attempt to find where the packets are being blocked. This is something like a combination of the previous two techniques, and usually works quite well.

The currently-unreleased development version of Nmap also reports TTL for response packets in the normal text output with the -v --reason options. For now, though, you have to use the XML output to get this information.

EDITED TO ADD: Nmap 6.49BETA1 was the first release to show TTL for response packets in text output with -v --reason or -vv, and was released in June 2015.

answered Mar 4, 2015 at 16:10

bonsaiviking's user avatar

bonsaivikingbonsaiviking

4,43017 silver badges27 bronze badges

2

Short answer — No, there is no way that you can see it.

Longer answer:

From: https://nmap.org/book/man-port-scanning-basics.html

«filtered
Nmap cannot determine whether the port is open because packet filtering prevents its probes from reaching the port. The filtering could be from a dedicated firewall device, router rules, or host-based firewall software. These ports frustrate attackers because they provide so little information. Sometimes they respond with ICMP error messages such as type 3 code 13 (destination unreachable: communication administratively prohibited), but filters that simply drop probes without responding are far more common. This forces Nmap to retry several times just in case the probe was dropped due to network congestion rather than filtering. This slows down the scan dramatically.»

You can try discover network topology with tools like traceroute. Usually ports are filtered on the host it self (i.e. ip tables), target network edge router, target network core router or top of the rack L3 switch.

If you are in the same subnet as target host almost for sure firewall is on target machine.

answered Mar 4, 2015 at 10:50

Maciek Sawicki's user avatar

Maciek SawickiMaciek Sawicki

7901 gold badge8 silver badges21 bronze badges

Try comparing a result of tcptrace to one of the filtered ports with a tcptrace to an open port (or a standard traceroute). If the tcptraces are the same it means that there’s something on the destination machine filtering the ports.

Update:
I meant tcptraceroute, I have it aliased.

answered Mar 4, 2015 at 18:53

Makdaam's user avatar

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Это вопрос, который пытается найти решения для моего конкретного случая использования и документировать то, что я пытался сделать для всех, кто следит за этим процессом.

У нас есть сервер RESTful и приложение iOS. У нас есть собственный центр сертификации, и у сервера есть корневой центр сертификации и самоподписанный сертификат. Мы выполнили этот процесс для создания следующих файлов:

Creating Your Own SSL Certificate Authority (and Dumping Self Signed Certs)

rootCA.pem
rootCA.key
server.crt
server.key

Только серверные сертификаты хранятся на нашем сервере, и как часть процесса SSL открытые ключи отправляются с вызовами API для проверки.

Я следил за этим процессом, чтобы использовать AFNetworking для использования фиксации сертификата, а также для фиксации открытого ключа для проверки наших самоподписанных сертификатов:

http://initwithfunk.com/blog/2014/03/12/afnetworking-ssl-pinning-with-self-signed-certificates/

Мы преобразуем файл .crt в файл .cer(в формате DER) в соответствии с этим руководством:

https://support.ssl.com/Knowledgebase/Article/View/19/0/der-vs-crt-vs-cer-vs-pem-certificates-and-how-to-convert-them

и включите файл .cer(server.cer) в комплекте приложений iOS. Это позволяет нашему приложению делать запросы GET/POST на наш сервер. Однако, поскольку наш серверный сертификат может истекать или переиздаваться, мы хотим вместо этого использовать корневой ЦС, как это сделали люди из этого потока в AFNetworking:

https://github.com/AFNetworking/AFNetworking/issues/1944

В настоящее время мы обновили AFNetworking 2.6.0, поэтому наши сетевые библиотеки должны обязательно включать все обновления, включая те, которые были в этом обсуждении:

https://github.com/AFNetworking/AFNetworking/issues/2744

Код, используемый для создания нашей политики безопасности:

    var manager: AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
    manager.requestSerializer = AFJSONRequestSerializer() // force serializer to use JSON encoding

    let policy: AFSecurityPolicy = AFSecurityPolicy(pinningMode: AFSSLPinningMode.PublicKey)
    var data: [NSData] = [NSData]()
    for name: String in ["rootCA", "server"] {
        let path: String? = NSBundle.mainBundle().pathForResource(name, ofType: "cer")
        let keyData: NSData = NSData(contentsOfFile: path!)!
        data.append(keyData)
    }
    policy.pinnedCertificates = data
    policy.allowInvalidCertificates = true 
    policy.validatesDomainName = false 
    manager.securityPolicy = policy

С включенным server.cer мы можем доверять нашему серверу, привязывая открытый ключ (также пытаемся использовать AFSecurityPolicyPinningMode.Certificate); это сработало, потому что точный сертификат включен. Однако, поскольку мы можем изменить файл server.crt, который имеет сервер, поэтому мы хотим иметь возможность сделать это с помощью только rootCA.cer.

Однако, только с rootCA, включенным в комплект приложения, это, похоже, не работает. Разве что у rootCA недостаточно информации о публичном ключе для проверки сертификата сервера, который был подписан с корневым центром сертификации? Файл server.crt также может иметь изменение CommonName.

Кроме того, поскольку моя беглость в терминологии SSL довольно грубая, если кто-нибудь может уточнить, задаю ли я правильные вопросы, это было бы здорово. Конкретные вопросы:

  • Правильно ли я создаю сертификаты, чтобы сервер мог подтвердить свою личность с помощью самоподписанного файла server.crt?
  • Можно ли включить в комплект только файл rootCA.cer и проверить ли серверный сертификат server.crt? Будет ли он проверять другой файл server2.crt, подписанный тем же корневым центром? Или мы должны включать промежуточный сертификат между rootCA и листом?
  • Является ли публичный ключ закреплением или сертификатом для правильного решения? Каждый форум и запись в блоге, которые я читал, говорят «да», но даже с самой обновленной библиотекой AFNetworking нам не повезло.
  • Нужно ли серверу каким-либо образом отправлять как серверные, так и сигнатуры roomCA.pem?

4b9b3361

Ответ 1

С помощью множества различных ресурсов SSL я нашел решение, позволяющее использовать самоподписанные сертификаты для проверки закрытого SSL-сервера. Я также получил гораздо лучшее представление о SSL, существующих решениях iOS и о незначительных проблемах с каждым, что заставило его не работать в моей системе. Я попытаюсь описать все ресурсы, которые вошли в мое решение, и какие мелочи сделали разницу.

Мы по-прежнему используем AFNetworking, и в настоящее время это 2.6.0, который предположительно включает в себя сертификацию. Это и есть корень нашей проблемы; мы не смогли проверить личность нашего частного сервера, который отправлял листовой сертификат, подписанный самозаписываемым корнем CA. В нашем приложении iOS мы объединяем самоподписанный корневой сертификат, который затем устанавливается как доверенный якорь AFNetworking. Однако, поскольку сервер является локальным сервером (аппаратное обеспечение, входящее в состав нашего продукта), IP-адрес является динамическим, поэтому проверка сертификата AFNetworking терпит неудачу, потому что мы не смогли отключить проверку IP.

Чтобы добраться до корня ответа, мы используем AFHTTPSessionManager, чтобы реализовать пользовательский sessionDidReceiveAuthenticationChallengeCallback. (Смотрите: https://gist.github.com/r00m/e450b8b391a4bf312966). В этом обратном вызове мы проверяем сертификат сервера с помощью SecPolicy, который не проверяет имя хоста; см. http://blog.roderickmann.org/2013/05/validating-a-self-signed-ssl-certificate-in-ios-and-os-x-against-a-changing-host-name/, которая является более старой версией для NSURLConnection, а не NSURLSession.

Код:

Создание AFHTTPSessionManager

    var manager: AFHTTPSessionManager = AFHTTPSessionManager()
    manager.requestSerializer = AFJSONRequestSerializer() // force serializer to use JSON encoding
    manager.setSessionDidReceiveAuthenticationChallengeBlock { (session, challenge, credential) -> NSURLSessionAuthChallengeDisposition in

        if self.shouldTrustProtectionSpace(challenge, credential: credential) {
            // shouldTrustProtectionSpace will evaluate the challenge using bundled certificates, and set a value into credential if it succeeds
            return NSURLSessionAuthChallengeDisposition.UseCredential
        }
        return NSURLSessionAuthChallengeDisposition.PerformDefaultHandling
    }

Выполнение пользовательской проверки

class func shouldTrustProtectionSpace(challenge: NSURLAuthenticationChallenge, var credential: AutoreleasingUnsafeMutablePointer<NSURLCredential?>) -> Bool {
    // note: credential is a reference; any created credential should be sent back using credential.memory

    let protectionSpace: NSURLProtectionSpace = challenge.protectionSpace
    var trust: SecTrustRef = protectionSpace.serverTrust!

    // load the root CA bundled with the app
    let certPath: String? = NSBundle.mainBundle().pathForResource("rootCA", ofType: "cer")
    if certPath == nil {
        println("Certificate does not exist!")
        return false
    }

    let certData: NSData = NSData(contentsOfFile: certPath!)!
    let cert: SecCertificateRef? = SecCertificateCreateWithData(kCFAllocatorDefault, certData).takeUnretainedValue()

    if cert == nil {
        println("Certificate data could not be loaded. DER format?")
        return false
    }

    // create a policy that ignores hostname
    let domain: CFString? = nil
    let policy:SecPolicy = SecPolicyCreateSSL(1, domain).takeRetainedValue() 

    // takes all certificates from existing trust
    let numCerts = SecTrustGetCertificateCount(trust)
    var certs: [SecCertificateRef] = [SecCertificateRef]()
    for var i = 0; i < numCerts; i++ {
        let c: SecCertificateRef? = SecTrustGetCertificateAtIndex(trust, i).takeUnretainedValue()
        certs.append(c!)
    }

    // and adds them to the new policy
    var newTrust: Unmanaged<SecTrust>? = nil
    var err: OSStatus = SecTrustCreateWithCertificates(certs, policy, &newTrust)
    if err != noErr {
        println("Could not create trust")
    }
    trust = newTrust!.takeUnretainedValue() // replace old trust

    // set root cert
    let rootCerts: [AnyObject] = [cert!]
    err = SecTrustSetAnchorCertificates(trust, rootCerts)

    // evaluate the certificate and product a trustResult
    var trustResult: SecTrustResultType = SecTrustResultType()
    SecTrustEvaluate(trust, &trustResult)

    if Int(trustResult) == Int(kSecTrustResultProceed) || Int(trustResult) == Int(kSecTrustResultUnspecified) {
        // create the credential to be used
        credential.memory = NSURLCredential(trust: trust)
        return true
    }
    return false
}

Несколько вещей, которые я узнал о быстром просмотре этого кода.

  • Реализация AFNetworking для setSessionDidReceiveAuthenticationChallengeBlock имеет следующую подпись:

    • (void) setSessionDidReceiveAuthenticationChallengeBlock: (nullable NSURLSessionAuthChallengeDisposition (^) (NSURLSession * session, NSURLAuthenticationChallenge * challenge, NSURLCredential * __nullable __autoreleasing * __nullable credential)) block;

Параметр учетных данных является переменной reference/inout, которая должна быть назначена. Быстро это выглядит так: AutoreleasingUnsafeMutablePointer. Чтобы присвоить ему что-то в C, вы сделали бы что-то вроде этого:

*credential = [[NSURLCredential alloc] initWithTrust...];

В быстром режиме он выглядит так: (от преобразование NSArray в RLMArray с RKValueTransFormer не удается преобразовать outputValue в AutoreleasingUnsafeMutablePointer < AnyObject? > )

credential.memory = NSURLCredential(trust: trust)
  1. SecPolicyCreateSSL, SecCertificateCreateWithData и SecTrustGetCertificateAtIndex возвращают неуправляемые! объектов, вы должны по существу преобразовать их/объединить их с помощью takeRetainedValue() или takeUnretainedValue(). (См. http://nshipster.com/unmanaged/). У нас были проблемы с памятью/сбои, когда мы использовали takeRetainedValue() и вызывали метод более одного раза (произошел сбой в SecDestroy). Прямо сейчас сборка кажется стабильной после того, как мы переключились на использование takeUnretainedValue(), так как после проверки вам не нужны политики сертификатов или ssl.

  2. Кэш сеансов TLS. https://developer.apple.com/library/ios/qa/qa1727/_index.html Это означает, что когда вы получаете успешную проверку на вызов, вы никогда не получите вызов снова. Это может повредить вам голову, когда вы тестируете действительный сертификат, а затем проверяете недействительный сертификат, который затем пропускает все проверки, и вы получаете успешный ответ с сервера. Решение заключается в Product- > Clean в вашем iOS-симуляторе после каждого использования действительного сертификата и прохождения проверки. В противном случае вы можете потратить некоторое время на неправильное мышление, чтобы вы, наконец, получили корневой ЦС для проверки.

Итак, вот просто рабочее решение для проблем, которые у меня были с моими серверами. Я хотел бы опубликовать все здесь, чтобы, надеюсь, помочь кому-то другому, работающему на локальном или dev-сервере, с самоподписанным ЦС и iOS-продуктом, который должен быть включен SSL. Конечно, с ATS в iOS 9 я ожидаю, что вы скоро перейдете в SSL.

В настоящее время этот код имеет некоторые проблемы с управлением памятью и будет обновлен в ближайшем будущем. Кроме того, если кто-либо видит эту реализацию и говорит: «Ах, это так же плохо, как возвращение ИСТИННОГО для недействительных сертификатов», пожалуйста, дайте мне знать! Насколько я могу судить по собственному тестированию, приложение отклоняет неверные сертификаты сервера, не подписанные нашим корневым центром сертификации, и принимает сертификат листа, сгенерированный и подписанный корневым центром сертификации. В комплект приложения входит только корневой ЦС, поэтому сертификат сервера может быть циклически после истечения срока действия, а существующие приложения не будут работать.

Если я копаю в AFNetworking немного больше и выясню от одного до трех линейных решений для всего этого (путем переключения всех этих маленьких флагов, которые они предоставляют), я также опубликую обновление.

Если AlamoFire начинает поддерживать SSL, не стесняйтесь публиковать решение здесь.

Ответ 2

Если вы используете coco pods, тогда подкласс класса AFSecurityPolicy и выполните проверку безопасности в соответствии с ответом на митенерометр fooobar.com/questions/294926/…

Слушайте мой код.

Инициализируйте AFHttpRequestOperationManager во время отправки запроса, как показано ниже.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.securityPolicy = [RootCAAFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager POST:Domain_Name parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation,responseObject);
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"Error  %@",error);
        failure(operation,error);
    }];

RootCAAFSecurityPolicy — это подкласс класса AFSecurityPolicy. См. Ниже для RootCAAFSecurityPolicy.h и .m class
переопределить метод

— (BOOL) evaluateServerTrust: (SecTrustRef) serverTrust forDomain: (NSString *) домен

Класс RootCAAFSecurityPolicy.h

#import <AFNetworking/AFNetworking.h>

@interface RootCAAFSecurityPolicy : AFSecurityPolicy

@end

RootCAAFSecurityPolicy.m класс

Замените RootCA именем вашего файла сертификата

#import "RootCAAFSecurityPolicy.h"

@implementation RootCAAFSecurityPolicy
-(BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain
{
    if(self.SSLPinningMode == AFSSLPinningModeCertificate)
    {
        return [self shouldTrustServerTrust:serverTrust];
    }
    else
    {
        return [super evaluateServerTrust:serverTrust forDomain:domain];
    }
}
- (BOOL)shouldTrustServerTrust:(SecTrustRef)serverTrust
{
    // load up the bundled root CA
    NSString *certPath = [[NSBundle mainBundle] pathForResource:@"RootCA" ofType:@"der"];

    NSAssert(certPath != nil, @"Specified certificate does not exist!");

    NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
    CFDataRef certDataRef = (__bridge_retained CFDataRef)certData;
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);

    NSAssert(cert != NULL, @"Failed to create certificate object. Is the certificate in DER format?");


    // establish a chain of trust anchored on our bundled certificate
    CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)&cert, 1, NULL);
    OSStatus anchorCertificateStatus = SecTrustSetAnchorCertificates(serverTrust, certArrayRef);

    NSAssert(anchorCertificateStatus == errSecSuccess, @"Failed to specify custom anchor certificate");


    // trust also built-in certificates besides the specified CA
    OSStatus trustBuiltinCertificatesStatus = SecTrustSetAnchorCertificatesOnly(serverTrust, false);

    NSAssert(trustBuiltinCertificatesStatus == errSecSuccess, @"Failed to reenable trusting built-in anchor certificates");


    // verify that trust
    SecTrustResultType trustResult;
    OSStatus evalStatus =  SecTrustEvaluate(serverTrust, &trustResult);

    NSAssert(evalStatus == errSecSuccess, @"Failed to evaluate certificate trust");


    // clean up
    CFRelease(certArrayRef);
    CFRelease(cert);
    CFRelease(certDataRef);


    // did our custom trust chain evaluate successfully
    return (trustResult == kSecTrustResultProceed || trustResult == kSecTrustResultUnspecified);
}
@end

Ответ 3

У меня была та же проблема, и я исправил ее, сравнив открытые ключи цепочки в методе didReceiveChallenge объекта AFURLSessionManager.

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
        // Get remote certificate
        SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;

        NSMutableArray *policies = [NSMutableArray array];
        [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef) challenge.protectionSpace.host)];

        SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
        NSUInteger trustedPublicKeyCount = 0;
        NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);

        for (id trustChainPublicKey in publicKeys) {
            for (id pinnedPublicKey in self.pinnedPublicKeys) {
                if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) {
                    trustedPublicKeyCount += 1;
                }
            }
        }

        // The pinnning check
        if (trustedPublicKeyCount > 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, NULL);
        }
    }

Вот инициализация pinnedPublicKeys:

    // Get local certificates
    NSArray *certNames = @[@"root_cert"];
    self.pinnedPublicKeys = [NSMutableSet new];

    for (NSString *certName in certNames) {
        NSString *path = [bundle pathForResource:certName ofType:@"der"];
        NSData *certificate = [NSData dataWithContentsOfFile:path];

        id publicKey = AFPublicKeyForCertificate(certificate);
        if (publicKey) {
            [self.pinnedPublicKeys addObject:publicKey];
        }
    }

Вот вспомогательные методы для получения цепочки доверия ключей (AFPublicKeyTrustChainForServerTrust), сравнение открытых ключей (AFSecKeyIsEqualToKey) и Метод получения открытого ключа из сертификата (AFPublicKeyTrustChainForServerTrust):

static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
    NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
    for (CFIndex i = 0; i < certificateCount; i++) {
        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);

        SecCertificateRef someCertificates[] = {certificate};
        CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);

        SecTrustRef trust;
        SecTrustCreateWithCertificates(certificates, policy, &trust);

        SecTrustResultType result;
        SecTrustEvaluate(trust, &result);

        [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];

        if (trust) {
            CFRelease(trust);
        }

        if (certificates) {
            CFRelease(certificates);
        }

        continue;
    }
    CFRelease(policy);

    return [NSArray arrayWithArray:trustChain];
}

static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
    return [(__bridge id)key1 isEqual:(__bridge id)key2];
}

static id AFPublicKeyForCertificate(NSData *certificate) {
    id allowedPublicKey = nil;
    SecCertificateRef allowedCertificate;
    SecCertificateRef allowedCertificates[1];
    CFArrayRef tempCertificates = nil;
    SecPolicyRef policy = nil;
    SecTrustRef allowedTrust = nil;
    SecTrustResultType result;

    allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);

    allowedCertificates[0] = allowedCertificate;
    tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);

    policy = SecPolicyCreateBasicX509();
    SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust);
    SecTrustEvaluate(allowedTrust, &result);

    allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust);

    if (allowedTrust) {
        CFRelease(allowedTrust);
    }

    if (policy) {
        CFRelease(policy);
    }

    if (tempCertificates) {
        CFRelease(tempCertificates);
    }

    if (allowedCertificate) {
        CFRelease(allowedCertificate);
    }

    return allowedPublicKey;
}

Понравилась статья? Поделить с друзьями:
  • Tube plugged ошибка кофемашина что делать
  • Tsd 500mini ошибка h
  • Tu quoque логическая ошибка
  • Truma combi коды ошибок
  • Tsc me240 нет риббона ошибка