f70f5a19191466c983e05fe64af0948ea8854193
[akkoma] / lib / pleroma / captcha / captcha.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Captcha do
6 alias Plug.Crypto.{KeyGenerator, MessageEncryptor}
7 alias Calendar.DateTime
8
9 use GenServer
10
11 @doc false
12 def start_link() do
13 GenServer.start_link(__MODULE__, [], name: __MODULE__)
14 end
15
16 @doc false
17 def init(_) do
18 {:ok, nil}
19 end
20
21 @doc """
22 Ask the configured captcha service for a new captcha
23 """
24 def new() do
25 GenServer.call(__MODULE__, :new)
26 end
27
28 @doc """
29 Ask the configured captcha service to validate the captcha
30 """
31 def validate(token, captcha, answer_data) do
32 GenServer.call(__MODULE__, {:validate, token, captcha, answer_data})
33 end
34
35 @doc false
36 def handle_call(:new, _from, state) do
37 enabled = Pleroma.Config.get([__MODULE__, :enabled])
38
39 if !enabled do
40 {:reply, %{type: :none}, state}
41 else
42 new_captcha = method().new()
43
44 secret_key_base = Pleroma.Config.get!([Pleroma.Web.Endpoint, :secret_key_base])
45
46 # This make salt a little different for two keys
47 token = new_captcha[:token]
48 secret = KeyGenerator.generate(secret_key_base, token <> "_encrypt")
49 sign_secret = KeyGenerator.generate(secret_key_base, token <> "_sign")
50 # Basicallty copy what Phoenix.Token does here, add the time to
51 # the actual data and make it a binary to then encrypt it
52 encrypted_captcha_answer =
53 %{
54 at: DateTime.now_utc(),
55 answer_data: new_captcha[:answer_data]
56 }
57 |> :erlang.term_to_binary()
58 |> MessageEncryptor.encrypt(secret, sign_secret)
59
60 {
61 :reply,
62 # Repalce the answer with the encrypted answer
63 %{new_captcha | answer_data: encrypted_captcha_answer},
64 state
65 }
66 end
67 end
68
69 @doc false
70 def handle_call({:validate, token, captcha, answer_data}, _from, state) do
71 secret_key_base = Pleroma.Config.get!([Pleroma.Web.Endpoint, :secret_key_base])
72 secret = KeyGenerator.generate(secret_key_base, token <> "_encrypt")
73 sign_secret = KeyGenerator.generate(secret_key_base, token <> "_sign")
74
75 # If the time found is less than (current_time - seconds_valid), then the time has already passed.
76 # Later we check that the time found is more than the presumed invalidatation time, that means
77 # that the data is still valid and the captcha can be checked
78 seconds_valid = Pleroma.Config.get!([Pleroma.Captcha, :seconds_valid])
79 valid_if_after = DateTime.subtract!(DateTime.now_utc(), seconds_valid)
80
81 result =
82 with {:ok, data} <- MessageEncryptor.decrypt(answer_data, secret, sign_secret),
83 %{at: at, answer_data: answer_md5} <- :erlang.binary_to_term(data) do
84 try do
85 if DateTime.before?(at, valid_if_after), do: throw({:error, "CAPTCHA expired"})
86
87 if not is_nil(Cachex.get!(:used_captcha_cache, token)),
88 do: throw({:error, "CAPTCHA already used"})
89
90 res = method().validate(token, captcha, answer_md5)
91 # Throw if an error occurs
92 if res != :ok, do: throw(res)
93
94 # Mark this captcha as used
95 {:ok, _} =
96 Cachex.put(:used_captcha_cache, token, true, ttl: :timer.seconds(seconds_valid))
97
98 :ok
99 catch
100 :throw, e -> e
101 end
102 else
103 _ -> {:error, "Invalid answer data"}
104 end
105
106 {:reply, result, state}
107 end
108
109 defp method, do: Pleroma.Config.get!([__MODULE__, :method])
110 end