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