-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperation.inc
1406 lines (1111 loc) · 40.1 KB
/
operation.inc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//
// operation.inc - centralized code for validating requested user operations
//
// All input data should be subjected to the following:
// - perform syntactic checks on all input data like making sure numbers are numbers and emails are emails,
// sanitizing input where appropriate
// - perform business-logic checks, like making sure referenced objects exist, and that the current user
// is authorized to perform the operation
//
// In some cases a GUI or API operation may instantiate more than one op_check, if the op is
// a compound operation.
//
// The point of the code in this file is to improve security. By creating a systematic and
// centralized means for checking user input in various ways, we make it much harder
// to ignore important security checks.
//
// Furthermore, the systematic approach to discovering errored input allows for much more
// consistent and user friendly error reporting.
//
// The attacks addressed by this scheme are XSS, injection, and Authorization attacks.
// The "common security programming errors" addressed by this file are referenced here:
// http://cwe.mitre.org/top25/#CWE-79
// http://cwe.mitre.org/top25/#CWE-89
// http://cwe.mitre.org/top25/#CWE-285
// http://cwe.mitre.org/top25/#CWE-807
// http://cwe.mitre.org/top25/#CWE-78
// http://cwe.mitre.org/top25/#CWE-754
// http://cwe.mitre.org/top25/#CWE-209
// http://cwe.mitre.org/top25/#CWE-306
//
// Classes defined in this file should have the form:
//
// SCC_OPC_<VERB>_<NOUN>
//
// NOTE: if adding new operations, make sure it hasn't already been implemented first!
// Also, look and see if other ops exist with the Noun you're working with.
//
// Try to be consistent with other VERBs and NOUNs.
define('API_PARAM_OPTIONAL', 0);
define('API_PARAM_MANDATORY', 1);
define("API_PARAM_ERR_MISSING", 1);
define("API_PARAM_ERR_INVALID", 2);
define("API_PARAM_ERR_CUSTOM", 3);
define("API_PARAM_DEFAULT_MAX_LEN", 256);
define("API_PARAM_MAX_PATH_LEN", 512);
define("API_PARAM_PASSWORD_MAX_LEN", 64); // sync with db
define("API_PARAM_STRING", "string");
define("API_PARAM_ALPHANUM", "alphanum");
define("API_PARAM_INTEGER", "integer");
define("API_PARAM_LARGE_INTEGER", "large_integer");
define("API_PARAM_BOOLEAN", "boolean");
define("API_PARAM_ENUM", "enum");
define("API_PARAM_EMAIL", "email");
define("API_PARAM_EMAIL_LIST", "email_list");
define("API_PARAM_FRIEND", "friend");
define("API_PARAM_FRIEND_LIST", "friend_list");
define("API_PARAM_PATH", "path");
define("API_PARAM_IP_ADDRESS", "ip_address");
define("API_PARAM_MAC_ADDRESS", "mac_address");
define("API_PARAM_PASSWORD", "password");
class API_Operation
{
static $node_stack = array();
static $url_params = array();
static $version = null;
static $docs_mode = null;
var $publish;
var $op_check;
var $description;
var $node;
var $verb;
function __construct($op_check, $description, $publish = API_PUBLIC)
{
$this->op_check = $op_check;
$this->description = $description;
$this->publish = $publish;
}
function setNode($node)
{
$this->node = $node;
}
function setVerb($verb)
{
$this->verb = $verb;
}
function go()
{
if (self::$docs_mode)
{
return self::$docs_mode->outputOperationDocs($this);
}
else
{
// do operation checks
$this->op_check->run(self::$url_params);
// do we need to proxy this request?
if (is_media_server())
{
// we need to proxy if:
// 1) requesting a user's resource and the user is not this media server's master user
// 2) requesting a non-media-server resource
if (false) //!$this->op_check->getResourceOwner() || !$this->op_check->isDSLService($this->op_check->getService()))
{
_api_translate_output(api_proxy_portal_request());
return;
}
}
else
{
// we need to proxy if:
// 1) requesting a media-server resource
if ($this->op_check->isDSLService($this->op_check->getService()))
{
_api_translate_output(api_proxy_dsl_request($this->op_check->getResourceOwner()));
return;
}
}
// run the operation
return $this->run($this->op_check->sanitized_params);
}
}
function run($params)
{
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "run() not implemented in [" . get_class($this) . "]");
}
static function set_docs_mode($docs_op)
{
self::$docs_mode = $docs_op;
}
static function push_node($node)
{
array_push(self::$node_stack, $node);
}
static function pop_node()
{
return array_pop(self::$node_stack);
}
static function add_url_param($param_name, $param)
{
self::$url_params[$param_name] = $param;
}
static function remove_url_param($param_name)
{
unset(self::$url_params[$param_name]);
}
}
class SCC_Operation_Check
{
var $api_operation = null;
var $param_definitions = array();
var $url_params = array();
var $params = array();
var $sanitized = false;
var $sanitized_params = array();
var $resource_owner;
var $network_info;
var $host;
var $path;
var $service;
function __construct($api_operation)
{
$this->api_operation = $api_operation;
// collect URL param definitions
foreach (API_Operation::$node_stack as $node)
{
if ($node->param_definition)
{
$node->param_definition['url_param'] = true;
$node->param_definition['required'] = true;
$this->define_param($node->param_definition);
}
}
$this->define_param(array(
'name' => 'debug',
'publish' => API_NOT_PUBLISHED,
'required' => API_PARAM_OPTIONAL,
'type' => API_PARAM_STRING,
'description' => "Give a little extra information to the API call")
);
}
function run($url_params)
{
// skip param validation in docs mode
if (!API_Operation::$docs_mode)
{
$this->prepareParams($url_params);
$this->validateParams();
}
// do object existence/non-existence checks
// - throws exceptions for invalid cases
$this->doExistenceChecks();
// make sure user has authorization for requested operation
// - throws exceptions for invalid cases
$this->doAuthorizationChecks();
// make sure the operation is allowed in terms of the target account's status
$this->doAccountStatusChecks();
// other checks, such as checking network/host status before connect attempts
// optional, does not need to be implemented
$this->doOtherChecks();
}
function doExistenceChecks()
{
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "Operation [" . get_class($this) . "]: Unimplemented doExistenceChecks()");
}
function doAuthorizationChecks()
{
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "Operation [" . get_class($this) . "]: Unimplemented doAuthorizationChecks()");
}
function doAccountStatusChecks()
{
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "Operation [" . get_class($this) . "]: Unimplemented doAccountStatusChecks()");
}
function doOtherChecks()
{
// optional function, no need to throw an exception here
}
////////////////////////////
//
// node functions
//
////////////////////////////
function getActiveNode()
{
return end(API_Operation::$node_stack);
}
function isSearchNode()
{
foreach (API_Operation::$node_stack as $node)
{
if ($node->node_id == "SEARCH")
return true;
}
return false;
}
function isMe()
{
foreach (API_Operation::$node_stack as $node)
{
if ($node->node_id == "ME")
return true;
}
return false;
}
function getNodeService($node)
{
$service = null;
switch ($node->node_id)
{
case "RDP":
$service = SCC_SERVICE_RDP;
break;
case "VNC":
$service = SCC_SERVICE_VNC;
break;
case "HTTP":
$service = SCC_SERVICE_HTTP;
break;
case "USB_DEVICE":
$service = SCC_SERVICE_USB_DEVICE;
break;
case "PATH":
$service = SCC_SERVICE_DSL;
break;
case "DOWNLOAD":
$service = SCC_SERVICE_FILE;
break;
case "ZIP":
$service = $this->isSearchNode()?SCC_SERVICE_SEARCH_ZIP:SCC_SERVICE_ZIP;
break;
case "SLIDESHOW":
$service = $this->isSearchNode()?SCC_SERVICE_SEARCH_SLIDESHOW:SCC_SERVICE_SLIDESHOW;
break;
case "MUSIC":
$service = $this->isSearchNode()?SCC_SERVICE_SEARCH_MUSIC:SCC_SERVICE_MUSIC;
break;
case "VIDEO":
$service = $this->isSearchNode()?SCC_SERVICE_SEARCH_VIDEO:SCC_SERVICE_VIDEO;
break;
}
return $service;
}
function getService()
{
if ($this->service)
return $this->service;
for ($n=count(API_Operation::$node_stack)-1; $n >= 0; $n--)
{
if (($this->service = $this->getNodeService(API_Operation::$node_stack[$n])) )
break;
}
return $this->service;
}
function isDSLService($service)
{
switch ($service)
{
case SCC_SERVICE_DSL:
case SCC_SERVICE_FILE:
case SCC_SERVICE_ZIP:
case SCC_SERVICE_SLIDESHOW:
case SCC_SERVICE_MUSIC:
case SCC_SERVICE_VIDEO:
case SCC_SERVICE_SEARCH_ZIP:
case SCC_SERVICE_SEARCH_SLIDESHOW:
case SCC_SERVICE_SEARCH_MUSIC:
case SCC_SERVICE_SEARCH_VIDEO:
return true;
}
return false;
}
////////////////////////////
//
// param functions
//
////////////////////////////
function define_param($param_def)
{
if (isset($this->param_definitions[$param_def['name']]))
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "param [" . $param_def['name'] . "] already defined in [" . get_class($this) . "]");
switch ($param_def['type'])
{
case API_PARAM_ENUM:
if (!isset($param_def['constraints']))
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "enum param [" . $param_def['name'] . "] requires definition of allowed keywords in constraints");
if (isset($param_def['constraints'][0]))
{
$constraints = array();
foreach ($param_def['constraints'] as $keyword)
$constraints[$keyword] = $keyword;
$param_def['constraints'] = $constraints;
}
break;
case API_PARAM_INTEGER:
case API_PARAM_LARGE_INTEGER:
case API_PARAM_ALPHANUM:
case API_PARAM_STRING:
case API_PARAM_BOOLEAN:
case API_PARAM_EMAIL:
case API_PARAM_EMAIL_LIST:
case API_PARAM_FRIEND:
case API_PARAM_FRIEND_LIST:
case API_PARAM_PATH:
case API_PARAM_IP_ADDRESS:
case API_PARAM_MAC_ADDRESS:
case API_PARAM_PASSWORD:
// no mandatory constraints to check
break;
default:
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "param [" . $param_def['name'] . "]: unknown type [" . $param_def['type'] . "]");
}
if (!isset($param_def['description']))
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "param [" . $param_def['name'] . "] missing description");
if (!isset($param_def['publish']))
$param_def['publish'] = API_PUBLIC;
$this->param_definitions[] = $param_def;
}
function prepareParams($url_params)
{
if ($url_params)
$this->url_params = $url_params;
if ($_SERVER['REQUEST_METHOD'] == "GET")
$this->params = array_merge($_GET, $this->url_params);
else
{
$req_headers = getallheaders();
if (strstr($req_headers['Content-Type'], "application/json"))
{
$json = file_get_contents("php://input");
}
else if (isset($_POST[FORM_API_JSON_REQ]))
{
$json = $_POST[FORM_API_JSON_REQ];
}
if ($json)
{
$json_params = json_decode($json, true);
if (!$json_params)
throw new SCC_API_Internal_Error_Exception("INTERNAL_ERROR", "Could not parse JSON request data");
$this->params = array_merge($json_params, $this->url_params);
}
else
{
$this->params = array_merge($_POST, $this->url_params);
}
}
}
function validateParams()
{
foreach ($this->param_definitions as $param_def)
{
$name = $param_def['name'];
$param = $this->params[$name];
$value = null;
if ($param_def['required'] && !isset($this->params[$name]))
throw new SCC_API_Bad_Request_Exception("PARAM_MISSING", "Mandatory parameter [$name] missing");
if (isset($this->params[$name]))
{
if ($param === '' && !$param_def['empty_string_ok'])
{
if ($param_def['required'])
throw new SCC_API_Bad_Request_Exception("PARAM_MISSING", "Mandatory parameter [$name] missing");
}
else switch ($param_def['type'])
{
case API_PARAM_ENUM:
$value = $this->validateEnum($param_def, $param);
break;
case API_PARAM_INTEGER:
$value = $this->validateInteger($param_def, $param);
break;
case API_PARAM_LARGE_INTEGER:
$value = $this->validateLargeInteger($param_def, $param);
break;
case API_PARAM_ALPHANUM:
$value = $this->validateAlphaNumeric($param_def, $param);
break;
case API_PARAM_STRING:
$value = $this->sanitizeText($param_def, $param);
break;
case API_PARAM_BOOLEAN:
$value = $this->validateBoolean($param_def, $param);
break;
case API_PARAM_EMAIL:
$value = $this->validateEmail($param_def, $param);
break;
case API_PARAM_EMAIL_LIST:
$value = $this->validateEmailList($param_def, $param);
break;
case API_PARAM_FRIEND:
$value = $this->validateFriend($param_def, $param);
break;
case API_PARAM_FRIEND_LIST:
$value = $this->validateFriendList($param_def, $param);
break;
case API_PARAM_PATH:
$value = $this->validatePath($param_def, $param);
break;
case API_PARAM_IP_ADDRESS:
$value = $this->validateIPAddr($param_def, $param);
break;
case API_PARAM_MAC_ADDRESS:
$value = $this->validateMACAddr($param_def, $param);
break;
case API_PARAM_PASSWORD:
$value = $this->validatePassword($param_def, $param);
break;
}
}
// set default value if defined
if ($value === null && isset($param_def['default']))
$value = $param_def['default'];
if ($value !== null)
$this->sanitized_params[$name] = $value;
}
}
function getParam($name)
{
return isset($this->sanitized_params[$name])?$this->sanitized_params[$name]:null;
}
////////////////////////////////////////////////////////
//
// Param format validation checks & sanitization
//
////////////////////////////////////////////////////////
function validateInteger($param_def, $param)
{
$param_name = $param_def['name'];
if (($param = filter_var($param, FILTER_VALIDATE_INT) === false))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must be a number");
$constraints = $param_def['constraints'];
$low = ($constraints && isset($constraints['low']))?$constraints['low']:null;
$high = ($constraints && isset($constraints['high']))?$constraints['high']:null;
if ($low !== null && $param < (int) $low)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] out of range");
if ($high !== null && $param > (int) $high)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] out of range");
return $param;
}
function validateBoolean($param_def, $param)
{
$param_name = $param_def['name'];
$fail = false;
if ( ($num = filter_var($param, FILTER_VALIDATE_INT)) !== false)
{
if ($num != 0 && $num != 1)
$fail = true;
}
else switch ($param)
{
case 'true':
case 'yes':
case 'on':
$num = 1;
break;
case 'false':
case 'no':
case 'off':
$num = 0;
break;
default:
$fail = true;
}
if ($fail)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Boolean parameter [$param_name] must have one of the following values: [0|1|true|false|yes|no|on|off]");
return $num;
}
// validate numbers that may exceed PHP_INT_MAX
function validateLargeInteger($param_def, $param)
{
$param_name = $param_def['name'];
if (!preg_match("/^-?\d+$/", $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must be a number");
$constraints = $param_def['constraints'];
$low = ($constraints && isset($constraints['low']))?$constraints['low']:null;
$high = ($constraints && isset($constraints['high']))?$constraints['high']:null;
if ($low !== null && gmp_cmp($param, $low) == -1)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] out of range");
if ($high !== null && gmp_cmp($param, $high) == 1)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] out of range");
return $param;
}
function validateEnum($param_def, $param)
{
$param_name = $param_def['name'];
$matched = null;
$keys_str = '';
foreach ($param_def['constraints'] as $key => $values)
{
$keys_str .= "$key|";
if ($param == $key)
$matched = isset($values['value'])?$values['value']:$key;
}
if ($matched === null)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must be one of [" . substr($keys_str, 0, -1) . "]");
return $matched;
}
function validateAlphaNumeric($param_def, $param)
{
$param_name = $param_def['name'];
if (!preg_match("/^[0-9a-zA-Z_]+$/", $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must consist only of numbers, letters, and the underscore character '_' - " . var_export($this->url_params, true));
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_DEFAULT_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
return $param;
}
function validatePassword($param_def, $param)
{
$param_name = $param_def['name'];
if (strlen($param) < 8 || !preg_match("/[0-9]/", $param) || !preg_match("/[`~!@#$%^&*()-_=+\[{\]}|\\\\;:'\",<.>\/?]/", $param))
throw new SCC_API_Bad_Request_Exception("WEAK_PASSWORD", "Password must be at least 8 characters long, contain at least one number, and at least one special character");
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_PASSWORD_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
return $param;
}
function validateIPAddr($param_def, $param)
{
$param_name = $param_def['name'];
if (!preg_match("/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] is not a valid IP address");
return $param;
}
function validateMACAddr($param_def, $param)
{
$param_name = $param_def['name'];
if (!preg_match("/^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/", $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] is not a valid MAC address");
return $param;
}
function validateEmail($param_def, $param)
{
$param_name = $param_def['name'];
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_DEFAULT_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", trim(strtolower($param))))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must be a valid email address");
return $param;
}
// returns array of email addresses
function validateEmailList($param_def, $param)
{
$param_name = $param_def['name'];
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_DEFAULT_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
$valid = array();
foreach (split('[,;]', $param) as $email)
{
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", trim(strtolower($email))))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must be a list of valid email addresses - [" . $this->cleanInputXSS($email) . "] is invalid.");
else
$valid[] = trim($email);
}
return $valid;
}
function validateFriend($param_def, $param)
{
$param_name = $param_def['name'];
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_DEFAULT_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
if (preg_match("/^@[0-9 _a-zA-Z]+$/", $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must take the form @username, where username consists only of letters, numbers, underscore (_), and spaces.");
return $param;
}
// returns array of usernames
function validateFriendList($param_def, $param)
{
$param_name = $param_def['name'];
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_DEFAULT_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
$valid = array();
foreach (split('[,;]', $param) as $friend)
{
if (preg_match("/^@[0-9 _a-zA-Z]+$/", trim($friend)))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must be a list of valid usernames, of the form @username - [" . $this->cleanInputXSS($friend) . "] is invalid.");
else
$valid[] = substr(trim($friend, 1));
}
return $valid;
}
// prevent injection and path traversal attacks (like abc/../../../sensitive/dir)
function validatePath($param_def, $param)
{
$param_name = $param_def['name'];
// check for '..', '../rest/of/path', 'start/of/path/../rest', 'path/..'
if ($param == '..' || preg_match('#^\.{2}/#', $param) || preg_match('#/\.{2}/#', $param) || preg_match('#/\.{2}$#', $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] is not a valid folder or file name");
// fs_name(/fs_name)*/?
// where fs_name is [^/:\*\?<>\|\\\\]+ - i.e. valid filenames don't have the following chars: /:*?<>|\
if (!preg_match('#^[^/:\*\?<>\|\\\\]+(/[^/:\*\?<>\|\\\\]+)*/?$#', $param))
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] is not a valid folder or file name");
// note: if path has UTF8 chars strlen will overestimate the length
// they fix this in PHP 5.3
if (strlen($param) >= API_PARAM_MAX_PATH_LEN)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] is not a valid folder or file name (exceeds " . API_PARAM_MAX_PATH_LEN . " characters)");
return $param;
}
// doesn't throw an exception since this is an optional value to pass to tc/tr params
function checkForUnoptValue($param_def, $param)
{
return (strtolower($param) == 'unopt');
}
function sanitizeText($param_def, $param)
{
$param_name = $param_def['name'];
$constraints = $param_def['constraints'];
$max_len = ($constraints && isset($constraints['max_length']))?$constraints['max_length']:API_PARAM_DEFAULT_MAX_LEN;
if (strlen($param) > $max_len)
throw new SCC_API_Bad_Request_Exception("INVALID_PARAM", "Parameter [$param_name] must not exceed $max_len characters");
$sanitized = $this->cleanInputXSS($param);
return $sanitized;
}
function sanitizeSearchKeywords($param_def, $param)
{
$sanitized = $this->sanitizeText($param_def, $param);
// clean up the query
$terms = preg_split("/\s+/", $sanitized);
$cleaned = array();
foreach ($terms as $term)
if ( ($term = preg_replace('/^\W+/', '', trim($term))) )
$cleaned[] = $term;
$cleaned_str = implode(' ', $cleaned);
return $cleaned_str;
}
function cleanInputXSS($string)
{
$string = str_replace(array("&","<",">"),array("&amp;","&lt;","&gt;"),$string);
// fix &entitiy\n;
$string = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u',"$1;",$string);
$string = preg_replace('#(&\#x*)([0-9A-F]+);*#iu',"$1$2;",$string);
$string = html_entity_decode($string, ENT_COMPAT, "UTF-8");
// remove any attribute starting with "on" or xmlns
$string = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $string);
// remove javascript: and vbscript: protocol
$string = preg_replace('#([a-z]*)[\x00-\x20\/]*=[\x00-\x20\/]*([\`\'\"]*)[\x00-\x20\/]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2nojavascript...', $string);
$string = preg_replace('#([a-z]*)[\x00-\x20\/]*=[\x00-\x20\/]*([\`\'\"]*)[\x00-\x20\/]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2novbscript...', $string);
$string = preg_replace('#([a-z]*)[\x00-\x20\/]*=[\x00-\x20\/]*([\`\'\"]*)[\x00-\x20\/]*-moz-binding[\x00-\x20]*:#Uu', '$1=$2nomozbinding...', $string);
$string = preg_replace('#([a-z]*)[\x00-\x20\/]*=[\x00-\x20\/]*([\`\'\"]*)[\x00-\x20\/]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $string);
//remove any style attributes, IE allows too much stupid things in them, eg.
//<span style="width: expression(alert('Ping!'));"></span>
// and in general you really don't want style declarations in your UGC
$string = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])style[^>]*>#iUu', "$1>", $string);
//remove namespaced elements (we do not need them...)
$string = preg_replace('#</*\w+:\w[^>]*>#i',"",$string);
//remove really unwanted tags
do {
$oldstring = $string;
$string = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i',"",$string);
} while ($oldstring != $string);
return $string;
}
////////////////////////////////////////////////////////
//
// Existence & authorization checks
//
////////////////////////////////////////////////////////
function checkAuthenticated()
{
if (false) // (!($creds = get_client_credentials()) )
{
if (is_ra_client())
// if we're coming from our web gui, we need a session
throw new SCC_API_Unauthorized_Exception("INVALID_SESSION");
else
// otherwise this is a client app that needs an OAuth bearer token
throw new SCC_API_Unauthorized_Exception("NO_CLIENT_ACCESS", "Client does not have valid credentials - use /oauth/req_token");
}
return true;
}
function checkIsMe()
{
// in docs mode just describe what we're doing
if (API_Operation::$docs_mode)
return API_Operation::$docs_mode->addOperationNote("This operation must be run as 'me', i.e. the currently authenticated user");
foreach (API_Operation::$node_stack as $node)
{
if ($node->node_id == "ME")
return true;
}
throw new SCC_API_Forbidden_Exception("FORBIDDEN", "This operation may only be performed on the user's own account");
}
function checkAccountIsPremium()
{
// in docs mode just describe what we're doing
if (API_Operation::$docs_mode)
return API_Operation::$docs_mode->addOperationNote("This operation requires a premium account.");
// switch(get_account_status())
// {
// case TRIAL_USAGE:
// case PAID_USAGE:
// case AUTOPAY_USAGE:
// break;
//
// default:
// throw new SCC_API_Service_Unavailable_Exception
// }
return true;
}
////////////////////////////////////////////
//
// web portal checks
//
////////////////////////////////////////////
function getResourceOwner()
{
if (!$this->resource_owner)
{
if (!is_media_server())
{
foreach (API_Operation::$node_stack as $node)
{
if ($node->node_id == 'ME')
$username = get_auth_username();
else if ($node->node_id == 'FRIEND')
$username = $this->getParam(FORM_API_FRIEND);
}
if ($username)
{
if (!($this->resource_owner = dbu_get_user($username)) )
throw new SCC_API_Not_Found_Exception("USER_NOT_FOUND", "Unknown user [$username]");
}
}
/*
else
{
$dsl_user = dbu_get_master_user();
foreach (API_Operation::$node_stack as $node)
{
if ($node->node_id == 'ME')
$this->resource_owner = $dsl_user;
else if ($node->node_id == 'FRIEND' && $dsl_user['username'] == $this->getParam(FORM_API_FRIEND))
$this->resource_owner = $dsl_user;
}
}
*/
}
return $this->resource_owner;
}
function checkNetworkInfoValid($acct = null)
{
// in docs mode just describe what we're doing
if (API_Operation::$docs_mode)
return API_Operation::$docs_mode->addOperationNote("This operation requires the user to have installed the software on one or more PCs in their network.");
if ($this->network_info)