Skip to content

[Revisão] Add --record_fname_encode to record calls whose Call-ID contains '/' - #1

Closed
mdzesseis wants to merge 1 commit into
masterfrom
record-fname-encode
Closed

mdzesseis wants to merge 1 commit into
masterfrom
record-fname-encode

Conversation

@mdzesseis

Copy link
Copy Markdown
Owner

Revisão prévia (interna ao fork). Este PR existe só para recolher comentários antes de abrir o PR oficial em sippy/rtpproxy. Ele não será mesclado aqui.

Comente nas linhas do código (aba Files changed) ou aqui embaixo. O texto abaixo da linha é exatamente o que vai como descrição do PR oficial, então sugestões de redação também são bem-vindas.


Follow-up to sippy#179.

Since 9c50b4e, rtpp_record_ctor() refuses to record (R, Rs, -a) when the Call-ID or from-tag used in the file name contains /. That closes the path traversal, and I agree that C with a name chosen by the client is the right long-term answer.

In the meantime, clients that still send R lose those recordings completely. / is legal in a Call-ID and some carriers use it routinely. Moving the client to C is not always possible soon, because it needs a config change in the proxy and in everything that later finds the recording by name.

This PR adds an opt-in --record_fname_encode option:

Tests: a new recording/basic sub-test, badpath_enc. With the option it records the same traversal Call-IDs as badpath, plus one with %, and checks they are created under their encoded names inside the recording directory and nowhere else. It also checks that an over-long Call-ID is still refused. Against master the new sub-test fails, because the option does not exist there (unrecognized option '--record_fname_encode'), while badpath passes on both. Local results with the project's own docker/Dockerfile.ci + scripts/do-test.sh are in the comment below.

Docs: usage(), doc/manpage.xml and rtpproxy.8.

If you would rather not have a global option for this, I am happy to rework it, for example as an R/Rs command modifier.


Resultados dos testes locais (vão como comentário no PR oficial)

Local test results, reproduced with the project's own CI recipe (docker/Dockerfile.ci, BASE_IMAGE=ubuntu:24.04, then scripts/do-test.sh), on this branch rebased on 0c507007:

master 0c507007 (gcc) this PR (gcc) this PR (clang)
recording/basic · badpath OK OK OK
recording/basic · badpath_enc (new) FAILED: unrecognized option '--record_fname_encode' OK OK
recording/basic · files, singlefile, singlefile_c, stopall, remote, remote_p OK OK OK
recording/basic · files_stophalf, singlefile_stophalf FAILED FAILED files_stophalf FAILED
Rest of the functional suite same set of PASS/FAIL same as master same as master
Compiler warnings in src/rtpp_record.c / src/main.c 12 (pre-existing) same 12, no new ones 0

The failures that also show up on master (*_stophalf, acct_rtcp_hep/basic, startstop/badargs, forwarding/forwarding1, playback/playback1, dtls_gw/*) come from my local Docker environment. They are identical with and without the patch. I'll rely on the GitHub CI run of this PR for those.

@mdzesseis

Copy link
Copy Markdown
Owner Author

Explicação da mudança (para quem vai revisar)

O problema

O rtpproxy grava o áudio de uma chamada em arquivos cujo nome é formado pelo Call-ID e pela from-tag da sessão:

<diretório de gravação>/<Call-ID>=<from-tag>.a.rtp   (e .o.rtp, ou .pcap)

O caractere / é válido num Call-ID SIP, e algumas operadoras o usam com frequência (ex.: ab/cd@host). Como / também é o separador de diretórios, esse Call-ID não serve como nome de arquivo:

O mantenedor recomenda, a longo prazo, que o cliente (OpenSIPS, Kamailio…) escolha o nome do arquivo com o comando C. Enquanto isso não acontece, quem usa o comando R (nome automático) perde essas gravações.

O que este PR faz

Adiciona a opção de linha de comando --record_fname_encode, desligada por padrão.

Sem a opção (padrão) Com --record_fname_encode
Call-ID comum (abc@host) abc@host=tag.a.rtp abc@host=tag.a.rtp (idêntico)
Call-ID com / (ab/cd@host) recusado (como hoje no master) ab%2Fcd@host=tag.a.rtp
Call-ID com % (a%41b) a%41b=tag.a.rtp a%2541b=tag.a.rtp
Call-ID malicioso (../../tmp/x) recusado ..%2F..%2Ftmp%2Fx=tag.a.rtp, dentro do diretório
Call-ID longo demais recusado recusado (mesmo limite PATH_MAX)
Comando C (nome explícito) sem mudança sem mudança

Por que codificar também o %: sem isso, a/b e a%2Fb gerariam o mesmo arquivo. Como o arquivo é aberto com O_TRUNC, uma gravação apagaria a outra. Codificando / → %2F e % → %25, o mapeamento fica reversível: para recuperar o Call-ID original, basta decodificar os %XX.

Onde mexe (7 arquivos)

Arquivo Mudança
src/rtpp_record.c Nova função rtpp_record_fname_cpy(): copia Call-ID e tag para buffers de PATH_MAX, codificando / e % quando a opção está ligada; devolve erro se não couber. A recusa do / continua, como verificação final, depois da cópia. Os snprintf() e as verificações de truncamento do sippy#179 foram mantidos.
src/main.c Registra a opção longa --record_fname_encode e a inclui no usage().
src/rtpp_cfg.h Novo campo record_fname_enc na configuração.
doc/manpage.xml, rtpproxy.8 Documentação da opção.
tests/recording/basic Inclui o subteste novo na lista.
tests/recording/basic.badpath_enc.rptl Subteste novo: com a opção, grava os Call-IDs de path traversal do badpath e um com % com o nome codificado, dentro do diretório de gravação. Confirma também que um Call-ID longo demais continua recusado.

O que vale a pena conferir na revisão

  • Compatibilidade: sem a opção, o comportamento é exatamente o do master. O teste badpath existente passa sem alteração, e só a mensagem de log ganhou a dica (see --record_fname_encode).
  • Segurança: com a opção, o nome nunca contém /, então não há como escapar do diretório. Nomes que começam com . (ex.: ..%2F…) viram arquivos ocultos, mas ficam dentro do diretório.
  • Limites: a cópia codificada usa buffers de PATH_MAX + 1 e devolve erro se não couber, e os snprintf() continuam verificando truncamento.
  • Escopo: é uma opção global. O texto do PR se oferece para transformá-la num modificador do comando R/Rs, caso o mantenedor prefira.
  • Redação do texto do PR e do commit (inglês).

Como testar localmente

Usando a receita de CI do próprio projeto, a partir desta branch:

docker build -f docker/Dockerfile.ci --build-arg BASE_IMAGE=ubuntu:24.04 --build-arg COMPILER=gcc -t rtpproxy-ci:pr .
docker run -d --name rtpp --init --sysctl net.ipv4.ip_unprivileged_port_start=1024 --workdir /opt/rtpproxy/basic rtpproxy-ci:pr
docker exec rtpp sh -c 'groupadd --system rtpproxy; useradd --system --gid rtpproxy --no-create-home rtpproxy; chown -R rtpproxy .; \
  SUB_TESTS="badpath badpath_enc" TEST_WITNESS_ENABLE=yes make -C tests check-TESTS TESTS=recording/basic'

Resultado esperado: badpath e badpath_enc com OK. No master puro, o badpath_enc falha com unrecognized option '--record_fname_encode'.

@mdzesseis

Copy link
Copy Markdown
Owner Author

Resultados dos testes locais

Local test results, reproduced with the project's own CI recipe (docker/Dockerfile.ci, BASE_IMAGE=ubuntu:24.04, then scripts/do-test.sh), on this branch rebased on 0c507007:

master 0c507007 (gcc) this PR (gcc) this PR (clang)
recording/basic · badpath OK OK OK
recording/basic · badpath_enc (new) FAILED: unrecognized option '--record_fname_encode' OK OK
recording/basic · files, singlefile, singlefile_c, stopall, remote, remote_p OK OK OK
recording/basic · files_stophalf, singlefile_stophalf FAILED FAILED files_stophalf FAILED
Rest of the functional suite same set of PASS/FAIL same as master same as master
Compiler warnings in src/rtpp_record.c / src/main.c 12 (pre-existing) same 12, no new ones 0

The failures that also show up on master (*_stophalf, acct_rtcp_hep/basic, startstop/badargs, forwarding/forwarding1, playback/playback1, dtls_gw/*) come from my local Docker environment. They are identical with and without the patch. I'll rely on the GitHub CI run of this PR for those.


Resumo em português: os subtestes de gravação badpath (comportamento atual) e badpath_enc (novo) passam com gcc e clang. No master puro, o badpath_enc falha porque a opção não existe (contraprova). As demais falhas da tabela acontecem igual no master, porque vêm do ambiente Docker local, não do PR. Não há avisos de compilação novos. Este texto vai como comentário no PR oficial.

Since 9c50b4e, rtpp_record_ctor() refuses to record (R, Rs, -a) when
the Call-ID or from-tag used in the file name contains '/', which keeps
recordings inside of the recording directory. '/' is a legal Call-ID
character and some carriers use it routinely, so those calls end up not
recorded at all for clients that still rely on R.

Add an opt-in --record_fname_encode option. When it is given, '/' and
'%' in the Call-ID and from-tag are percent-encoded as "%2F" and "%25"
before the name is built, so the file is created inside of the recording
directory, never contains '/', and the original value can be recovered
by decoding the "%XX" sequences. The encoded value is bounded by the same
PATH_MAX buffers and the snprintf() truncation checks are kept, so names
that do not fit are still refused. The default behaviour is unchanged:
without the option '/' is refused as before (the log message now points
at the option). Names given explicitly with C are not affected.

Add a recording/basic sub-test, badpath_enc, that records the traversal
Call-IDs from badpath and a Call-ID with '%' under their encoded names
with the option, and still refuses an over-long Call-ID.
@mdzesseis

Copy link
Copy Markdown
Owner Author

Aberto oficialmente: sippy#187

@mdzesseis mdzesseis closed this Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant