fb08d645b6cf57d4e6dd9fa3602852ab0af7702c
[akkoma] / lib / pleroma / web / salmon / salmon.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.Web.Salmon do
6 @httpoison Application.get_env(:pleroma, :httpoison)
7
8 use Bitwise
9
10 alias Pleroma.{Instances, User}
11 alias Pleroma.Web.XML
12 alias Pleroma.Web.OStatus.ActivityRepresenter
13
14 require Logger
15
16 def decode(salmon) do
17 doc = XML.parse_document(salmon)
18
19 {:xmlObj, :string, data} = :xmerl_xpath.string('string(//me:data[1])', doc)
20 {:xmlObj, :string, sig} = :xmerl_xpath.string('string(//me:sig[1])', doc)
21 {:xmlObj, :string, alg} = :xmerl_xpath.string('string(//me:alg[1])', doc)
22 {:xmlObj, :string, encoding} = :xmerl_xpath.string('string(//me:encoding[1])', doc)
23 {:xmlObj, :string, type} = :xmerl_xpath.string('string(//me:data[1]/@type)', doc)
24
25 {:ok, data} = Base.url_decode64(to_string(data), ignore: :whitespace)
26 {:ok, sig} = Base.url_decode64(to_string(sig), ignore: :whitespace)
27 alg = to_string(alg)
28 encoding = to_string(encoding)
29 type = to_string(type)
30
31 [data, type, encoding, alg, sig]
32 end
33
34 def fetch_magic_key(salmon) do
35 with [data, _, _, _, _] <- decode(salmon),
36 doc <- XML.parse_document(data),
37 uri when not is_nil(uri) <- XML.string_from_xpath("/entry/author[1]/uri", doc),
38 {:ok, public_key} <- User.get_public_key_for_ap_id(uri),
39 magic_key <- encode_key(public_key) do
40 {:ok, magic_key}
41 end
42 end
43
44 def decode_and_validate(magickey, salmon) do
45 [data, type, encoding, alg, sig] = decode(salmon)
46
47 signed_text =
48 [data, type, encoding, alg]
49 |> Enum.map(&Base.url_encode64/1)
50 |> Enum.join(".")
51
52 key = decode_key(magickey)
53
54 verify = :public_key.verify(signed_text, :sha256, sig, key)
55
56 if verify do
57 {:ok, data}
58 else
59 :error
60 end
61 end
62
63 def decode_key("RSA." <> magickey) do
64 make_integer = fn bin ->
65 list = :erlang.binary_to_list(bin)
66 Enum.reduce(list, 0, fn el, acc -> acc <<< 8 ||| el end)
67 end
68
69 [modulus, exponent] =
70 magickey
71 |> String.split(".")
72 |> Enum.map(fn n -> Base.url_decode64!(n, padding: false) end)
73 |> Enum.map(make_integer)
74
75 {:RSAPublicKey, modulus, exponent}
76 end
77
78 def encode_key({:RSAPublicKey, modulus, exponent}) do
79 modulus_enc = :binary.encode_unsigned(modulus) |> Base.url_encode64()
80 exponent_enc = :binary.encode_unsigned(exponent) |> Base.url_encode64()
81
82 "RSA.#{modulus_enc}.#{exponent_enc}"
83 end
84
85 # Native generation of RSA keys is only available since OTP 20+ and in default build conditions
86 # We try at compile time to generate natively an RSA key otherwise we fallback on the old way.
87 try do
88 _ = :public_key.generate_key({:rsa, 2048, 65537})
89
90 def generate_rsa_pem do
91 key = :public_key.generate_key({:rsa, 2048, 65537})
92 entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
93 pem = :public_key.pem_encode([entry]) |> String.trim_trailing()
94 {:ok, pem}
95 end
96 rescue
97 _ ->
98 def generate_rsa_pem do
99 port = Port.open({:spawn, "openssl genrsa"}, [:binary])
100
101 {:ok, pem} =
102 receive do
103 {^port, {:data, pem}} -> {:ok, pem}
104 end
105
106 Port.close(port)
107
108 if Regex.match?(~r/RSA PRIVATE KEY/, pem) do
109 {:ok, pem}
110 else
111 :error
112 end
113 end
114 end
115
116 def keys_from_pem(pem) do
117 [private_key_code] = :public_key.pem_decode(pem)
118 private_key = :public_key.pem_entry_decode(private_key_code)
119 {:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} = private_key
120 public_key = {:RSAPublicKey, modulus, exponent}
121 {:ok, private_key, public_key}
122 end
123
124 def encode(private_key, doc) do
125 type = "application/atom+xml"
126 encoding = "base64url"
127 alg = "RSA-SHA256"
128
129 signed_text =
130 [doc, type, encoding, alg]
131 |> Enum.map(&Base.url_encode64/1)
132 |> Enum.join(".")
133
134 signature =
135 signed_text
136 |> :public_key.sign(:sha256, private_key)
137 |> to_string
138 |> Base.url_encode64()
139
140 doc_base64 =
141 doc
142 |> Base.url_encode64()
143
144 # Don't need proper xml building, these strings are safe to leave unescaped
145 salmon = """
146 <?xml version="1.0" encoding="UTF-8"?>
147 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
148 <me:data type="application/atom+xml">#{doc_base64}</me:data>
149 <me:encoding>#{encoding}</me:encoding>
150 <me:alg>#{alg}</me:alg>
151 <me:sig>#{signature}</me:sig>
152 </me:env>
153 """
154
155 {:ok, salmon}
156 end
157
158 def remote_users(%{data: %{"to" => to} = data}) do
159 to = to ++ (data["cc"] || [])
160
161 to
162 |> Enum.map(fn id -> User.get_cached_by_ap_id(id) end)
163 |> Enum.filter(fn user -> user && !user.local end)
164 end
165
166 @doc "Pushes an activity to remote account."
167 def send_to_user(%{recipient: %{info: %{salmon: salmon}}} = params),
168 do: send_to_user(Map.put(params, :recipient, salmon))
169
170 def send_to_user(%{recipient: url, feed: feed, poster: poster} = params) when is_binary(url) do
171 with {:ok, %{status: code}} when code in 200..299 <-
172 poster.(
173 url,
174 feed,
175 [{"Content-Type", "application/magic-envelope+xml"}]
176 ) do
177 if !Map.has_key?(params, :unreachable_since) || params[:unreachable_since],
178 do: Instances.set_reachable(url)
179
180 Logger.debug(fn -> "Pushed to #{url}, code #{code}" end)
181 :ok
182 else
183 e ->
184 unless params[:unreachable_since], do: Instances.set_reachable(url)
185 Logger.debug(fn -> "Pushing Salmon to #{url} failed, #{inspect(e)}" end)
186 :error
187 end
188 end
189
190 def send_to_user(_), do: :noop
191
192 @supported_activities [
193 "Create",
194 "Follow",
195 "Like",
196 "Announce",
197 "Undo",
198 "Delete"
199 ]
200
201 @doc """
202 Publishes an activity to remote accounts
203 """
204 @spec publish(User.t(), Pleroma.Activity.t(), Pleroma.HTTP.t()) :: none
205 def publish(user, activity, poster \\ &@httpoison.post/3)
206
207 def publish(%{info: %{keys: keys}} = user, %{data: %{"type" => type}} = activity, poster)
208 when type in @supported_activities do
209 feed = ActivityRepresenter.to_simple_form(activity, user, true)
210
211 if feed do
212 feed =
213 ActivityRepresenter.wrap_with_entry(feed)
214 |> :xmerl.export_simple(:xmerl_xml)
215 |> to_string
216
217 {:ok, private, _} = keys_from_pem(keys)
218 {:ok, feed} = encode(private, feed)
219
220 remote_users = remote_users(activity)
221
222 salmon_urls = Enum.map(remote_users, & &1.info.salmon)
223 reachable_urls_metadata = Instances.filter_reachable(salmon_urls)
224 reachable_urls = Map.keys(reachable_urls_metadata)
225
226 remote_users
227 |> Enum.filter(&(&1.info.salmon in reachable_urls))
228 |> Enum.each(fn remote_user ->
229 Logger.debug(fn -> "Sending Salmon to #{remote_user.ap_id}" end)
230
231 Pleroma.Web.Federator.enqueue(:publish_single_salmon, %{
232 recipient: remote_user,
233 feed: feed,
234 poster: poster,
235 unreachable_since: reachable_urls_metadata[remote_user.info.salmon]
236 })
237 end)
238 end
239 end
240
241 def publish(%{id: id}, _, _), do: Logger.debug(fn -> "Keys missing for user #{id}" end)
242 end