CWE-939 Base Incompleto

Improper Authorization in Handler for Custom URL Scheme

This vulnerability occurs when an app implements a custom URL scheme handler but fails to properly verify which other apps or sources are allowed to trigger it.

Definição

What is CWE-939?

This vulnerability occurs when an app implements a custom URL scheme handler but fails to properly verify which other apps or sources are allowed to trigger it.
Modern mobile and desktop platforms use custom URL schemes (like myapp://) as a bridge for apps to communicate and pass data. However, if the receiving app doesn't enforce strict authorization checks, any malicious or untrusted app on the same device can invoke this handler. This effectively creates an unintended public interface into your app's internal functions. Without proper validation, attackers can exploit this open handler to trigger dangerous actions. For example, a vulnerable handler might allow unauthorized file deletion, data export, or changes to app settings, simply by crafting a malicious URL. The security of the entire mechanism depends entirely on the developer implementing explicit checks to verify the calling source's identity and permissions.
Impacto no mundo real

Real-world CVEs caused by CWE-939

  • URL scheme has action replace which requires no user prompt and allows remote attackers to perform undesired actions.

  • URL scheme has action follow and favorite which allows remote attackers to force user to perform undesired actions.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This iOS application uses a custom URL scheme. The replaceFileText action in the URL scheme allows an external application to interface with the file incomingMessage.txt and replace the contents with the text field of the query string.

  2. 2

    External Application

  3. 3

    Application URL Handler

  4. 4

    The handler has no restriction on who can use its functionality. The handler can be invoked using any method that invokes the URL handler such as the following malicious iframe embedded on a web page opened by Safari.

  5. 5

    The attacker can host a malicious website containing the iframe and trick users into going to the site via a crafted phishing email. Since Safari automatically executes iframes, the user is not prompted when the handler executes the iframe code which automatically invokes the URL handler replacing the bookmarks file with a list of malicious websites. Since replaceFileText is a potentially dangerous action, an action that modifies data, there should be a sanity check before the writeToFile:withText: function.

Exemplo de código vulnerável

Vulnerable Objective-C

Application URL Handler

Vulnerável Objective-C
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  	if (!url) {
  		return NO;
  	}
  	NSString *action = [url host];
  	if([action isEqualToString: @"replaceFileText"]) {
  		NSDictionary *dict = [self parseQueryStringExampleFunction:[url query]];
```
//this function will write contents to a specified file* 
  		FileObject *objectFile = [self writeToFile:[dict objectForKey: @"file"] withText:[dict objectForKey: @"text"]];}
  	return YES;}
Payload do atacante

The handler has no restriction on who can use its functionality. The handler can be invoked using any method that invokes the URL handler such as the following malicious iframe embedded on a web page opened by Safari.

Payload do atacante HTML
<iframe src="appscheme://replaceFileText?file=Bookmarks.dat&text=listOfMaliciousWebsites">
Exemplo de código seguro

Secure Objective-C

External Application

Seguro Objective-C
NSString *stringURL = @"appscheme://replaceFileText?file=incomingMessage.txt&text=hello";
  NSURL *url = [NSURL URLWithString:stringURL];
  [[UIApplication sharedApplication] openURL:url];
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de verificação de prevenção

How to prevent CWE-939

  • Architecture and Design Utilize a user prompt pop-up to authorize potentially harmful actions such as those modifying data or dealing with sensitive information. When designing functionality of actions in the URL scheme, consider whether the action should be accessible to all mobile applications, or if an allowlist of applications to interface with is appropriate.
Sinais de deteção

How to detect CWE-939

SAST High

Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.

DAST Moderate

Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.

Runtime Moderate

Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.

Code review Moderate

Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-939 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o CWE-939?

This vulnerability occurs when an app implements a custom URL scheme handler but fails to properly verify which other apps or sources are allowed to trigger it.

Qual a gravidade do CWE-939?

A MITRE não publicou uma classificação de probabilidade de exploração para esta fraqueza. Trate-a como impacto médio até o seu modelo de ameaças provar o contrário.

Que linguagens ou plataformas são afetadas pelo CWE-939?

MITRE lists the following affected platforms: Mobile.

Como posso prevenir o CWE-939?

Utilize a user prompt pop-up to authorize potentially harmful actions such as those modifying data or dealing with sensitive information. When designing functionality of actions in the URL scheme, consider whether the action should be accessible to all mobile applications, or if an allowlist of applications to interface with is appropriate.

Como é que o Plexicus deteta e corrige o CWE-939?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-939 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-939?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/939.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.