- Authentication (BITS)
- Using implicit credentials
- Using certificates for client/server authentication
- How to handle authenticated proxy scenarios that require user-specific settings
- BITS что это за служба в Windows?
- BITS Administration Utility (bitsadmin.exe)
- Вирус может использовать BITS
- Issues with BITS
- Finding BITS
- Stopping and restarting BITS
- Troubleshooting BITS download issues
- The BITS service must run under the Local System user account
- Proxy servers must support HTTP 1.1 RANGE requests
- There is a mismatch between the BITS per-user job limit and the per-computer job limit
- BITS jobs are failing
- Repairing a corrupted BITS configuration
Authentication (BITS)
BITS supports Basic authentication, Passport authentication, and several challenge/response authentication schemes. If the server or proxy requires user authentication, use the IBackgroundCopyJob2::SetCredentials function to specify the user’s credentials. BITS uses the CryptoAPI to protect the credentials.
To set credentials for Basic authentication use the SetCredentials function to specify the user name and password. You should only use Basic authentication with https:// protected secure websites; otherwise the username and password will be visible to users.
It’s possible to embed the user name and password in the URL. This is not considered a good security practice, and is deprecated in RFC 3986 (section 3.2.1).
For Passport authentication, BITS supports explicit credentials only, not implicit credentials tied to the account.
For challenge/response authentication, BITS impersonates the user and uses Snego to determine which challenge/response authentication to use, such as NTLM or the Kerberos protocol. For a list of challenge/response schemes that BITS supports, see BG_AUTH_SCHEME.
BITS jobs can fail if the virtual directory on the server has anonymous authentication and another authentication scheme enabled and if ACLs protect the virtual directory or download files. For example, a job fails with «access denied» if the virtual directory has anonymous and integrated authentication enabled and the file contains an ACL that allows only Ben to read the file. This occurs because the virtual directory allows anonymous access, so IIS does not explicitly authenticate Ben (Ben’s credentials are not used to access the file and access is denied).
Using implicit credentials
To use the user’s implicit (logon) credentials for NTLM or Kerberos authentication, call the IBackgroundCopyJob2::SetCredentials method and set the UserName and Password members of the BG_BASIC_CREDENTIALS structure to NULL. If you specify implicit credentials for a proxy, BITS will also use the implicit credentials for server authentication unless you specify explicit server credentials.
For additional information for services, see Service Accounts and BITS.
You could also change the LMCompatibilityLevel or UseLMCompat registry value; however, you should change these values only if you have an existing application that cannot be changed to call the SetCredentials method.
BITS will use implicit credentials for authentication if the LMCompatibilityLevel registry value is two or greater, and you have not called the SetCredentials method. The full path to the LMCompatibilityLevel registry value is HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\LmCompatibilityLevel.
Note that changing the LMCompatibilityLevel registry value can affect other applications and services running on the computer. For more information about using the LMCompatibilityLevel registry value, see KB147706.
If setting the LMCompatibilityLevel registry value is an issue, you can create the UseLMCompat registry value under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\BITS. The registry value is a DWORD. The following table lists the possible values for UseLMCompat:
Value | Description |
---|---|
0 | BITS will send implicit credentials whenever the server prompts for NTLM or Kerberos credentials. |
1 | BITS will send implicit credentials only if the client computer’s LMCompatibilityLevel registry value is greater than or equal to 2. |
2 | BITS will send implicit credentials only if the application called the SetCredentials method. |
BITS will use a default value of «2» for the UseLMCompat registry value if the registry value does not exist.
Using certificates for client/server authentication
In secure client/server communication, clients and servers can use digital certificates to mutually authenticate each other. BITS automatically supports certificate-based server authentication for secure HTTP transports. To provide BITS the client certificate needed for mutual authentication, call either the IBackgroundCopyJobHttpOptions::SetClientCertificateByID or IBackgroundCopyJobHttpOptions::SetClientCertificateByName method.
When a website accepts but does not require an SSL client certificate, and the BITS job does not specify a client certificate, the job will fail with ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED (0x80072f0c).
How to handle authenticated proxy scenarios that require user-specific settings
If you are using BITS in an environment that requires proxy authentication while running as an account without usable NTLM or Kerberos credentials in the machine’s network domain, you must take extra steps to authenticate properly by using the credentials of another user account that does have credentials on the domain. This is a typical scenario when your BITS code is running as a system service such as LocalService, NetworkService, or LocalSystem, as those accounts do not have usable NTLM or Kerberos credentials.
The proxy detection logic used in BITS does the following when a network helper token (BG_TOKEN_NETWORK) is set:
- If IBackgroundCopyJob::SetProxySettings was called with BG_JOB_PROXY_USAGE_PRECONFIG, then read local IE proxy settings using job owner token context impersonation via WinHttpGetIEProxyConfigForCurrentUser. Starting in Windows 10, version 1809 (10.0; Build 17763), the helper token identity is used for this step.
- If IBackgroundCopyJob::SetProxySettings was called with BG_PROXY_USAGE_AUTODETECT or if the IE settings from the BG_JOB_PROXY_USAGE_PRECONFIG case specify auto-detect or an auto-config URL, then conduct auto-proxy detection, or Web Proxy Autodiscovery Protocol (WPAD), using helper token impersonation via WinHttpGetProxyForUrl.
After that, helper token impersonation is used for proxy or server authentication throughout.
Starting in Windows 10, version 1809 (10.0; Build 17763), the authenticated proxy scenario with user-specific credentials is simplified.
- Call the BITS job’s SetCredentials method with BG_AUTH_SCHEME_NEGOTIATE, UserName set to NULL, Password set to NULL, and Target set to BG_AUTH_TARGET_PROXY. This causes the user account’s implicit credentials to be used for NTLM and Kerberos authentication with the proxy and server.
- Call IBackgroundCopyJob::SetProxySettings with BG_JOB_PROXY_USAGE_PRECONFIG.
- QueryInterface for IBitsTokenOptions.
- Impersonate the user account you’re using for NTLM/Kerberos credentials.
- Call SetHelperToken.
- Call SetHelperTokenFlags with BG_TOKEN_NETWORK.
- Revert impersonation.
- Continue job setup.
- Call Resume on the job.
Before Windows 10, version 1809 (10.0; Build 17763), the correct user identity (the helper token’s identity) is used for network-based proxy detection (WPAD) and for proxy authentication, but the actual detection of local (IE) proxy settings is always done using the job owner’s token, even when a helper token is configured. To work around this shortcoming, you can follow these steps.
BITS что это за служба в Windows?
BITS — интеллектуальная служба передачи данных между клиентом и HTTP-сервером. При этом при передачи используется интернет, который не используется. Как это? Например у вас интернет-пакет со скоростью 10 мегабит, а вы просто сидите в социальной сети, которая ну никак не может для отправки сообщений использовать все 10 мегабит. И вот то, что не используется — то может взять себе служба BITS для передачи данных) вот как-то так все и работает)
Но где эта служба применяется? Самое главное применение — загрузка обновлений с серверов Microsoft. Обновления могут быть большие и вот чтобы загрузка их не мешала пользователю в плане скорости — то и нужна служба BITS. Вот поэтому то он и интеллектуальная — качает с такой скоростью, чтобы вам не мешать сидеть на сайтах, или например играть в онлайн игру..)
Как я понимаю, основная фишка службы BITS — фоновая загрузка данных, при которой используется не вся скорость интерната, а только неиспользуемая.
Кроме обновлений служба также используется и в антивирусе Microsoft Security Essentials (Windows Defender).
Как я понимаю, эту службу могут использовать и другие программы. Они могут загружать файлы из интернета при помощи этой службы. Для этого программа создает задание, в котором указаны файлы, и потом это задание идет или в очередь или сразу выполняется. В общем это уже больше для разработчиков, вряд ли вам интересно)
Нужно ли отключать службу BITS? Судя по тому где она используется — нет, отключать не стоит, иначе могут быть проблемы со встроенным антивирусом или с обновлениями. Но если вы ни первым ни другим не пользуетесь — то получается отключить можно. Но опять же, а если еще какая-то программа использует эту службу? Нельзя ведь точно знать какие проги используют, а какие нет. Поэтому.. нет, лучше все таки ее не отключать. Тем более что вряд ли она может грузить ПК — разве что совсем немного и только когда идет передача данных.
Чтобы отключить службу или посмотреть, включена она или нет, то нужно открыть окошко свойств — там есть вся необходимая информация. Как это сделать? А вот как — зажимаете Win + R, вставляете эту команду:
Нажимаете ОК и потом в списке служб находите Фоновая интеллектуальная, нажимаете два раза и будет окошко свойств. Там все будет сказано. Чтобы отключить — в Тип запуска выбираете Отключена и нажимаете кнопку Остановить. Но отключать в итоге все таки думаю что не стоит.
Как и многие системные службы, BITS работает под процессом svchost.exe, тут ничего удивительного нет.
Проверка состояния службы BITS
BITS Administration Utility (bitsadmin.exe)
BITS Administration Utility — инструмент управления службой BITS. Возможно что инструмент из себя представляет команду, так как имеет параметры для запуска из командной строки:
Да, bitsadmin.exe — это команда:
Я точно не знаю — но если интересно, то можете попробовать ввести в командную строку:
И в результате может отобразиться справка по этой команде.
Вирус может использовать BITS
Но я нашел еще кое-что интересное. Впрочем ничего странного нет.. в общем вирусы тоже могут использовать службу BITS. На одном сайте читаю, что некий троян в 2016 году использовал функционал службы для загрузки вирусов на ПК. Ну тут просто без комментариев, я то думал что там в Microsoft это учли и сделали так, что загрузка могла бы быть только с безопасных источников. Но как видим — нет.
Сегодня тот вирус уже вряд ли опасен — информация за 2016 год, а сейчас конец 2018, и скорее всего вирус уже внесен в антивирусные базы.
Нашел даже более точную информацию — вирус назывался Zlob.Q и он использовал BITS для связи с командным центром (C&C). И как обнаружили этот вирус? Все очень просто — была подозрительная активность службы BITS, ну и начали копать, и в итоге докопались.
Возможно у вас тоже есть подозрительная активность? В любом случае, при малейшем подозрении — проверьте ПК на вирусы. Чем? Я перечислю две основные утилиты, которыми стоит проверять регулярно ПК:
- Первая утилита от Доктора Веба — Dr.Web CureIt!. Популярная в интернете, многие знают, одна из лучших, если не самая. Умеет чистить ПК от всяких троянов, червей, бэкдоров, находить даже те вирусы, которые используют механизмы скрытия и обусфакции. Кстати обусфакция (может неправильно написал, сори) — это когда вирус постоянно меняет свой код, чтобы его не обнаружили.
- Вторая утилита — AdwCleaner. Это уже немного проще утилита, но также важна и может вам сберечь нервы. Утилита ищет и удаляет не очень серьезные вирусы, но такие коварные.. и тут я имею ввиду — рекламные. Все эти вирусы, которые постоянно пихают вам рекламу, заражают рекламными ссылками ярлыки, автозагрузку, левые расширения ставят. В общем после чистки AdwCleaner комп может спокойно заработать быстрее.
Вот этими двумя утилитами я оч советую проверить ПК при малейшем подозрении на вирус. На этом все — удачи, надеюсь информация помогла.
Issues with BITS
Background Intelligent Transfer Service (BITS) is the service used by WSUS to download updates from Microsoft Update to the main WSUS server, as well as from WSUS servers to their clients. BITS also supports the transfer of files between peer computers in a domain.
Some download issues may be caused by problems with running BITS on the server or client computers. When you are troubleshooting download problems, after you have verified that all WSUS settings are correct on both the server and its clients, you should ensure that BITS is running properly on all affected computers.
BITS provides a downloadable tool called bitsadmin that allows you to verify and change BITS settings. For more information about the bitsadmin utility, see BITSAdmin Tool (https://go.microsoft.com/fwlink/?LinkId=80934). This tool is available as part of the WindowsВ Vista operating system, and also as part of the Windows XP Service PackВ 2 Support Tools.
Finding BITS
To find the BITS service, open a command shell and type:
If BITS is running, you should see output like the following:
If BITS is not running, you should see output like the following:
Stopping and restarting BITS
Often it is possible to resolve BITS issues simply by stopping the service and restarting it. The following procedure shows how to stop and restart the service from the command line. You must be logged on as a local administrator to stop and restart BITS.
To modify, stop, or restart BITS, you must be logged on as an administrator.
To stop and restart BITS
Open a command shell.
Type sc stop bits
Type sc start bits
Troubleshooting BITS download issues
The following sections are an incomplete list of possible problems with BITS configuration. To get more information about BITS, see Background Intelligent Transfer Service (https://go.microsoft.com/fwlink/?LinkId=81083).
The BITS service must run under the Local System user account
By default BITS runs under the LocalSystem account.
To configure the service to run under the correct account
Open a command shell.
Type: sc config bits obj= LocalSystem
(note that a space must occur between obj= and LocalSystem )
Verify that output from the command is:
[SC] ChangeServiceConfig SUCCESS
Stop and restart BITS.
Proxy servers must support HTTP 1.1 RANGE requests
- BITS supports HTTP and HTTPS downloads and uploads and requires that the server support the HTTP 1.1 protocol. For downloads, the HTTP server’s HEAD method must return the file size, and its GET method must support the Content-Range and Content-Length headers. BITS can use an HTTP/1.0 server as long as it meets the HEAD and GET method requirements (MIME headers must include the standard Content-Range and Content-Type headers plus a maximum of 180 bytes of other headers, and a maximum of two CR/LF characters may occur between the HTTP headers and the first boundary string).
There is a mismatch between the BITS per-user job limit and the per-computer job limit
To detect or correct a mismatch between the per-user job limit and the per-computer job limit specified through Group Policy
Run gpedit.msc, if the policy is specified locally; if the policy is a domain policy edit the Group Policy object with GPMC.
In the Group Policy Object Editor, navigate to Computer Configuration\Administrative Templates\Network\Background Intelligent Transfer Service (BITS).
Ensure that the setting «Maximum number of BITS jobs for each user» is set to a lower value than the setting «Maximum number of BITS jobs for this computer»
Type gpupdate /force
Stop and restart BITS.
Verify that there are no errors in the event logs.
BITS jobs are failing
If BITS jobs fail, look in the event log to find errors. You can use the following table to diagnose the cause of the errors.
Error name | Error code | Description |
---|---|---|
E_INVALIDARG | 0x80070057 | An incorrect proxy server name was specified in the user’s Internet Explorer proxy settings. This error is also seen when credentials are supplied for authentication schemes that are not NTLM/Negotiate, but the user name or password is null. Change the user’s IE settings to be a valid proxy server or Change the credentials not to be NULL user name/password for schemes other than NTLM/Negotiate. |
ERROR_WINHTTP_NAME_NOT_RESOLVED | 0x80072ee7 | The server/proxy could not be resolved by BITS. Internet Explorer on the same machine in the context of the job owner would see the same problem. Try downloading the same file via the web browser using the context of the job owner. |
ERROR_HTTP_INVALID_SERVER_RESPONSE | 0x80072f78 | This is a transient error and the job will continue downloading. |
BG_E_INSUFFICIENT_RANGE_SUPPORT | 0x80200013 | BITS uses range headers in HTTP requests to request parts of a file. If the server or proxy server doesn’t understand Range requests and returns the full file instead of the requested range, BITS puts the job into the ERROR state with this error. Capture the network traffic during the error and examine if HTTP GET requests with “Range” header are getting valid responses. Check proxy servers to ensure that they are configured correctly to support Range requests. |
BG_E_MISSING_FILE_SIZE | 0x80200011 | When BITS sends a HEAD request and the server/proxy does not return Content-Length header in the response, BITS puts the job in ERROR state with this error. Check the proxy server and WSUS server to ensure that they are configured correctly. Some versions of the Apache 2.0 proxy server are known to exhibit this behavior. |
BG_E_HTTP_ERROR_403 | 0x80190193 | When the server returns HTTP 403 response in any of the requests, BITS puts the job in ERROR state with this error code. HTTP 403 corresponds to “Forbidden: Access is denied.» Check access permissions for the account running the job. |
ERROR_NOT_LOGGED_ON | 0x800704dd | The SENS service is not receiving user logon notifications. BITS (version 2.0 and up) depends on logon notifications from Service Control Manager, which in turn depends on the SENS service. Ensure that the SENS service is started and running correctly. |
#### BITS fails to start If the BITS service fail to start, use the following table to diagnose the cause of the error.
ERROR_SERVICE_DOES_NOT_EXIST | 0x80070424 | See the section on repairing the BITS configuration below. |
ERROR_SERVICE_NOT_IN_EXE | 0x8007043B | BITS is not listed as one of the services in the netsvcs svchost group (does not apply to WindowsВ 2000). |
ERROR_SERVICE_DISABLED | 0x80070422 | BITS has been disabled. Enable the BITS service. |
ERROR_SERVICE_DEPENDENCY_DELETED ERROR_SERVICE_DEPENDENCY_FAIL | 0x80070433, 0x8007042c | A service appearing in the BITS service dependency list cannot be started. Make sure the dependency list for the BITS service is correct:
Windows ServerВ 2003: Rpcss, EventSystem WindowsВ XP: Rpcss WindowsВ 2000: Rpcss, SENS, Wmi |
ERROR_PATH_NOT_FOUND | 0x80070003 | Pre-Windows Vista: %ALLUSERSPROFILE%\Microsoft\Network doesn’t exist |
ERROR_FILE_NOT_FOUND | 0x80070002 | The “Parameters” key is missing. Ensure that the following keys and values exist: HKLM\SYSTEM\CurrentControlSet\Services\BITS\Parameters\ServiceDll= %SystemRoot%\System32\qmgr.dll |
REGDB_E_CLASSNOTREG, EVENT_E_INTERNALERROR | 0x80040154, 0x80040206 | BITS for WindowsВ 2000 is dependent on SENS and EventSystem services. If the COM+ catalog is corrupted, BITS may fail with this error code. See KB article Q315296 for details. |
Repairing a corrupted BITS configuration
To repair corrupted BITS service configuration, you can enter the BITS service configuration manually.
This action should only be taken in circumstances where all other troubleshooting attempts have failed. You must be an administrator to modify the BITS configuration.
To repair a corrupted BITS configuration
Open a command shell.
Sc config bits binpath=”%systemroot%\system32\svchost.exe –k netsvcs“ Sc config bits depend = RpcSs EventSystem
Sc config bits start=delayed-auto
Sc config bits type=interact
Sc config bits error=normal
Sc config bits obj=LocalSystem
Sc privs bits privileges=SeCreateGlobalPrivilege/SeImpersonatePrivilege/SeTcbPrivilege/SeAssignPrimaryTokenPrivilege/SeIncreateQuotaPrivilege
Sc sidtype bits type= unrestricted
Sc failure bits reset= 86400 actions=restart/60000/restart/120000