logo

Use of insecure channel - Source code - Elixir


Need

To protect sensitive information during transmission over a network.


Context

  1. Usage of Elixir (1.12.0 and above) for building scalable and concurrent applications
  2. Usage of Cowboy HTTP server for handling HTTP requests

Description

Insecure Code Example

defmodule MyAppWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :my_app

  socket "/socket", MyAppWeb.UserSocket,
    websocket: true,
    longpoll: false

  plug Plug.Static,
    at: "/",
    from: :my_app,
    gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt)

  plug Plug.RequestId
  plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]

  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Phoenix.json_library()

  plug Plug.MethodOverride
  plug Plug.Head

  plug Plug.Session, store: :cookie

  plug MyAppWeb.Router
end

The code above configures an HTTP server with no encryption. Any data sent between the server and clients is vulnerable to interception. This can be exploited by an attacker to capture sensitive information and credentials in plain text, or intercept communication and steal or forge requests and responses.

Steps

  1. Acquire a valid TLS certificate for your domain.
  2. Configure your server to use HTTPS with the TLS certificate.
  3. Redirect all HTTP requests to HTTPS.

Secure Code Example

defmodule MyAppWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :my_app

  socket "/socket", MyAppWeb.UserSocket,
    websocket: true,
    longpoll: false

  plug Plug.Static,
    at: "/",
    from: :my_app,
    gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt)

  plug Plug.RequestId
  plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]

  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Phoenix.json_library()

  plug Plug.MethodOverride
  plug Plug.Head

  plug Plug.Session, store: :cookie

  plug Plug.ForceSSL
  plug MyAppWeb.Router
end

The updated code now includes the 'Plug.ForceSSL' plug, which redirects all non-HTTPS requests to HTTPS, ensuring that all data is transmitted over an encrypted channel. This mitigates the risk of data interception and forgery.


References

  • 332 - Use of insecure channel - Source code

  • Last updated

    2023/09/18