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