Make outgoing salmons work.
[akkoma] / lib / pleroma / web / salmon / salmon.ex
1 defmodule Pleroma.Web.Salmon do
2 use Bitwise
3 alias Pleroma.Web.XML
4 alias Pleroma.Web.OStatus.ActivityRepresenter
5 alias Pleroma.User
6 require Logger
7
8 def decode(salmon) do
9 doc = XML.parse_document(salmon)
10
11 {:xmlObj, :string, data} = :xmerl_xpath.string('string(//me:data[1])', doc)
12 {:xmlObj, :string, sig} = :xmerl_xpath.string('string(//me:sig[1])', doc)
13 {:xmlObj, :string, alg} = :xmerl_xpath.string('string(//me:alg[1])', doc)
14 {:xmlObj, :string, encoding} = :xmerl_xpath.string('string(//me:encoding[1])', doc)
15 {:xmlObj, :string, type} = :xmerl_xpath.string('string(//me:data[1]/@type)', doc)
16
17
18 {:ok, data} = Base.url_decode64(to_string(data), ignore: :whitespace)
19 {:ok, sig} = Base.url_decode64(to_string(sig), ignore: :whitespace)
20 alg = to_string(alg)
21 encoding = to_string(encoding)
22 type = to_string(type)
23
24 [data, type, encoding, alg, sig]
25 end
26
27 # TODO rewrite in with-stile
28 # Make it fetch the key from the saved user if there is one
29 def fetch_magic_key(salmon) do
30 [data, _, _, _, _] = decode(salmon)
31 doc = XML.parse_document(data)
32 uri = XML.string_from_xpath("/entry/author[1]/uri", doc)
33
34 {:ok, info} = Pleroma.Web.OStatus.gather_user_info(uri)
35
36 info.magic_key
37 end
38
39 def decode_and_validate(magickey, salmon) do
40 [data, type, encoding, alg, sig] = decode(salmon)
41
42 signed_text = [data, type, encoding, alg]
43 |> Enum.map(&Base.url_encode64/1)
44 |> Enum.join(".")
45
46 key = decode_key(magickey)
47
48 verify = :public_key.verify(signed_text, :sha256, sig, key)
49
50 if verify do
51 {:ok, data}
52 else
53 :error
54 end
55 end
56
57 def decode_key("RSA." <> magickey) do
58 make_integer = fn(bin) ->
59 list = :erlang.binary_to_list(bin)
60 Enum.reduce(list, 0, fn (el, acc) -> (acc <<< 8) ||| el end)
61 end
62
63 [modulus, exponent] = magickey
64 |> String.split(".")
65 |> Enum.map(&Base.url_decode64!/1)
66 |> Enum.map(make_integer)
67
68 {:RSAPublicKey, modulus, exponent}
69 end
70
71 def encode_key({:RSAPublicKey, modulus, exponent}) do
72 modulus_enc = :binary.encode_unsigned(modulus) |> Base.url_encode64
73 exponent_enc = :binary.encode_unsigned(exponent) |> Base.url_encode64
74
75 "RSA.#{modulus_enc}.#{exponent_enc}"
76 end
77
78 def generate_rsa_pem do
79 port = Port.open({:spawn, "openssl genrsa"}, [:binary])
80 {:ok, pem} = receive do
81 {^port, {:data, pem}} -> {:ok, pem}
82 end
83 Port.close(port)
84 if Regex.match?(~r/RSA PRIVATE KEY/, pem) do
85 {:ok, pem}
86 else
87 :error
88 end
89 end
90
91 def keys_from_pem(pem) do
92 [private_key_code] = :public_key.pem_decode(pem)
93 private_key = :public_key.pem_entry_decode(private_key_code)
94 {:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} = private_key
95 public_key = {:RSAPublicKey, modulus, exponent}
96 {:ok, private_key, public_key}
97 end
98
99 def encode(private_key, doc) do
100 type = "application/atom+xml"
101 encoding = "base64url"
102 alg = "RSA-SHA256"
103
104 signed_text = [doc, type, encoding, alg]
105 |> Enum.map(&Base.url_encode64/1)
106 |> Enum.join(".")
107
108 signature = :public_key.sign(signed_text, :sha256, private_key) |> to_string |> Base.url_encode64
109 doc_base64= doc |> Base.url_encode64
110
111 # Don't need proper xml building, these strings are safe to leave unescaped
112 salmon = """
113 <?xml version="1.0" encoding="UTF-8"?>
114 <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
115 <me:data type="application/atom+xml">#{doc_base64}</me:data>
116 <me:encoding>#{encoding}</me:encoding>
117 <me:alg>#{alg}</me:alg>
118 <me:sig>#{signature}</me:sig>
119 </me:env>
120 """
121
122 {:ok, salmon}
123 end
124
125 def remote_users(%{data: %{"to" => to}}) do
126 to
127 |> Enum.map(fn(id) -> User.get_cached_by_ap_id(id) end)
128 |> Enum.filter(fn(user) -> user && !user.local end)
129 end
130
131 defp send_to_user(%{info: %{"salmon" => salmon}}, feed, poster) do
132 poster.(salmon, feed, [{"Content-Type", "application/magic-envelope+xml"}])
133 end
134
135 defp send_to_user(_,_,_), do: nil
136
137 def publish(user, activity, poster \\ &HTTPoison.post/3)
138 def publish(%{info: %{"keys" => keys}} = user, activity, poster) do
139 feed = ActivityRepresenter.to_simple_form(activity, user, true)
140 |> ActivityRepresenter.wrap_with_entry
141 |> :xmerl.export_simple(:xmerl_xml)
142 |> to_string
143
144 if feed do
145 {:ok, private, _} = keys_from_pem(keys)
146 {:ok, feed} = encode(private, feed)
147
148 remote_users(activity)
149 |> Enum.each(fn(remote_user) ->
150 Logger.debug("sending salmon to #{remote_user.ap_id}")
151 send_to_user(remote_user, feed, poster)
152 end)
153 end
154 end
155
156 def publish(%{id: id}, _, _), do: Logger.debug("Keys missing for user #{id}")
157 end