]> git.mxchange.org Git - friendica.git/blob - mod/salmon.php
salmon protocol changes magicsig draft-experimental, fixes to hostxrd
[friendica.git] / mod / salmon.php
1 <?php
2
3
4 // There is a lot of debug stuff in here because this is quite a
5 // complicated process to try and sort out. 
6
7 require_once('include/salmon.php');
8 require_once('library/simplepie/simplepie.inc');
9
10 function salmon_return($val) {
11
12         if($val >= 400)
13                 $err = 'Error';
14         if($val >= 200 && $val < 300)
15                 $err = 'OK';
16
17         logger('mod-salmon returns ' . $val);   
18         header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
19         killme();
20
21 }
22
23 function salmon_post(&$a) {
24
25         $xml = file_get_contents('php://input');
26
27         logger('mod-salmon: new salmon ' . $xml);
28
29         $nick       = (($a->argc > 1) ? notags(trim($a->argv[1])) : '');
30         $mentions   = (($a->argc > 2 && $a->argv[2] === 'mention') ? true : false);
31
32         $r = q("SELECT * FROM `user` WHERE `nickname` = '%s' LIMIT 1",
33                 dbesc($nick)
34         );
35         if(! count($r))
36                 salmon_return(500);
37
38         $importer = $r[0];
39
40         // parse the xml
41
42         $dom = simplexml_load_string($xml,'SimpleXMLElement',0,NAMESPACE_SALMON_ME);
43
44         // figure out where in the DOM tree our data is hiding
45
46         if($dom->provenance->data)
47                 $base = $dom->provenance;
48         elseif($dom->env->data)
49                 $base = $dom->env;
50         elseif($dom->data)
51                 $base = $dom;
52         
53         if(! $base) {
54                 logger('mod-salmon: unable to locate salmon data in xml ');
55                 salmon_return(400);
56         }
57
58         // Stash the signature away for now. We have to find their key or it won't be good for anything.
59
60
61         $signature = base64url_decode($base->sig);
62
63         // unpack the  data
64
65         // strip whitespace so our data element will return to one big base64 blob
66         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
67
68         // stash away some other stuff for later
69
70         $type = $base->data[0]->attributes()->type[0];
71         $keyhash = $base->sig[0]->attributes()->keyhash[0];
72         $encoding = $base->encoding;
73         $alg = $base->alg;
74
75         // Salmon magic signatures have evolved and there is no way of knowing ahead of time which
76         // flavour we have. We'll try and verify it regardless.
77
78         $stnet_signed_data = $data;
79
80         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
81
82         $compliant_format = str_replace('=','',$signed_data);
83
84
85         // decode the data
86         $data = base64url_decode($data);
87
88         // Remove the xml declaration
89         $data = preg_replace('/\<\?xml[^\?].*\?\>/','',$data);
90
91         // Create a fake feed wrapper so simplepie doesn't choke
92
93         $tpl = get_markup_template('fake_feed.tpl');
94         
95         $base = substr($data,strpos($data,'<entry'));
96
97         $feedxml = $tpl . $base . '</feed>';
98
99         logger('mod-salmon: Processed feed: ' . $feedxml);
100
101         // Now parse it like a normal atom feed to scrape out the author URI
102         
103     $feed = new SimplePie();
104     $feed->set_raw_data($feedxml);
105     $feed->enable_order_by_date(false);
106     $feed->init();
107
108         logger('mod-salmon: Feed parsed.');
109
110         if($feed->get_item_quantity()) {
111                 foreach($feed->get_items() as $item) {
112                         $author = $item->get_author();
113                         $author_link = unxmlify($author->get_link());
114                         break;
115                 }
116         }
117
118         if(! $author_link) {
119                 logger('mod-salmon: Could not retrieve author URI.');
120                 salmon_return(400);
121         }
122
123         // Once we have the author URI, go to the web and try to find their public key
124
125         logger('mod-salmon: Fetching key for ' . $author_link );
126
127
128         $key = get_salmon_key($author_link,$keyhash);
129
130         if(! $key) {
131                 logger('mod-salmon: Could not retrieve author key.');
132                 salmon_return(400);
133         }
134
135         // Setup RSA stuff to verify the signature
136
137         set_include_path(get_include_path() . PATH_SEPARATOR . 'library/phpsec');
138
139         require_once('library/phpsec/Crypt/RSA.php');
140
141         $key_info = explode('.',$key);
142
143         $m = base64url_decode($key_info[1]);
144         $e = base64url_decode($key_info[2]);
145
146         logger('mod-salmon: key details: ' . print_r($key_info,true));
147
148     $rsa = new CRYPT_RSA();
149     $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
150     $rsa->setHash('sha256');
151
152     $rsa->modulus = new Math_BigInteger($m, 256);
153     $rsa->k = strlen($rsa->modulus->toBytes());
154     $rsa->exponent = new Math_BigInteger($e, 256);
155
156         // We should have everything we need now. Let's see if it verifies.
157
158     $verify = $rsa->verify($compliant_format,$signature);
159
160         if(! $verify) {
161                 logger('mod-salmon: message did not verify using protocol. Trying padding hack.');
162             $verify = $rsa->verify($signed_data,$signature);
163     }
164
165         if(! $verify) {
166                 logger('mod-salmon: message did not verify using padding. Trying old statusnet hack.');
167             $verify = $rsa->verify($stnet_signed_data,$signature);
168     }
169
170         if(! $verify) {
171                 logger('mod-salmon: Message did not verify. Discarding.');
172                 salmon_return(400);
173         }
174
175         logger('mod-salmon: Message verified.');
176
177
178         /*
179         *
180         * If we reached this point, the message is good. Now let's figure out if the author is allowed to send us stuff.
181         *
182         */
183
184         $r = q("SELECT * FROM `contact` WHERE `network` = 'stat' AND ( `url` = '%s' OR `alias` = '%s') 
185                 AND `uid` = %d LIMIT 1",
186                 dbesc($author_link),
187                 dbesc($author_link),
188                 intval($importer['uid'])
189         );
190         if(! count($r)) {
191                 logger('mod-salmon: Author unknown to us.');
192         }       
193
194         // is this a follower? Or have we ignored the person?
195         // If so we can not accept this post.
196
197         if((count($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == REL_VIP) || ($r[0]['blocked']))) {
198                 logger('mod-salmon: Ignoring this author.');
199                 salmon_return(202);
200                 // NOTREACHED
201         }
202
203         require_once('include/items.php');
204
205         // Placeholder for hub discovery. We shouldn't find any hubs
206         // since we supplied the fake feed header - and it doesn't have any.
207
208         $hub = '';
209
210         /**
211          *
212          * anti-spam measure: consume_feed will accept a follow activity from 
213          * this person (and nothing else) if there is no existing contact record.
214          *
215          */
216
217         $contact_rec = ((count($r)) ? $r[0] : null);
218
219         consume_feed($feedxml,$importer,$contact_rec,$hub);
220
221         salmon_return(200);
222 }
223
224
225
226