You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5159 lines
207 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. wsseapi.c
  3. WS-Security plugin
  4. gSOAP XML Web services tools
  5. Copyright (C) 2000-2010, Robert van Engelen, Genivia Inc., All Rights Reserved.
  6. This part of the software is released under one of the following licenses:
  7. GPL, the gSOAP public license, or Genivia's license for commercial use.
  8. --------------------------------------------------------------------------------
  9. gSOAP public license.
  10. The contents of this file are subject to the gSOAP Public License Version 1.3
  11. (the "License"); you may not use this file except in compliance with the
  12. License. You may obtain a copy of the License at
  13. http://www.cs.fsu.edu/~engelen/soaplicense.html
  14. Software distributed under the License is distributed on an "AS IS" basis,
  15. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  16. for the specific language governing rights and limitations under the License.
  17. The Initial Developer of the Original Code is Robert A. van Engelen.
  18. Copyright (C) 2000-2010, Robert van Engelen, Genivia Inc., All Rights Reserved.
  19. --------------------------------------------------------------------------------
  20. GPL license.
  21. This program is free software; you can redistribute it and/or modify it under
  22. the terms of the GNU General Public License as published by the Free Software
  23. Foundation; either version 2 of the License, or (at your option) any later
  24. version.
  25. This program is distributed in the hope that it will be useful, but WITHOUT ANY
  26. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  27. PARTICULAR PURPOSE. See the GNU General Public License for more details.
  28. You should have received a copy of the GNU General Public License along with
  29. this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  30. Place, Suite 330, Boston, MA 02111-1307 USA
  31. Author contact information:
  32. engelen@genivia.com / engelen@acm.org
  33. This program is released under the GPL with the additional exemption that
  34. compiling, linking, and/or using OpenSSL is allowed.
  35. --------------------------------------------------------------------------------
  36. A commercial use license is available from Genivia, Inc., contact@genivia.com
  37. --------------------------------------------------------------------------------
  38. */
  39. /**
  40. @mainpage
  41. - @ref wsse documents the wsse plugin for WS-Security 1.0 support.
  42. - @ref smdevp documents the smdevp signature/digest engine.
  43. - @ref mecevp documents the mecevp encryption engine.
  44. - @ref threads documents a portable threads and locking API.
  45. */
  46. /**
  47. @page wsse The wsse WS-Security plugin
  48. @section wsse_5 Security Header
  49. The material in this section relates to the WS-Security specification section 5.
  50. To use the wsse plugin:
  51. -# Run wsdl2h -t typemap.dat on a WSDL of a service that requires WS-Security
  52. headers. The typemap.dat file is used to recognize and translate Security
  53. header blocks for XML signature and encryption.
  54. -# Run soapcpp2 on the header file produced by wsdl2h.
  55. -# (Re-)compile stdsoap2.c/pp, dom.c/pp, smdevp.c, mecevp.c, wsseapi.c and the
  56. generated source files with the -DWITH_DOM and -DWITH_OPENSSL compile flags
  57. set. The smdevp.c, mecevp.c, and wsseapi.c files are located in the 'plugin'
  58. directory.
  59. -# Use the wsse plugin API functions described below to add and verify
  60. Security headers, sign and verify messages, and to encrypt/decrypt messages.
  61. An example wsse client/server application can be found in gsoap/samples/wsse.
  62. The wsse engine is thread safe. However, if HTTPS is required please follow the
  63. instructions in Section @ref wsse_11 to ensure thread-safety of WS-Security
  64. with HTTPS.
  65. The wsse plugin API consists of a set of functions to populate and verify
  66. WS-Security headers and message body content. For more details, we refer to the
  67. following sections that correspond to the WS-Security specification sections:
  68. - Section 6 @ref wsse_6
  69. - Section 7 @ref wsse_7
  70. - Section 8 @ref wsse_8
  71. - Section 9 @ref wsse_9
  72. - Section 10 @ref wsse_10
  73. - @ref wsse_11
  74. - @ref wsse_12
  75. - @ref wsse_13
  76. - @ref wsse_wsc
  77. The basic API is introduced below.
  78. To add an empty Security header block to the SOAP header, use:
  79. @code
  80. soap_wsse_add_Security(soap);
  81. @endcode
  82. To delete a Security header, use:
  83. @code
  84. soap_wsse_delete_Security(soap);
  85. @endcode
  86. Adding an empty Security header block is not very useful. In the following, we
  87. present the higher-level functions of the wsse plugin to populate and verify
  88. Security header content.
  89. Note: The soap context includes an actor value soap.actor that is populated and
  90. rendered as the SOAP-ENV:actor (SOAP 1.1) or SOAP-ENV:role (SOAP 1.2) attribute
  91. in XML within the generic SOAP Header. The attribute is optional, but should be
  92. used to target a recipient such as an intermediate node to process the SOAP
  93. header. In contrast, actor or role attributes within Security header blocks
  94. target specific recipients to process the Security header block. The gSOAP
  95. implementation does not automate this feature and application should set and
  96. check the actor/role attribute when necessary. In addition, the current
  97. implementation supports the inclusion of a single Security header block in the
  98. SOAP header.
  99. To populate the SOAP-ENV:actor or SOAP-ENV:role attribute within the Security
  100. header, use:
  101. @code
  102. soap_wsse_add_Security_actor(soap, "recipient");
  103. @endcode
  104. To obtain the actor or role value (e.g. after receiving a message), use:
  105. @code
  106. _wsse__Security *security = soap_wsse_Security(soap);
  107. if (security)
  108. { ... = security->SOAP_ENV__actor; // SOAP 1.1
  109. ... = security->SOAP_ENV__role; // SOAP 1.2
  110. @endcode
  111. The SOAP-ENV:mustUnderstand attribute is automatically added and checked by the
  112. gSOAP engine. A gSOAP application compiled without Security support will reject
  113. Security headers.
  114. Security header blocks are attached to the soap context, which means that the
  115. information will be automatically kept to support multiple invocations.
  116. @section wsse_6 Security Tokens
  117. The material in this section relates to the WS-Security specification section 6.
  118. @subsection wsse_6_2 User Name Token
  119. To add a user name token to the Security header block, use:
  120. @code
  121. soap_wsse_add_UsernameTokenText(soap, "Id", "username", NULL);
  122. @endcode
  123. The Id value is optional. When non-NULL the user name token is included in the
  124. digital signature to protect its integrity. It is common for the wsse plugin
  125. functions to accept such Ids, which are serialized as wsu:Id identifiers for
  126. cross-referencing XML elements. The signature engine of the wsse plugin is
  127. designed to automatically sign all wsu:Id attributed elements to simplify the
  128. code you need to write to implement the signing process.
  129. To add a user name token with clear text password, use:
  130. @code
  131. soap_wsse_add_UsernameTokenText(soap, "Id", "username", "password");
  132. @endcode
  133. It is strongly recommended to use @ref soap_wsse_add_UsernameTokenText only in
  134. combination with HTTPS encrypted transmission or not at all. A better
  135. alternative is to use password digests. With password digest authentication,
  136. the digest value of a password (with message creation time and a random nonce)
  137. is compared on both sides, thus eliminating the need to exchange a password
  138. over the wire.
  139. To add a user name token with password digest, use:
  140. @code
  141. soap_wsse_add_UsernameTokenDigest(soap, "Id", "username", "password");
  142. @endcode
  143. Although the password string is passed to this function, it is not rendered in
  144. XML or stored in a message log. It has been argued that this approach adopted
  145. by the WS-Security protocol is still vulnerable since the application retrieves
  146. the password in text form requiring a database to store passwords in clear
  147. text. However, a digest algorithm can be used to hash the passwords and store
  148. their digests instead, which eliminates the need to store clear-text passwords.
  149. Note that this is a common approach adopted by Unix for decades.
  150. By setting the Id value to a unique string, the user name token is also
  151. digitally signed by the signature engine further preventing tampering with its
  152. value.
  153. You must use @ref soap_wsse_add_UsernameTokenDigest for each message exchange
  154. to refresh the password digest even when the user name and password are not
  155. changed. Otherwise, the receiver might flag the message as a replay attack.
  156. Clear-text passwords and password digests are verified with
  157. @ref soap_wsse_verify_Password. To verify a password at the receiving side to
  158. authorize a request (e.g. within a Web service operation), use:
  159. @code
  160. int ns__myMethod(struct soap *soap, ...)
  161. { const char *username = soap_wsse_get_Username(soap);
  162. const char *password;
  163. if (!username)
  164. return soap->error; // no username: return FailedAuthentication
  165. password = ...; // lookup password of username
  166. if (soap_wsse_verify_Password(soap, password))
  167. return soap->error; // password verification failed: return FailedAuthentication
  168. ... // process request, then sign the response message:
  169. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  170. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  171. || soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0)
  172. return soap->error;
  173. return SOAP_OK;
  174. }
  175. @endcode
  176. Note that the @ref soap_wsse_get_Username functions sets the
  177. wsse:FailedAuthentication fault. It is common for the wsse plugin functions to
  178. return SOAP_OK or a wsse fault that should be passed to the sender by returning
  179. soap->error from service operations. The fault is displayed with the
  180. soap_print_fault() function.
  181. Password digest authentication prevents message replay attacks. The wsse plugin
  182. keeps a database of password digests to thwart replay attacks. This is the
  183. only part in the plugin code that requires mutex provided by threads.h. Of
  184. course, this only works correctly if the server is persistent, such as a
  185. stand-alone service. Note that CGI-based services do not keep state. Machine
  186. clocks must be synchronized and clock skew should not exceed @ref
  187. SOAP_WSSE_CLKSKEW at the server side.
  188. @subsection wsse_6_3 Binary Security Tokens
  189. X509 certificates are commonly included in Security header blocks as binary
  190. security tokens. A certificate is used to verify the digital signature of a
  191. digitally signed message using the public key embedded within the certificate.
  192. The certificate itself is signed by a certificate authority (CA) that vouches
  193. for the authenticity of the certificate, i.e. to prove the identify of the
  194. message originator. This verification process is important, because digital
  195. signatures are useless without verification: an attacker could simply replace
  196. the message, sign it, and replace the certificate.
  197. Certificates are automatically verified by the wsse plugin signature engine
  198. when received and accessed, which means that the certificates of the CAs must
  199. be made accessible to the wsse plugin as follows:
  200. @code
  201. soap->cafile = "cacerts.pem"; // use this
  202. soap->capath = "dir/to/certs"; // and/or point to CA certs
  203. soap->crlfile = "revoked.pem"; // use CRL (optional)
  204. @endcode
  205. The @ref soap_wsse_verify_X509 function checks the validity of a certificate.
  206. The check is automatically performed. The check is also performed when
  207. retrieving the certificate from a Security header block, either automatically
  208. by the wsse plugin's signature verification engine or manually as follows:
  209. @code
  210. X509 *cert = soap_wsse_get_BinarySecurityTokenX509(soap, "Id");
  211. @endcode
  212. where Id is the identification string of the binary security token or NULL.
  213. The verification is an expensive process that will be optimized in future
  214. releases by caching the certificate chain.
  215. To attach a binary security token stored in a PEM file to a Security header
  216. block for transmission, use:
  217. @code
  218. soap_wsse_add_BinarySecurityTokenPEM(soap, NULL, "mycert.pem")
  219. @endcode
  220. A binary security token can be automatically signed by setting its Id
  221. attribute:
  222. @code
  223. soap_wsse_add_BinarySecurityTokenPEM(soap, "X509Token", "mycert.pem")
  224. @endcode
  225. Repeatedly loading a certificate from a PEM file is inefficient. To reuse a
  226. certificate loaded from a PEM file for multiple invocations, use:
  227. @code
  228. FILE *fd = fopen("mycert.pem", "r");
  229. X509 *cert = PEM_read_X509(fd, NULL, NULL, NULL);
  230. fclose(fd);
  231. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert))
  232. ... // an error occurred
  233. @endcode
  234. Other types of binary security tokens can be added to the Security header block using:
  235. @code
  236. soap_wsse_add_BinarySecurityToken(soap, "Id", "valueType", data, datalen);
  237. @endcode
  238. @section wsse_6_4 XML Tokens
  239. The use and processing rules for XML tokens such as SAML assertions is specific
  240. to an application. The wsse plugin does not automate the use of XML tokens.
  241. The developer is encouraged to generate code for the SAML schema with wsdl2h
  242. and add the necessary assertions to the Security header block:
  243. @code
  244. typedef struct _wsse__Security
  245. { struct _wsu__Timestamp* wsu__Timestamp;
  246. struct _wsse__UsernameToken* UsernameToken;
  247. struct _wsse__BinarySecurityToken* BinarySecurityToken;
  248. struct _saml__Assertion* saml__Assertion; // added
  249. struct xenc__EncryptedKeyType* xenc__EncryptedKey;
  250. struct ds__SignatureType* ds__Signature;
  251. @char* SOAP_ENV__actor;
  252. @char* SOAP_ENV__role;
  253. } _wsse__Security;
  254. @endcode
  255. Alternatively, a DOM can be used to store and retrieve XML tokens:
  256. @code
  257. #import "dom.h"
  258. typedef struct _wsse__Security
  259. { struct _wsu__Timestamp* wsu__Timestamp;
  260. struct _wsse__UsernameToken* UsernameToken;
  261. struct _wsse__BinarySecurityToken* BinarySecurityToken;
  262. struct xenc__EncryptedKeyType* xenc__EncryptedKey;
  263. struct ds__SignatureType* ds__Signature;
  264. int __size;
  265. xsd__anyType* any;
  266. @char* SOAP_ENV__actor;
  267. @char* SOAP_ENV__role;
  268. } _wsse__Security;
  269. @endcode
  270. @section wsse_7 Token References
  271. The material in this section relates to the WS-Security specification section 7.
  272. To use a certificate for signature verification, add a direct security token
  273. reference URI for the token to the KeyInfo, for example:
  274. @code
  275. soap_wsse_add_KeyInfo_SecurityTokenReferenceURI(soap, "URI", "valueType");
  276. @endcode
  277. and:
  278. @code
  279. soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "URI");
  280. @endcode
  281. For X509 certificates we use this to add a binary security token with the
  282. certificate and a reference to the local token:
  283. @code
  284. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  285. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token"))
  286. ... // an error occurred
  287. @endcode
  288. This follows the recommended practice to place Security token references in
  289. the KeyInfo element of a Signature. The KeyInfo is used to verify the validity
  290. of a signature value.
  291. Key identifiers can be used as well:
  292. @code
  293. soap_wsse_add_KeyInfo_SecurityTokenReferenceKeyIdentifier(soap, "Id", "valueType", data, datalen);
  294. @endcode
  295. Embedded references are added with:
  296. @code
  297. soap_wsse_add_KeyInfo_SecurityTokenReferenceEmbedded(soap, "Id", "valueType");
  298. @endcode
  299. Full support for embedded references requires coding to add tokens and
  300. assertions, as well as to consume embedded references at the receiving side.
  301. There is no automated mechanism to take the embedded references and process
  302. them accordingly.
  303. The use of key names is not recommended, but in case they are required they can
  304. be added with:
  305. @code
  306. soap_wsse_add_KeyInfo_KeyName(soap, "name");
  307. @endcode
  308. @section wsse_8 Signatures
  309. The material in this section relates to the WS-Security specification section 8.
  310. The wsse plugin must be registered to sign and verify messages:
  311. @code
  312. soap_register_plugin(soap, soap_wsse);
  313. @endcode
  314. XML signatures are usually computed over normalized XML (to ensure the XML
  315. processors of intermediate nodes can accurately reproduce the XML). To this
  316. end, the exclusive canonical XML standard (exc-c14n) is required, which is set
  317. using the SOAP_XML_CANONICAL flag:
  318. @code
  319. struct soap *soap = soap_new1(SOAP_XML_CANONICAL);
  320. soap_register_plugin(soap, soap_wsse);
  321. @endcode
  322. If you prefer XML indentation, use:
  323. @code
  324. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  325. soap_register_plugin(soap, soap_wsse);
  326. @endcode
  327. Other flags to consider:
  328. - SOAP_IO_CHUNK for HTTP chunked content to stream messages.
  329. - SOAP_ENC_GZIP for HTTP compression (also enables HTTP chunking).
  330. Next, we decide which signature algorithm is appropriate to use:
  331. - HMAC-SHA uses a secret key (also known as a shared key in symmetric
  332. cryptography) to sign the SHA digest of the SignedInfo element.
  333. - DSA-SHA uses a DSA private key to sign the SHA digest of the SignedInfo
  334. element.
  335. - RSA-SHA uses a RSA private key to sign the SHA digest of the SignedInfo
  336. element.
  337. HMAC-SHA is the simplest method, but relies on the fact that you have to make
  338. absolutely sure the key is kept secret on both the sending and receiving side.
  339. As long as the secret key is confidential, messages are securely signed.
  340. However, this is virtually impossible when exchanging messages with untrusted
  341. disparate parties. The advantage of HMAC-SHA is the speed by which messages
  342. are signed and verified.
  343. Algorithms HMAC SHA1, SHA256, and SHA512 are supported:
  344. - @ref SOAP_SMD_HMAC_SHA1 http://www.w3.org/2000/09/xmldsig#hmac-sha1
  345. - @ref SOAP_SMD_HMAC_SHA256 http://www.w3.org/2001/04/xmldsig-more#hmac-sha256
  346. - @ref SOAP_SMD_HMAC_SHA512 http://www.w3.org/2001/04/xmldsig-more#hmac-sha512
  347. DSA-SHA and RSA-SHA rely on public key cryptography. In simplified terms, a
  348. message is signed using the (confidential!) private key. The public key is used
  349. to verify the signature. Since only the originating party could have used its
  350. private key to sign the message, the integrity of the message is guaranteed. Of
  351. course, we must trust the public key came from the originator (it is often
  352. included as an X509 certificate in the message). To this end, a trusted
  353. certificate authority should have signed the public key, thereby creating a
  354. X509 certificate that contains the public key and the identity of the message
  355. originator.
  356. Algorithms DSA-SHA1, RSA-SHA1, RSA-SHA256, and RSA-SHA512 are supported:
  357. - @ref SOAP_SMD_SIGN_DSA_SHA1 http://www.w3.org/2000/09/xmldsig#dsa-sha1
  358. - @ref SOAP_SMD_SIGN_RSA_SHA1 http://www.w3.org/2000/09/xmldsig#rsa-sha1
  359. - @ref SOAP_SMD_SIGN_RSA_SHA256 http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
  360. - @ref SOAP_SMD_SIGN_RSA_SHA512 http://www.w3.org/2001/04/xmldsig-more#rsa-sha512
  361. An optional callback function can be passed to the plugin that is responsible
  362. for providing a certificate or key to the wsse engine to verify a signed
  363. message. For example, when a security token is absent from an DSA-SHA or
  364. RSA-SHA signed message then the only mechanism to automatically verify the
  365. signature is to let the callback produce a certificate:
  366. @code
  367. soap_register_plugin_arg(soap, soap_wsse, security_token_handler);
  368. const void *security_token_handler(struct soap *soap, int *alg, const char *keyname, int *keylen)
  369. { // Note: 'keyname' argument is may be used with shared secret key
  370. // decryption where the keyname is from the ds:KeyInfo/KeyName content
  371. if (keyname)
  372. { ... lookup keyname ...
  373. const void *key = ...;
  374. *keylen = ...;
  375. *alg = ...;
  376. return key;
  377. }
  378. // Get the user name from UsernameToken in message
  379. const char *uid = soap_wsse_get_Username(soap);
  380. switch (*alg)
  381. { case SOAP_SMD_VRFY_DSA_SHA1:
  382. case SOAP_SMD_VRFY_RSA_SHA1:
  383. case SOAP_SMD_VRFY_RSA_SHA256:
  384. case SOAP_SMD_VRFY_RSA_SHA512:
  385. if (uid)
  386. { // Lookup uid to retrieve the X509 certificate to verify the signature
  387. const X509 *cert = ...;
  388. return (const void*)cert;
  389. }
  390. return NULL; // no certificate: fail
  391. case SOAP_SMD_HMAC_SHA256:
  392. if (uid)
  393. { // Lookup uid to retrieve the HMAC SHA256 key to verify the signature
  394. const void *key = ...;
  395. *alg = ...;
  396. *keylen = ...;
  397. return key;
  398. }
  399. return NULL; // no certificate: fail
  400. case SOAP_MEC_ENV_DEC_DES_CBC:
  401. case SOAP_MEC_ENV_DEC_AES128_CBC:
  402. case SOAP_MEC_ENV_DEC_AES256_CBC:
  403. case SOAP_MEC_ENV_DEC_AES512_CBC:
  404. // return decryption private key associated with keyname
  405. case SOAP_MEC_DEC_DES_CBC:
  406. case SOAP_MEC_DEC_AES128_CBC:
  407. case SOAP_MEC_DEC_AES256_CBC:
  408. case SOAP_MEC_DEC_AES512_CBC:
  409. // *keylen = ...
  410. // return decryption shared secret key associated with keyname
  411. }
  412. return NULL; // fail
  413. }
  414. @endcode
  415. @subsection wsse_8_2a Signing Messages
  416. After the plugin is registered and a signature algorithm selected, the
  417. @ref soap_wsse_sign function or the @ref soap_wsse_sign_body function is used
  418. to initiate the signature engine to automatically sign outbound messages.
  419. The code to sign the SOAP Body of a message using HMAC-SHA1 is:
  420. @code
  421. static char hmac_key[16] =
  422. { 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88,
  423. 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 };
  424. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  425. soap_register_plugin(soap, soap_wsse);
  426. if (soap_wsse_sign_body(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key))
  427. ... // an error occurred
  428. else if (soap_call_ns__myMethod(soap, ...))
  429. ... // a transmission error occurred
  430. @endcode
  431. The hmac_key is some secret key you generated for the sending side and
  432. receiving side (don't use the one shown here). Instead of SHA1, SHA256 and
  433. SHA512 hashes can be used.
  434. As always, use soap_print_fault() to display the error message.
  435. To sign the body of an outbound SOAP message using RSA-SHA (DSA-SHA is
  436. similar), we include the X509 certificate with the public key as a
  437. BinarySecurityToken in the header and a KeyInfo reference to the token to let
  438. receivers use the public key in the certificate to verify the authenticity of
  439. the message:
  440. @code
  441. FILE *fd;
  442. EVP_PKEY *rsa_private_key;
  443. X509 *cert;
  444. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  445. soap_register_plugin(soap, soap_wsse);
  446. fd = fopen("privkey.pem", "r");
  447. rsa_private_key = PEM_read_PrivateKey(fd, NULL, NULL, "password");
  448. fclose(fd);
  449. fd = fopen("cert.pem", "r");
  450. X509 *cert = PEM_read_X509(fd, NULL, NULL, NULL);
  451. fclose(fd);
  452. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  453. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  454. || soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0))
  455. ... // an error occurred
  456. else if (soap_call_ns__myMethod(soap, ...))
  457. ... // a transmission error occurred
  458. @endcode
  459. The private key and its certificate are often placed in the same file, see e.g.
  460. server.pem in the package.
  461. To summarize the signing process:
  462. -# Register the wsse plugin.
  463. -# Obtain an HMAC secret key or a DSA or RSA private key.
  464. -# For DSA or RSA, obtain the X509 certificate with the public key signed by a
  465. certificate authority.
  466. -# Add the X509 certificate as a BinarySecurityToken to the header.
  467. -# Add a KeyInfo BinarySecurityTokenReference.
  468. -# Invoke @ref soap_wsse_sign or @ref soap_wsse_sign_body to sign the message.
  469. -# Always check the function return values for errors. You don't want to
  470. produce and accept messages with an invalid Security headers.
  471. @subsection wsse_8_2b Signing Message Parts
  472. The @ref soap_wsse_sign_body function signs the entire SOAP body. If it is
  473. desirable to sign individual parts of a message the @ref soap_wsse_sign
  474. function should be used. All message parts with wsu:Id attributes are signed.
  475. These message parts should not be nested (nested elements will not be
  476. separately signed). By default, all and only those XML elements with wsu:Id
  477. attributes are signed. Therefore, the wsu:Id attribute values used in a message
  478. must be unique within the message. Although usually not required, the default
  479. signing rule can be overridden with the @ref soap_wsse_sign_only function, see
  480. @ref wsse_8_3.
  481. For example, consider a transaction in which we only want to sign a contract in
  482. the SOAP Body. This allows us to modify the rest of the message or extract the
  483. contract in XML and pass it on with the signature.
  484. The gSOAP header file includes a myContract declaration:
  485. @code
  486. struct ns__myContract
  487. { @char* wsu__Id = "Contract";
  488. char* name;
  489. char* title;
  490. char* terms;
  491. };
  492. int ns__myMethod(struct ns__myContract agreement, bool* accepted);
  493. @endcode
  494. The default value of the wsu:Id is "Contract" so that we can instantiate the
  495. struct, automatically sign it, and send it as follows:
  496. @code
  497. struct ns__myContract contract;
  498. bool accept;
  499. soap_default_ns__myContract(soap, &contract);
  500. contract.name = ...;
  501. contract.title = ...;
  502. contract.terms = ...;
  503. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  504. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  505. || soap_wsse_sign(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0))
  506. ... // an error occurred
  507. else if (soap_call_ns__myMethod(soap, contract, &accept))
  508. ... // a transmission error occurred
  509. @endcode
  510. The above example shows a wsu:Id attribute embedded (hardcoded) in a struct.
  511. When it is not possible to add the wsu__Id member, for example when the type is
  512. a string instead of a struct, it is suggested to specify the XML element to be
  513. signed with the @ref soap_wsse_set_wsu_id(soap, "space-separated string of
  514. element names") function. Use it before each call or in the server operation
  515. (when returning XML data from a service operation). This lets the engine add
  516. wsu:Id="tag" attribute-value pair to the element's tag name. For example:
  517. @code
  518. soap_wsse_set_wsu_id(soap, "ns:myContract"); // <ns:myContract wsu:Id="ns:myContract">...
  519. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  520. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  521. || soap_wsse_sign(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0))
  522. ... // an error occurred
  523. soap_wsse_set_wsu_id(soap, NULL);
  524. @endcode
  525. This code adds the wsu:Id="ns-myContract" to the ns:myContract element. Here,
  526. the wsu__Id value in the struct MUST NOT be set. Otherwise, two wsu:Id
  527. attributes are present which is invalid. Also, the element signed must be
  528. unique in the message. That is, there cannot be more than one matching element,
  529. otherwise the resulting signature is invalid.
  530. Note: to reset the automatic wsu:Id attributes addition, pass NULL to
  531. @ref soap_wsse_set_wsu_id as shown above. This is automatically performed when
  532. a new message is received (but not automatically in a sequence of one-way sends
  533. for example).
  534. WARNING:
  535. When signing parts of the body as outlined above, use @ref soap_wsse_sign
  536. (do NOT use @ref soap_wsse_sign_body).
  537. WARNING:
  538. Do not attempt to sign an element with a wsu:Id that is a subelement of another
  539. element with a wsu:Id, that is, do not sign inner nested wsu:Id elements. The
  540. element that you will try to sign will not be canonicalized and will lead to a
  541. failure of the signature verification. When elements with wsu:Id are nested,
  542. sign the outermost element.
  543. We recommend to sign the entire SOAP Body using soap_wsse_sign_body and
  544. reserve the use of soap_wsse_set_wsu_id for SOAP Header elements, such as
  545. WS-Addressing elements. For example:
  546. @code
  547. #include "wsaapi.h"
  548. ...
  549. soap_wsa_request(soap, RequestMessageID, ToAddress, RequestAction);
  550. soap_wsse_set_wsu_id(soap, "wsa5:To wsa5:From wsa5:ReplyTo wsa5:Action");
  551. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  552. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  553. || soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0))
  554. ... // an error occurred
  555. else if (soap_call_ns__myMethod(soap, ...))
  556. ... // a transmission error occurred
  557. soap_wsse_set_wsu_id(soap, NULL);
  558. @endcode
  559. This code signs the wsa5:To and wsa5:Action SOAP header elements (set with
  560. soap_wsa_request, see the WS-Addressing "wsa" API in the gSOAP documentation
  561. for more information on the use of WS-Addressing). It is fine to specify more
  562. elements with @ref soap_wsse_set_wsu_id than actually present in the XML
  563. payload. The other WS-Addressing headers are not present and are not signed.
  564. WARNING:
  565. @ref soap_wsse_set_wsu_id should only be set once for each @ref soap_wsse_sign
  566. or @ref soap_wsse_sign_body. Each new call overrides the previous setting.
  567. WARNING:
  568. Never use @ref soap_wsse_set_wsu_id to set the wsu:Id for an element that
  569. occurs more than once in the payload, since each will have the same wsu:Id
  570. attribute that may lead to a WS-Signature failure.
  571. @subsection wsse_8_3 Signing Tokens
  572. To sign security tokens such as user names, passwords, and binary security
  573. tokens, just assign their Id values with a unique string, such as "Time" for
  574. timestamps and "User" for user names. For example:
  575. @code
  576. soap_wsse_add_Timestamp(soap, "Time", 600);
  577. soap_wsse_add_UsernameTokenDigest(soap, "User", "username", "password");
  578. ... // the rest of the signing code
  579. @endcode
  580. Note that by default all wsu:Id-attributed elements are signed. To filter a
  581. subset of wsu:Id-attributed elements for signatures, use the
  582. @ref soap_wsse_sign_only function as follows:
  583. @code
  584. soap_wsse_add_UsernameTokenDigest(soap, "User", "username", "password");
  585. soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert);
  586. soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token");
  587. soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0);
  588. soap_wsse_sign_only(soap, "User Body");
  589. @endcode
  590. Note that in the above we MUST set the X509Token name for cross-referencing
  591. with a wsu:Id, which normally results in automatically signing that token
  592. unless filtered out with @ref soap_wsse_sign_only. The SOAP Body wsu:Id is
  593. always "Body" and should be part of the @ref soap_wsse_sign_only set of wsu:Id
  594. names to sign.
  595. When using @ref soap_wsse_set_wsu_id we need to use the tag name with
  596. @ref soap_wsse_sign_only. For example:
  597. @code
  598. soap_wsa_request(soap, RequestMessageID, ToAddress, RequestAction);
  599. soap_wsse_set_wsu_id(soap, "wsa5:To wsa5:From wsa5:ReplyTo wsa5:Action");
  600. soap_wsse_add_UsernameTokenDigest(soap, "User", "username", "password");
  601. soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert);
  602. soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token");
  603. soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0);
  604. soap_wsse_sign_only(soap, "wsa5:To wsa5:From wsa5:ReplyTo wsa5:Action User Body");
  605. @endcode
  606. Note: @ref soap_wsse_sign_only should only be set once for each @ref
  607. soap_wsse_sign or @ref soap_wsse_sign_body. Each new call overrides the
  608. previous.
  609. Note: to reset the filtering of signed tokens and elements, pass NULL to
  610. @ref soap_wsse_sign_only. This is automatically performed when a new message is
  611. received (but not automatically in a sequence of one-way sends for example).
  612. @subsection wsse_8_4 Signature Validation
  613. To automatically verify the signature of an inbound message signed with DSA or
  614. RSA algorithms, assuming the message contains the X509 certificate as a binary
  615. security token, use:
  616. @code
  617. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  618. soap_register_plugin(soap, soap_wsse);
  619. soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
  620. soap->cafile = "cacerts.pem"; // file with CA certs of peers
  621. soap->capath = "dir/to/certs"; // and/or point to CA certs
  622. soap->crlfile = "revoked.pem"; // use CRL (optional)
  623. // server:
  624. if (soap_serve(soap))
  625. ... // an error occurred
  626. // client:
  627. if (soap_call_ns__myMethod(soap, ...))
  628. ... // an error occurred
  629. @endcode
  630. All locally referenced and signed elements in the signed message will be
  631. verified with @ref soap_wsse_verify_auto using the default settings set with
  632. SOAP_SMD_NONE. Elements that are not signed cannot be verified. Also elements
  633. referenced with absolute URIs that are not part of the message are not
  634. automatically verified. The received message is stored in a DOM accessible with
  635. soap->dom. This enables further analysis of the message content.
  636. For a post-parsing check to verify if an XML element was signed in an inbound
  637. message, use:
  638. @code
  639. soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
  640. ... // client call
  641. if (soap_wsse_verify_element(soap, "namespaceURI", "tag") > 0)
  642. ... // at least one element with matching tag and namespace is signed
  643. @endcode
  644. The signed element nesting rules are obeyed, so if the matching element is a
  645. descendent of a signed element, it is signed as well.
  646. Because it is a post check, a client should invoke @ref soap_wsse_verify_element
  647. after the call completed. A service should invoke this function within the
  648. service operation routine, i.e. when the message request is accepted and about
  649. to be processed.
  650. For example, to check whether the wsu:Timestamp element was signed (assuming it is present and message expiration checked with @ref soap_wsse_verify_Timestamp), use @ref soap_wsse_verify_element(soap, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Timestamp").
  651. To check the SOAP Body (either using SOAP 1.1 or 1.2), simply use @ref
  652. soap_wsse_verify_body.
  653. The @ref soap_wsse_verify_auto function keeps processing signed (and unsigned)
  654. messages as they arrive. For unsigned messages this can be expensive and the
  655. verification engine should be shut down using @ref soap_wsse_verify_done.
  656. There can be two problems with signature verification. First, some
  657. WS-Security implementations include SignedInfo/Reference/@URI without targeting
  658. an element, which will produce an error that a Reference URI target does not
  659. exist. Second, certificates provided by the peer are not verifiable unless the
  660. signing CA certificate is included in the cafile or capath. To disable
  661. certificate verification set the fsslverify callback:
  662. @code
  663. static int ssl_verify(int ok, X509_STORE_CTX *store)
  664. { // put certificate verification here, return 0 when fails 1 when ok
  665. return 1;
  666. }
  667. ...
  668. soap_wsse_verify_auto(soap, SOAP_SMD_NONE | SOAP_WSSE_IGNORE_EXTRA_REFS, NULL, 0);
  669. soap->fsslverify = ssl_verify;
  670. @endcode
  671. To verify the HMAC signature of an inbound message, the HMAC key must be
  672. supplied:
  673. @code
  674. static char hmac_key[16] = // the same secret key that was used to sign
  675. { 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88,
  676. 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00 };
  677. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  678. soap_register_plugin(soap, soap_wsse);
  679. soap_wsse_verify_auto(soap, SOAP_SMD_HMAC_SHA1, hmac_key, sizeof(hmac_key));
  680. // server:
  681. if (soap_serve(soap))
  682. ... // an error occurred
  683. // client:
  684. if (soap_call_ns__myMethod(soap, ...))
  685. ... // an error occurred
  686. @endcode
  687. To summarize the signature verification process:
  688. -# Register the wsse plugin.
  689. -# For HMAC, obtain the HMAC secret key
  690. -# Use @ref soap_wsse_verify_auto to verify inbound messages.
  691. -# Set the cafile (or capath) to verify certificates of the peers and crlfile
  692. (optional)
  693. -# After receiving a message, the DOM in soap->dom can be traversed for further analysis.
  694. -# Always check the function return values for errors. You don't want to accept
  695. a request or response message with an invalid Security header.
  696. -# Use @ref soap_wsse_verify_done to terminate verification, e.g. to consume
  697. plain messages more efficiently.
  698. @section wsse_9 Encryption
  699. The material in this section relates to the WS-Security specification section 9.
  700. The wsse plugin must be registered:
  701. @code
  702. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  703. soap_register_plugin(soap, soap_wsse);
  704. @endcode
  705. Other flags to consider:
  706. - SOAP_IO_CHUNK for HTTP chunked content to stream messages.
  707. - SOAP_ENC_GZIP for HTTP compression (also enables HTTP chunking).
  708. @subsection wsse_9_1 Encrypting Messages
  709. Encryption should be used in combination with signing. A signature ensures
  710. message integrity while encryption ensures confidentially. Encrypted messages
  711. can be tampered with unless integrity is ensured. Therefore, Section
  712. @ref wsse_8 should be followed to sign and verify message content.
  713. Messages are encrypted using either public key cryptography or a symmetric
  714. secret key. A symmetric secret key should only be shared between the sender and
  715. receiver (or any trusted communicating peer).
  716. Encryption with public key cryptography uses an "envelope" process, where the
  717. public key of the recipient is used to encrypt a temporary (ephemeral) secret
  718. key that is sent together with the secret key-encrypted message to the
  719. recipient. The recipient decrypts the ephemeral key and uses it to decrypt the
  720. message. The public key is usually part of a X509 certificate. The public key
  721. (containing the subject information) is added to the WS-Security header and
  722. used for encryption of the SOAP Body as follows:
  723. @code
  724. X509 *cert = ...; //
  725. if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, NULL, NULL))
  726. soap_print_fault(soap, stderr);
  727. @endcode
  728. SOAP_MEC_ENV_ENC_DES_CBC specifies envelope encoding with triple DES CBC and
  729. PKCS1 RSA-1_5. Use SOAP_MEC_ENV_ENC_AES256_CBC for AES256 with RSA-OAEP. The
  730. "Cert" parameter is a unique URI to reference the key from the encrypted SOAP
  731. Body. The above enables the encryption engine for the next message to be sent,
  732. either at the client or server side. The server should use this withing a
  733. server operation (before returning) to enable the service operation response to
  734. be encrypted.
  735. To include a subject key ID in the WS-Security header instead of the entire
  736. public key, specify the subject key ID parameter:
  737. @code
  738. X509 *cert = ...; //
  739. if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, "Subject Key ID", NULL, NULL))
  740. soap_print_fault(soap, stderr);
  741. @endcode
  742. The difference with the previous example where no subject key ID was specified
  743. is that the WS-Security header only contains the subject key ID and no longer
  744. the public key in base64 format.
  745. To exclude the encrypted key certificate from the message and include a X509Data element with
  746. IssuerName and SerialNumber:
  747. @code
  748. X509 *cert = ...;
  749. if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, "CN=Root Agency", "-79441640260855276448009124614332182350"))
  750. soap_print_fault(soap, stderr);
  751. @endcode
  752. The issuer name and serial number (must be in decimal for
  753. soap_wsse_add_EncryptedKey) of a certificate can be obtained as follows:
  754. @code
  755. X509 *cert = ...;
  756. BIGNUM *bn = BN_new();
  757. char issuer[256], *serial;
  758. X509_NAME_oneline(X509_get_issuer_name(cert), issuer, sizeof(issuer));
  759. ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), bn);
  760. serial = BN_bn2dec(bn);
  761. OPENSSL_free(bn);
  762. ...
  763. if (soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, issuer+1, serial))
  764. soap_print_fault(soap, stderr);
  765. ...
  766. OPENSSL_free(serial);
  767. @code
  768. Note that in the above code the leading slash in "/CN=Root Agency" is excluded from the issuer name.
  769. When excluding the encrypted key certificate from the message, the token
  770. handler callback must be provided on the receiving end to obtain the
  771. certificate that corresponds to the issuer name and serial number. For example:
  772. @code
  773. soap_register_plugin_arg(soap, soap_wsse, security_token_handler);
  774. static const void *token_handler(struct soap *soap, int alg, const char *keyname, int *keylen)
  775. { struct ds__X509IssuerSerialType *issuer;
  776. switch (alg)
  777. { case SOAP_SMD_VRFY_DSA_SHA1:
  778. case SOAP_SMD_VRFY_RSA_SHA1:
  779. case SOAP_SMD_VRFY_RSA_SHA256:
  780. case SOAP_SMD_VRFY_RSA_SHA512:
  781. issuer = soap_wsse_get_KeyInfo_SecurityTokenReferenceX509Data(soap);
  782. if (issuer)
  783. {
  784. if (!strcmp(issuer->X509IssuerName, clt_issuer)
  785. && !strcmp(issuer->X509SerialNumber, clt_serial))
  786. return (const void*)clt_cert;
  787. if (!strcmp(issuer->X509IssuerName, srv_issuer)
  788. && !strcmp(issuer->X509SerialNumber, srv_serial))
  789. return (const void*)srv_cert;
  790. }
  791. break;
  792. ...
  793. @endcode
  794. To encrypt specific elements of the SOAP Body rather than the entire SOAP Body,
  795. use @ref soap_wsse_add_EncryptedKey_encrypt_only in combination with
  796. @ref soap_wsse_set_wsu_id as follows:
  797. @code
  798. X509 *cert = ...;
  799. // the SOAP Body contains one <ns:myContract> and one <ns:myPIN> (not nested)
  800. soap_wsse_set_wsu_id(soap, "ns:myContract ns:myPIN");
  801. if (soap_wsse_add_EncryptedKey_encrypt_only(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, NULL, NULL, "ns:myContract ns:myPIN"))
  802. soap_print_fault(soap, stderr);
  803. @endcode
  804. To encrypt the SOAP Body and SOAP Header element(s), such as ds:Signature, use
  805. "SOAP-ENV:Body" with @ref soap_wsse_add_EncryptedKey_encrypt_only:
  806. @code
  807. X509 *cert = ...;
  808. soap_wsse_set_wsu_id(soap, "ds:Signature");
  809. if (soap_wsse_add_EncryptedKey_encrypt_only(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, NULL, NULL, "ds:Signature SOAP-ENV:Body"))
  810. soap_print_fault(soap, stderr);
  811. @endcode
  812. WARNING:
  813. - The @ref soap_wsse_set_wsu_id MUST be used to specify all element tag names
  814. to encrypt. Additional elements MAY be specified in @ref soap_wsse_set_wsu_id
  815. (for example elements to digitally sign).
  816. - The elements to encrypt MUST occur EXACTLY ONCE in the SOAP Body.
  817. For symmetric encryption with a shared secret key, generate a 160-bit triple
  818. DES key and make sure both the sender and reciever can use the key without it
  819. being shared by any other party (key exchange problem). Then use the
  820. @ref soap_wsse_encrypt_body function to encrypt the SOAP Body as follows:
  821. @code
  822. char des_key[20] = ...; // 20-byte (160-bit) DES shared secret key
  823. if (soap_wsse_encrypt_body(soap, SOAP_MEC_ENC_DES_CBC, des_key, sizeof(des_key)))
  824. soap_print_fault(soap, stderr);
  825. @endcode
  826. Triple DES can be selected as above, but also AES128, AES256, or AES512, for
  827. example:
  828. @code
  829. char aes256_key[32] = ...; // 32-byte (256-bit) AES256 shared secret key
  830. if (soap_wsse_encrypt_body(soap, SOAP_MEC_ENC_AES256_CBC, aes256_key, sizeof(aes256_key)))
  831. soap_print_fault(soap, stderr);
  832. @endcode
  833. To symmetrically encrypt specific elements of the SOAP Body rather than the
  834. entire SOAP Body, use @ref soap_wsse_encrypt_only in combination with
  835. @ref soap_wsse_set_wsu_id as follows:
  836. @code
  837. char des_key[20] = ...; // 20-byte (160-bit) secret key
  838. // the SOAP Body contains one <ns:myContract> and one <ns:myPIN> (not nested)
  839. soap_wsse_set_wsu_id(soap, "ns:myContract ns:myPIN");
  840. if (soap_wsse_encrypt_only(soap, SOAP_MEC_ENC_DES_CBC, des_key, sizeof(des_key), "ns:myContract ns:myPIN"))
  841. soap_print_fault(soap, stderr);
  842. @endcode
  843. WARNING:
  844. - The @ref soap_wsse_set_wsu_id MUST be used to specify all element tag names
  845. to encrypt. Additional elements MAY be specified in @ref soap_wsse_set_wsu_id
  846. (for example elements to digitally sign).
  847. - The elements to encrypt MUST occur EXACTLY ONCE in the SOAP Body.
  848. @subsection wsse_9_2 Decrypting Message Parts
  849. The wsse engine automatically decrypts message parts, but requires a private
  850. key or secret shared key to do so. A default key can be given to enable
  851. decryption, but it will fail if a non-compatible key was used for encryption.
  852. In that case a token handler callback should be defined by the user to select a
  853. proper decryption key based on the available subject key name or identifier
  854. embedded in the encrypted message.
  855. Here is an example of a token handler callback:
  856. @code
  857. soap_register_plugin_arg(soap, soap_wsse, security_token_handler);
  858. const void *security_token_handler(struct soap *soap, int alg, const char *keyname, int *keylen)
  859. { // Note: 'keyname' argument may be used with shared secret key
  860. // decryption where the keyname is from the ds:KeyInfo/KeyName content
  861. if (keyname)
  862. { ... lookup keyname ...
  863. const void *key = ...;
  864. keylen = ...;
  865. *alg = ...;
  866. return key;
  867. }
  868. // Get the user name from UsernameToken in message
  869. const char *uid = soap_wsse_get_Username(soap);
  870. switch (*alg)
  871. { case SOAP_SMD_VRFY_DSA_SHA1:
  872. case SOAP_SMD_VRFY_RSA_SHA1:
  873. case SOAP_SMD_VRFY_RSA_SHA256:
  874. case SOAP_SMD_VRFY_RSA_SHA512:
  875. if (uid)
  876. { // Lookup uid to retrieve the X509 certificate to verify the signature
  877. const X509 *cert = ...;
  878. return (const void*)cert;
  879. }
  880. return NULL; // no certificate: fail
  881. case SOAP_SMD_HMAC_SHA1:
  882. if (uid)
  883. { // Lookup uid to retrieve the HMAC key to verify the signature
  884. const void *key = ...;
  885. *alg = ...;
  886. *keylen = ...;
  887. return key;
  888. }
  889. return NULL; // no certificate: fail
  890. case SOAP_MEC_ENV_DEC_DES_CBC:
  891. case SOAP_MEC_ENV_DEC_AES128_CBC:
  892. case SOAP_MEC_ENV_DEC_AES256_CBC:
  893. case SOAP_MEC_ENV_DEC_AES256_CBC:
  894. // return decryption private key associated with keyname
  895. case SOAP_MEC_DEC_DES_CBC:
  896. case SOAP_MEC_DEC_AES128_CBC:
  897. case SOAP_MEC_DEC_AES256_CBC:
  898. case SOAP_MEC_DEC_AES512_CBC:
  899. // *keylen = ...
  900. // return decryption shared secret key associated with keyname
  901. }
  902. return NULL; // fail
  903. }
  904. @endcode
  905. The last two arms are used to return a private key associated with the keyname
  906. paramater, which is a string that contains the subject key id from the public
  907. key information in an encrypted message or the subject key ID string that was
  908. set with @ref soap_wsse_add_EncryptedKey at the sender side.
  909. To set the default private key for envelope decryption, use:
  910. @code
  911. EVP_PKEY *rsa_private_key = ...;
  912. soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_private_key, 0);
  913. @endcode
  914. Or to set the default shared secret key for symmetric decryption, use:
  915. @code
  916. char des_key[20] = ...; // 20-byte (160-bit) triple DES key
  917. soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_DES_CBC, des_key, sizeof(des_key));
  918. @endcode
  919. The above assumes that triple DES is used, but you can select AES128, AES256,
  920. or AES512:
  921. @code
  922. char aes256_key[32] = ...; // 32-byte (256-bit) AES256 key
  923. soap_wsse_decrypt_auto(soap, SOAP_MEC_DEC_AES256_CBC, aes256_key, sizeof(aes256_key));
  924. @endcode
  925. If a default key is not set, the token handler callback should be used as
  926. discussed above in this section. Do NOT set a default key if a token handler is
  927. used to handle multiple different keys. The default key mechanism is simpler to
  928. use when only one decryption key is used to decrypt all encrypted messages.
  929. To remove the default key, use:
  930. @code
  931. soap_wsse_decrypt_auto(soap, SOAP_MEC_NONE, NULL, 0);
  932. @endcode
  933. @subsection wsse_9_3 Example Combining Signing with Encryption/Decryption
  934. Here is an client-side example to use signatures and encryption for the
  935. outbound service request message and verification and decryption of the inbound
  936. response message:
  937. @code
  938. FILE *fd;
  939. EVP_PKEY *rsa_private_key;
  940. X509 *cert;
  941. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  942. soap_register_plugin(soap, soap_wsse);
  943. soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
  944. fd = fopen("privkey.pem", "r");
  945. rsa_private_key = PEM_read_PrivateKey(fd, NULL, NULL, "password");
  946. fclose(fd);
  947. soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_private_key, 0);
  948. fd = fopen("cert.pem", "r");
  949. X509 *cert = PEM_read_X509(fd, NULL, NULL, NULL);
  950. fclose(fd);
  951. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  952. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  953. || soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, NULL, NULL)
  954. || soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0)
  955. ... // an error occurred
  956. else if (soap_call_ns__myMethod(soap, ...))
  957. ... // a transmission error occurred
  958. ...
  959. EVP_PKEY_free(rsa_private_key);
  960. X509_free(cert);
  961. @endcode
  962. The server-side service operation is as follows:
  963. @code
  964. FILE *fd;
  965. EVP_PKEY *rsa_private_key;
  966. X509 *cert;
  967. struct soap *soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  968. soap_register_plugin(soap, soap_wsse);
  969. soap_wsse_verify_auto(soap, SOAP_SMD_NONE, NULL, 0);
  970. fd = fopen("privkey.pem", "r");
  971. rsa_private_key = PEM_read_PrivateKey(fd, NULL, NULL, "password");
  972. fclose(fd);
  973. soap_wsse_decrypt_auto(soap, SOAP_MEC_ENV_DEC_DES_CBC, rsa_private_key, 0);
  974. fd = fopen("cert.pem", "r");
  975. X509 *cert = PEM_read_X509(fd, NULL, NULL, NULL);
  976. fclose(fd);
  977. ...
  978. if (soap_serve(soap))
  979. { soap_wsse_delete_Security(soap);
  980. soap_print_fault(soap, stderr);
  981. }
  982. ...
  983. EVP_PKEY_free(rsa_private_key);
  984. X509_free(cert);
  985. @endcode
  986. where an example service operation could be:
  987. @code
  988. int ns__myMethod(struct soap *soap, ...)
  989. { ...
  990. soap_wsse_delete_Security(soap);
  991. if (soap_wsse_add_BinarySecurityTokenX509(soap, "X509Token", cert)
  992. || soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(soap, "#X509Token")
  993. || soap_wsse_add_EncryptedKey(soap, SOAP_MEC_ENV_ENC_DES_CBC, "Cert", cert, NULL, NULL, NULL)
  994. || soap_wsse_sign_body(soap, SOAP_SMD_SIGN_RSA_SHA256, rsa_private_key, 0)
  995. return soap->error;
  996. return SOAP_OK;
  997. }
  998. @endcode
  999. The service operation signs the message using a private key and encrypts the
  1000. response message using a public key (from the certificate).
  1001. @section wsse_10 Security Timestamps
  1002. The material in this section relates to the WS-Security specification section
  1003. 10.
  1004. To add a timestamp with the creation time to the Security header, use:
  1005. @code
  1006. soap_wsse_add_Timestamp(soap, NULL, 0); // no expiration
  1007. @endcode
  1008. The lifetime of a message (in seconds) is passed as the third argument, which
  1009. will be displayed as the timestamp expiration time:
  1010. @code
  1011. soap_wsse_add_Timestamp(soap, NULL, 10); // 10 seconds lifetime
  1012. @endcode
  1013. Timestamps, like other header elements, are not automatically secured with a
  1014. digital signature. To secure a timestamp, we add an identifier (wsu:Id) to each
  1015. element we want the WS-Security plugin to sign thereby making it impossible for
  1016. someone to tamper with that part of the message. To do this for the timestamp,
  1017. we simply pass a unique identification string as the second argument:
  1018. @code
  1019. soap_wsse_add_Timestamp(soap, "Time", 10); // timestamp will be signed
  1020. @endcode
  1021. @section wsse_11 WS-Security and HTTPS
  1022. HTTPS is used at the client side with the usual "https:" URL addressing, shown
  1023. here with the registration of the wsse plugin and setting up locks for
  1024. thread-safe use of SSL for HTTPS:
  1025. @code
  1026. #include "wsseapi.h"
  1027. #include "threads.h"
  1028. struct soap *soap;
  1029. if (CRYPTO_thread_setup())
  1030. ... // error
  1031. soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  1032. soap_register_plugin(soap, soap_wsse);
  1033. if (soap_ssl_client_context(&soap,
  1034. SOAP_SSL_DEFAULT, // requires server authentication
  1035. NULL, // keyfile for client authentication to server
  1036. NULL, // the keyfile password
  1037. "cacerts.pem", // cafile CA certificates to authenticate the server
  1038. NULL, // capath CA directory path to certificates
  1039. NULL
  1040. ))
  1041. ... // error
  1042. soap->cafile = "cacerts.pem"; // same as above (or overrides the above)
  1043. soap->capath = "dir/to/certs"; // and/or point to CA certs
  1044. soap->crlfile = "revoked.pem"; // use CRL (optional)
  1045. ... // set up WS-Security for signatures/encryption etc
  1046. if (soap_call_ns__myMethod(soap, "https://...", ...))
  1047. ... // error
  1048. ... // process response results
  1049. soap_destroy(soap);
  1050. soap_end(soap);
  1051. soap_free(soap);
  1052. CRYPTO_thread_cleanup();
  1053. @endcode
  1054. The CRYPTO threads should be set up before any threads are created.
  1055. The soap_ssl_client_context only needs to be set up once. Use the following
  1056. flags:
  1057. - SOAP_SSL_DEFAULT requires server authentication, CA certs should be used
  1058. - SOAP_SSL_NO_AUTHENTICATION disables server authentication
  1059. - SOAP_SSL_SKIP_HOST_CHECK disables server authentication host check
  1060. The server uses the following:
  1061. @code
  1062. #include "wsseapi.h"
  1063. #include "threads.h"
  1064. SOAP_SOCKET m, s;
  1065. int port = 443;
  1066. struct soap *soap;
  1067. if (CRYPTO_thread_setup())
  1068. ... // error
  1069. soap = soap_new1(SOAP_XML_CANONICAL | SOAP_XML_INDENT);
  1070. soap_register_plugin(soap, soap_wsse);
  1071. if (soap_ssl_server_context(&soap,
  1072. SOAP_SSL_DEFAULT, // requires server to authenticate, but not the client
  1073. server.pem, // keyfile for authentication to client
  1074. "password", // the keyfile password
  1075. NULL, // CA certificates to authenticate the client
  1076. NULL, // CA directory path to certificates
  1077. NULL, // use RSA 2048 bits (or give file name with DH param)
  1078. NULL,
  1079. NULL
  1080. ))
  1081. ... // error
  1082. if (!soap_valid_socket(m = soap_bind(soap, NULL, port, 100))
  1083. ... // error
  1084. for (;;)
  1085. { if (!soap_valid_socket(s = soap_accept(soap)))
  1086. ... // error
  1087. THREAD_CREATE(&tid, (void*(*)(void*))&process_request, soap_copy(soap));
  1088. }
  1089. soap_destroy(soap);
  1090. soap_end(soap);
  1091. soap_free(soap);
  1092. CRYPTO_thread_cleanup();
  1093. @endcode
  1094. where we define a process_request function that is executed by the thread to
  1095. process the request (on a copy of the soap context struct):
  1096. @code
  1097. void *process_request(struct soap *soap)
  1098. { ... // set up WS-Security for signatures/encryption etc
  1099. if (soap_ssl_accept(soap)
  1100. || soap_serve(soap))
  1101. ... // error
  1102. soap_destroy(soap);
  1103. soap_end(soap);
  1104. soap_free(soap);
  1105. }
  1106. @endcode
  1107. The soap_ssl_server_context only needs to be set up once. Use the following
  1108. flags:
  1109. - SOAP_SSL_DEFAULT requires server authentication, but no client authentication
  1110. - SOAP_SSL_REQUIRE_CLIENT_AUTHENTICATION requires client authentication
  1111. We need to define the thread set up and clean up operations as follows:
  1112. @code
  1113. struct CRYPTO_dynlock_value
  1114. { MUTEX_TYPE mutex;
  1115. };
  1116. static MUTEX_TYPE *mutex_buf;
  1117. static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
  1118. { struct CRYPTO_dynlock_value *value;
  1119. value = (struct CRYPTO_dynlock_value*)malloc(sizeof(struct CRYPTO_dynlock_value));
  1120. if (value)
  1121. MUTEX_SETUP(value->mutex);
  1122. return value;
  1123. }
  1124. static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
  1125. { if (mode & CRYPTO_LOCK)
  1126. MUTEX_LOCK(l->mutex);
  1127. else
  1128. MUTEX_UNLOCK(l->mutex);
  1129. }
  1130. static void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line)
  1131. { MUTEX_CLEANUP(l->mutex);
  1132. free(l);
  1133. }
  1134. void locking_function(int mode, int n, const char *file, int line)
  1135. { if (mode & CRYPTO_LOCK)
  1136. MUTEX_LOCK(mutex_buf[n]);
  1137. else
  1138. MUTEX_UNLOCK(mutex_buf[n]);
  1139. }
  1140. unsigned long id_function()
  1141. { return (unsigned long)THREAD_ID;
  1142. }
  1143. int CRYPTO_thread_setup()
  1144. { int i;
  1145. mutex_buf = (MUTEX_TYPE*)malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  1146. if (!mutex_buf)
  1147. return SOAP_EOM;
  1148. for (i = 0; i < CRYPTO_num_locks(); i++)
  1149. MUTEX_SETUP(mutex_buf[i]);
  1150. CRYPTO_set_id_callback(id_function);
  1151. CRYPTO_set_locking_callback(locking_function);
  1152. CRYPTO_set_dynlock_create_callback(dyn_create_function);
  1153. CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
  1154. CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
  1155. return SOAP_OK;
  1156. }
  1157. void CRYPTO_thread_cleanup()
  1158. { int i;
  1159. if (!mutex_buf)
  1160. return;
  1161. CRYPTO_set_id_callback(NULL);
  1162. CRYPTO_set_locking_callback(NULL);
  1163. CRYPTO_set_dynlock_create_callback(NULL);
  1164. CRYPTO_set_dynlock_lock_callback(NULL);
  1165. CRYPTO_set_dynlock_destroy_callback(NULL);
  1166. for (i = 0; i < CRYPTO_num_locks(); i++)
  1167. MUTEX_CLEANUP(mutex_buf[i]);
  1168. free(mutex_buf);
  1169. mutex_buf = NULL;
  1170. }
  1171. @endcode
  1172. For additional details and examples, see the user guide and examples in the
  1173. gSOAP package directory gsoap/samples/ssl.
  1174. @section wsse_12 Miscellaneous
  1175. The Security header block was generated from the WS-Security schema with the
  1176. wsdl2h tool and WS/WS-typemap.dat:
  1177. @code
  1178. > wsdl2h -cegxy -o wsse.h -t WS/WS-typemap.dat WS/wsse.xsd
  1179. @endcode
  1180. The same process was used to generate the header file ds.h from the XML digital
  1181. signatures core schema, and the xenc.h encryption schema:
  1182. @code
  1183. > wsdl2h -cuxy -o ds.h -t WS/WS-typemap.dat WS/ds.xsd
  1184. > wsdl2h -cuxy -o xenc.h -t WS/WS-typemap.dat WS/xenc.xsd
  1185. @endcode
  1186. The import/wsse.h file has the following definition for the Security header
  1187. block:
  1188. @code
  1189. typedef struct _wsse__Security
  1190. { struct _wsu__Timestamp* wsu__Timestamp;
  1191. struct _wsse__UsernameToken* UsernameToken;
  1192. struct _wsse__BinarySecurityToken* BinarySecurityToken;
  1193. struct xenc__EncryptedKeyType* xenc__EncryptedKey;
  1194. struct _xenc__ReferenceList* xenc__ReferenceList;
  1195. struct ds__SignatureType* ds__Signature;
  1196. @char* SOAP_ENV__actor;
  1197. @char* SOAP_ENV__role;
  1198. } _wsse__Security;
  1199. @endcode
  1200. The _wsse__Security header is modified by a WS/WS-typemap.dat mapping rule to
  1201. include additional details.
  1202. @section wsse_13 Encryption Limitations
  1203. - Individual encryption/decryption of simple content (CDATA content) with @ref
  1204. soap_wsse_add_EncryptedKey_encrypt_only IS NOT SUPPORTED. Encrypt the entire
  1205. SOAP Body or encrypt elements with complex content (complexType and
  1206. complexContent elements that have sub elements).
  1207. - Encryption is performed after signing (likewise, signatures are verified
  1208. after decryption). Signing after encryption is not supported.
  1209. @section wsse_wsc WS-SecureConversation
  1210. To use a WS-SecureConversation security context token (SCT) with WS-Security:
  1211. @code
  1212. const char *identifier = "...";
  1213. soap_wsse_add_SecurityContextToken(soap, "SCT", identifier);
  1214. @endcode
  1215. In this example a context has been established and the secret that is
  1216. identified by the 'identifier' string is known to both parties. This secret is
  1217. used to sign the message body. The "SCT" is a wsu:Id, which is used as a
  1218. reference to sign the token.
  1219. */
  1220. #include "wsseapi.h"
  1221. #include "smdevp.h"
  1222. #include "mecevp.h"
  1223. #include "threads.h" /* only need threads to enable mutex for MT */
  1224. #if defined(SOAP_WSA_2003) || defined(SOAP_WSA_2004) || defined(SOAP_WSA_200408) || defined(SOAP_WSA_2005)
  1225. #include "wsaapi.h"
  1226. #endif
  1227. #ifdef __cplusplus
  1228. extern "C" {
  1229. #endif
  1230. /** Plugin identification for plugin registry */
  1231. const char soap_wsse_id[14] = SOAP_WSSE_ID;
  1232. /** Maximum number of SignedInfo References */
  1233. #define SOAP_WSSE_MAX_REF (100)
  1234. /** Clock skew between machines (in sec) to fit message expiration in window */
  1235. #define SOAP_WSSE_CLKSKEW (300)
  1236. /** Size of the random nonce */
  1237. #define SOAP_WSSE_NONCELEN (20)
  1238. /** Digest authentication accepts messages that are not older than creation time + SOAP_WSSE_NONCETIME */
  1239. #define SOAP_WSSE_NONCETIME (SOAP_WSSE_CLKSKEW + 240)
  1240. /******************************************************************************\
  1241. *
  1242. * Common URIs
  1243. *
  1244. \******************************************************************************/
  1245. const char *wsse_PasswordTextURI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
  1246. const char *wsse_PasswordDigestURI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest";
  1247. const char *wsse_Base64BinaryURI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary";
  1248. const char *wsse_X509v3URI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
  1249. const char *wsse_X509v3SubjectKeyIdentifierURI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier";
  1250. const char *ds_sha1URI = "http://www.w3.org/2000/09/xmldsig#sha1";
  1251. const char *ds_sha256URI = "http://www.w3.org/2001/04/xmlenc#sha256";
  1252. const char *ds_sha512URI = "http://www.w3.org/2001/04/xmlenc#sha512";
  1253. const char *ds_hmac_sha1URI = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
  1254. const char *ds_hmac_sha256URI = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
  1255. const char *ds_hmac_sha512URI = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
  1256. const char *ds_dsa_sha1URI = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
  1257. const char *ds_rsa_sha1URI = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
  1258. const char *ds_rsa_sha256URI = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
  1259. const char *ds_rsa_sha512URI = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
  1260. const char *xenc_rsa15URI = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
  1261. const char *xenc_rsaesURI = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
  1262. const char *xenc_3desURI = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
  1263. const char *xenc_aes128URI = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
  1264. const char *xenc_aes192URI = "http://www.w3.org/2001/04/xmlenc#aes192-cbc";
  1265. const char *xenc_aes256URI = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
  1266. const char *xenc_aes512URI = "http://www.w3.org/2001/04/xmlenc#aes512-cbc";
  1267. const char *xenc_elementURI = "http://www.w3.org/2001/04/xmlenc#Element";
  1268. const char *xenc_contentURI = "http://www.w3.org/2001/04/xmlenc#Content";
  1269. const char *ds_URI = "http://www.w3.org/2000/09/xmldsig#";
  1270. const char *c14n_URI = "http://www.w3.org/2001/10/xml-exc-c14n#";
  1271. const char *wsu_URI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
  1272. /******************************************************************************\
  1273. *
  1274. * Digest authentication session
  1275. *
  1276. \******************************************************************************/
  1277. /**
  1278. @struct soap_wsse_session
  1279. @brief Digest authentication session data
  1280. */
  1281. struct soap_wsse_session
  1282. { struct soap_wsse_session *next; /**< Next session in list */
  1283. time_t expired; /**< Session expiration */
  1284. char hash[SOAP_SMD_SHA1_SIZE]; /**< SHA1 digest */
  1285. char nonce[1]; /**< Nonce string flows into region below this struct */
  1286. };
  1287. /** The digest authentication session database */
  1288. static struct soap_wsse_session *soap_wsse_session = NULL;
  1289. /** Lock for digest authentication session database exclusive access */
  1290. static MUTEX_TYPE soap_wsse_session_lock = MUTEX_INITIALIZER;
  1291. static char* soap_wsse_ids(struct soap *soap, const char *tags);
  1292. static int soap_wsse_session_verify(struct soap *soap, const char hash[SOAP_SMD_SHA1_SIZE], const char *created, const char *nonce);
  1293. static void soap_wsse_session_cleanup(struct soap *soap);
  1294. static void calc_digest(struct soap *soap, const char *created, const char *nonce, int noncelen, const char *password, char hash[SOAP_SMD_SHA1_SIZE]);
  1295. static void calc_nonce(struct soap *soap, char nonce[SOAP_WSSE_NONCELEN]);
  1296. static int soap_wsse_init(struct soap *soap, struct soap_wsse_data *data, const void *(*arg)(struct soap*, int*, const char*, int*));
  1297. static int soap_wsse_copy(struct soap *soap, struct soap_plugin *dst, struct soap_plugin *src);
  1298. static void soap_wsse_delete(struct soap *soap, struct soap_plugin *p);
  1299. static int soap_wsse_preparesend(struct soap *soap, const char *buf, size_t len);
  1300. static int soap_wsse_preparefinalsend(struct soap *soap);
  1301. static void soap_wsse_preparecleanup(struct soap *soap, struct soap_wsse_data *data);
  1302. static int soap_wsse_preparefinalrecv(struct soap *soap);
  1303. static int soap_wsse_header(struct soap *soap);
  1304. static int soap_wsse_element_begin_in(struct soap *soap, const char *tag);
  1305. static int soap_wsse_element_end_in(struct soap *soap, const char *tag1, const char *tag2);
  1306. static int soap_wsse_element_begin_out(struct soap *soap, const char *tag);
  1307. static int soap_wsse_element_end_out(struct soap *soap, const char *tag);
  1308. static size_t soap_wsse_verify_nested(struct soap *soap, struct soap_dom_element *dom, const char *URI, const char *tag);
  1309. /******************************************************************************\
  1310. *
  1311. * wsse:Security header element
  1312. *
  1313. \******************************************************************************/
  1314. /**
  1315. @fn _wsse__Security* soap_wsse_add_Security(struct soap *soap)
  1316. @brief Adds Security header element.
  1317. @param soap context
  1318. @return _wsse__Security object
  1319. */
  1320. struct _wsse__Security*
  1321. soap_wsse_add_Security(struct soap *soap)
  1322. { DBGFUN("soap_wsse_add_Security");
  1323. /* if we don't have a SOAP Header, create one */
  1324. soap_header(soap);
  1325. /* if we don't have a wsse:Security element in the SOAP Header, create one */
  1326. if (!soap->header->wsse__Security)
  1327. { soap->header->wsse__Security = (_wsse__Security*)soap_malloc(soap, sizeof(_wsse__Security));
  1328. if (!soap->header->wsse__Security)
  1329. return NULL;
  1330. soap_default__wsse__Security(soap, soap->header->wsse__Security);
  1331. }
  1332. return soap->header->wsse__Security;
  1333. }
  1334. /**
  1335. @fn _wsse__Security* soap_wsse_add_Security_actor(struct soap *soap, const char *actor)
  1336. @brief Adds Security header element with actor or role attribute.
  1337. @param soap context
  1338. @param actor string
  1339. @return _wsse__Security object
  1340. */
  1341. struct _wsse__Security*
  1342. soap_wsse_add_Security_actor(struct soap *soap, const char *actor)
  1343. { _wsse__Security *security = soap_wsse_add_Security(soap);
  1344. DBGFUN1("soap_wsse_add_Security_actor", "actor=%s", actor);
  1345. if (soap->namespaces && !strcmp(soap->namespaces[0].ns, "http://schemas.xmlsoap.org/soap/envelope/"))
  1346. security->SOAP_ENV__actor = soap_strdup(soap, actor);
  1347. else
  1348. security->SOAP_ENV__role = soap_strdup(soap, actor);
  1349. return security;
  1350. }
  1351. /**
  1352. @fn void soap_wsse_delete_Security(struct soap *soap)
  1353. @brief Deletes Security header element.
  1354. @param soap context
  1355. */
  1356. void
  1357. soap_wsse_delete_Security(struct soap *soap)
  1358. { DBGFUN("soap_wsse_delete_Security");
  1359. if (soap->header)
  1360. soap->header->wsse__Security = NULL;
  1361. }
  1362. /**
  1363. @fn _wsse__Security* soap_wsse_Security(struct soap *soap)
  1364. @brief Returns Security header element if present.
  1365. @param soap context
  1366. @return _wsse__Security object or NULL
  1367. */
  1368. struct _wsse__Security*
  1369. soap_wsse_Security(struct soap *soap)
  1370. { if (soap->header)
  1371. return soap->header->wsse__Security;
  1372. return NULL;
  1373. }
  1374. /******************************************************************************\
  1375. *
  1376. * wsse:Security/ds:Signature header element
  1377. *
  1378. \******************************************************************************/
  1379. /**
  1380. @fn ds__SignatureType* soap_wsse_add_Signature(struct soap *soap)
  1381. @brief Adds Signature header element.
  1382. @param soap context
  1383. @return ds__SignatureType object
  1384. */
  1385. struct ds__SignatureType*
  1386. soap_wsse_add_Signature(struct soap *soap)
  1387. { _wsse__Security *security = soap_wsse_add_Security(soap);
  1388. DBGFUN("soap_wsse_add_Signature");
  1389. /* if we don't have a ds:Signature, create one */
  1390. if (!security->ds__Signature)
  1391. { security->ds__Signature = (ds__SignatureType*)soap_malloc(soap, sizeof(ds__SignatureType));
  1392. if (!security->ds__Signature)
  1393. return NULL;
  1394. soap_default_ds__SignatureType(soap, security->ds__Signature);
  1395. }
  1396. return security->ds__Signature;
  1397. }
  1398. /**
  1399. @fn void soap_wsse_delete_Signature(struct soap *soap)
  1400. @brief Deletes Signature header element.
  1401. @param soap context
  1402. */
  1403. void
  1404. soap_wsse_delete_Signature(struct soap *soap)
  1405. { _wsse__Security *security = soap_wsse_Security(soap);
  1406. DBGFUN("soap_wsse_delete_Signature");
  1407. if (security)
  1408. security->ds__Signature = NULL;
  1409. }
  1410. /**
  1411. @fn ds__SignatureType* soap_wsse_Signature(struct soap *soap)
  1412. @brief Returns Signature header element if present.
  1413. @param soap context
  1414. @return ds__SignatureType object or NULL
  1415. */
  1416. struct ds__SignatureType*
  1417. soap_wsse_Signature(struct soap *soap)
  1418. { _wsse__Security *security = soap_wsse_Security(soap);
  1419. if (security)
  1420. return security->ds__Signature;
  1421. return NULL;
  1422. }
  1423. /******************************************************************************\
  1424. *
  1425. * wsse:Security/wsu:Timestamp header element
  1426. *
  1427. \******************************************************************************/
  1428. /**
  1429. @fn int soap_wsse_add_Timestamp(struct soap *soap, const char *id, time_t lifetime)
  1430. @brief Adds Timestamp element with optional expiration date+time (lifetime).
  1431. @param[in] soap context
  1432. @param[in] id for signature referencing or NULL
  1433. @param[in] lifetime expressed in time_t units, or 0 for no expiration
  1434. @return SOAP_OK
  1435. */
  1436. int
  1437. soap_wsse_add_Timestamp(struct soap *soap, const char *id, time_t lifetime)
  1438. { _wsse__Security *security = soap_wsse_add_Security(soap);
  1439. time_t now = time(NULL);
  1440. char *created = soap_strdup(soap, soap_dateTime2s(soap, now));
  1441. char *expired = lifetime ? soap_strdup(soap, soap_dateTime2s(soap, now + lifetime)) : NULL;
  1442. DBGFUN1("soap_wsse_add_Timestamp", "id=%s", id?id:"");
  1443. /* allocate a Timestamp if we don't have one already */
  1444. if (!security->wsu__Timestamp)
  1445. { security->wsu__Timestamp = (_wsu__Timestamp*)soap_malloc(soap, sizeof(_wsu__Timestamp));
  1446. if (!security->wsu__Timestamp)
  1447. return soap->error = SOAP_EOM;
  1448. }
  1449. soap_default__wsu__Timestamp(soap, security->wsu__Timestamp);
  1450. /* populate the wsu:Timestamp element */
  1451. security->wsu__Timestamp->wsu__Id = soap_strdup(soap, id);
  1452. security->wsu__Timestamp->Created = created;
  1453. security->wsu__Timestamp->Expires = expired;
  1454. return SOAP_OK;
  1455. }
  1456. /**
  1457. @fn _wsu__Timestamp *soap_wsse_Timestamp(struct soap *soap)
  1458. @brief Returns Timestamp element if present.
  1459. @param soap context
  1460. @return _wsu__Timestamp object or NULL
  1461. */
  1462. struct _wsu__Timestamp*
  1463. soap_wsse_Timestamp(struct soap *soap)
  1464. { _wsse__Security *security = soap_wsse_Security(soap);
  1465. if (security)
  1466. return security->wsu__Timestamp;
  1467. return NULL;
  1468. }
  1469. /**
  1470. @fn int soap_wsse_verify_Timestamp(struct soap *soap)
  1471. @brief Verifies the Timestamp/Expires element against the current time.
  1472. @param soap context
  1473. @return SOAP_OK or SOAP_FAULT with wsse:FailedAuthentication fault
  1474. Sets wsse:FailedAuthentication fault if wsu:Timestamp is expired. The
  1475. SOAP_WSSE_CLKSKEW value is used as a margin to mitigate clock skew. Keeps
  1476. silent when no timestamp is supplied or no expiration date is included in the
  1477. wsu:Timestamp element.
  1478. */
  1479. int
  1480. soap_wsse_verify_Timestamp(struct soap *soap)
  1481. { _wsu__Timestamp *timestamp = soap_wsse_Timestamp(soap);
  1482. DBGFUN("soap_wsse_verify_Timestamp");
  1483. /* if we have a timestamp with an expiration date, check it */
  1484. if (timestamp && timestamp->Expires)
  1485. { time_t now = time(NULL), expired;
  1486. soap_s2dateTime(soap, timestamp->Expires, &expired);
  1487. if (expired + SOAP_WSSE_CLKSKEW <= now)
  1488. { const char *code = soap_wsu__tTimestampFault2s(soap, wsu__MessageExpired);
  1489. return soap_wsse_sender_fault_subcode(soap, code, "Message has expired", timestamp->Expires);
  1490. }
  1491. }
  1492. return SOAP_OK;
  1493. }
  1494. /******************************************************************************\
  1495. *
  1496. * wsse:Security/UsernameToken header element
  1497. *
  1498. \******************************************************************************/
  1499. /**
  1500. @fn int soap_wsse_add_UsernameTokenText(struct soap *soap, const char *id, const char *username, const char *password)
  1501. @brief Adds UsernameToken element with optional clear-text password.
  1502. @param soap context
  1503. @param[in] id string for signature referencing or NULL
  1504. @param[in] username string
  1505. @param[in] password string or NULL to omit the password
  1506. @return SOAP_OK
  1507. Passwords are sent in the clear, so transport-level encryption is required.
  1508. Note: this release supports the use of at most one UsernameToken in the header.
  1509. */
  1510. int
  1511. soap_wsse_add_UsernameTokenText(struct soap *soap, const char *id, const char *username, const char *password)
  1512. { _wsse__Security *security = soap_wsse_add_Security(soap);
  1513. DBGFUN2("soap_wsse_add_UsernameTokenText", "id=%s", id?id:"", "username=%s", username?username:"");
  1514. /* allocate a UsernameToken if we don't have one already */
  1515. if (!security->UsernameToken)
  1516. { if (!(security->UsernameToken = (_wsse__UsernameToken*)soap_malloc(soap, sizeof(_wsse__UsernameToken))))
  1517. return soap->error = SOAP_EOM;
  1518. }
  1519. soap_default__wsse__UsernameToken(soap, security->UsernameToken);
  1520. /* populate the UsernameToken */
  1521. security->UsernameToken->wsu__Id = soap_strdup(soap, id);
  1522. security->UsernameToken->Username = soap_strdup(soap, username);
  1523. /* allocate and populate the Password */
  1524. if (password)
  1525. { if (!(security->UsernameToken->Password = (_wsse__Password*)soap_malloc(soap, sizeof(_wsse__Password))))
  1526. return soap->error = SOAP_EOM;
  1527. soap_default__wsse__Password(soap, security->UsernameToken->Password);
  1528. security->UsernameToken->Password->Type = (char*)wsse_PasswordTextURI;
  1529. security->UsernameToken->Password->__item = soap_strdup(soap, password);
  1530. }
  1531. return SOAP_OK;
  1532. }
  1533. /**
  1534. @fn int soap_wsse_add_UsernameTokenDigest(struct soap *soap, const char *id, const char *username, const char *password)
  1535. @brief Adds UsernameToken element for digest authentication.
  1536. @param soap context
  1537. @param[in] id string for signature referencing or NULL
  1538. @param[in] username string
  1539. @param[in] password string
  1540. @return SOAP_OK
  1541. Computes SHA1 digest of the time stamp, a nonce, and the password. The digest
  1542. provides the authentication credentials. Passwords are NOT sent in the clear.
  1543. Note: this release supports the use of at most one UsernameToken in the header.
  1544. */
  1545. int
  1546. soap_wsse_add_UsernameTokenDigest(struct soap *soap, const char *id, const char *username, const char *password)
  1547. { _wsse__Security *security = soap_wsse_add_Security(soap);
  1548. time_t now = time(NULL);
  1549. const char *created = soap_dateTime2s(soap, now);
  1550. char HA[SOAP_SMD_SHA1_SIZE], HABase64[29];
  1551. char nonce[SOAP_WSSE_NONCELEN], *nonceBase64;
  1552. DBGFUN2("soap_wsse_add_UsernameTokenDigest", "id=%s", id?id:"", "username=%s", username?username:"");
  1553. /* generate a nonce */
  1554. calc_nonce(soap, nonce);
  1555. nonceBase64 = soap_s2base64(soap, (unsigned char*)nonce, NULL, SOAP_WSSE_NONCELEN);
  1556. /* The specs are not clear: compute digest over binary nonce or base64 nonce? */
  1557. /* compute SHA1(created, nonce, password) */
  1558. calc_digest(soap, created, nonce, SOAP_WSSE_NONCELEN, password, HA);
  1559. /* Hm...?
  1560. calc_digest(soap, created, nonceBase64, strlen(nonceBase64), password, HA);
  1561. */
  1562. soap_s2base64(soap, (unsigned char*)HA, HABase64, SOAP_SMD_SHA1_SIZE);
  1563. /* populate the UsernameToken with digest */
  1564. soap_wsse_add_UsernameTokenText(soap, id, username, HABase64);
  1565. /* populate the remainder of the password, nonce, and created */
  1566. security->UsernameToken->Password->Type = (char*)wsse_PasswordDigestURI;
  1567. security->UsernameToken->Nonce = nonceBase64;
  1568. security->UsernameToken->wsu__Created = soap_strdup(soap, created);
  1569. return SOAP_OK;
  1570. }
  1571. /**
  1572. @fn _wsse__UsernameToken* soap_wsse_UsernameToken(struct soap *soap, const char *id)
  1573. @brief Returns UsernameToken element if present.
  1574. @param soap context
  1575. @param[in] id string of UsernameToken or NULL
  1576. @return _wsse__UsernameToken object or NULL
  1577. Note: this release supports the use of at most one UsernameToken in the header.
  1578. */
  1579. struct _wsse__UsernameToken*
  1580. soap_wsse_UsernameToken(struct soap *soap, const char *id)
  1581. { _wsse__Security *security = soap_wsse_Security(soap);
  1582. if (security
  1583. && security->UsernameToken
  1584. && (!id || (security->UsernameToken->wsu__Id
  1585. && !strcmp(security->UsernameToken->wsu__Id, id))))
  1586. return security->UsernameToken;
  1587. return NULL;
  1588. }
  1589. /**
  1590. @fn const char* soap_wsse_get_Username(struct soap *soap)
  1591. @brief Returns UsernameToken/username string or wsse:FailedAuthentication fault.
  1592. @param soap context
  1593. @return UsernameToken/username string or NULL with wsse:FailedAuthentication fault error set
  1594. @see soap_wsse_verify_Password
  1595. The returned username should be used to lookup the user's password in a
  1596. dictionary or database for server-side authentication with
  1597. soap_wsse_verify_Password.
  1598. */
  1599. const char*
  1600. soap_wsse_get_Username(struct soap *soap)
  1601. { _wsse__UsernameToken *token = soap_wsse_UsernameToken(soap, NULL);
  1602. DBGFUN("soap_wsse_get_Username");
  1603. if (token)
  1604. return token->Username;
  1605. soap_wsse_fault(soap, wsse__FailedAuthentication, "Username authentication required");
  1606. return NULL;
  1607. }
  1608. /**
  1609. @fn int soap_wsse_verify_Password(struct soap *soap, const char *password)
  1610. @brief Verifies the supplied password or sets wsse:FailedAuthentication fault.
  1611. @param soap context
  1612. @param[in] password string to verify against
  1613. @return SOAP_OK (authorized) or SOAP_FAULT with wsse:FailedAuthentication fault
  1614. The verification supports both clear-text password verification and digest
  1615. password authentication. For digest authentication a history mechanism with a
  1616. digest authentication session database ensures protection against replay
  1617. attacks.
  1618. Note: this release supports the use of at most one UsernameToken in the header.
  1619. */
  1620. int
  1621. soap_wsse_verify_Password(struct soap *soap, const char *password)
  1622. { _wsse__UsernameToken *token = soap_wsse_UsernameToken(soap, NULL);
  1623. DBGFUN("soap_wsse_verify_Password");
  1624. /* if we have a UsernameToken with a Password, check it */
  1625. if (token && token->Password)
  1626. { /* password digest or text? */
  1627. if (token->Password->Type
  1628. && !strcmp(token->Password->Type, wsse_PasswordDigestURI))
  1629. { /* check password digest: compute SHA1(created, nonce, password) */
  1630. if (token->Nonce
  1631. && token->wsu__Created
  1632. && strlen(token->Password->__item) == 28) /* digest pw len = 28 */
  1633. { char HA1[SOAP_SMD_SHA1_SIZE], HA2[SOAP_SMD_SHA1_SIZE];
  1634. /* The specs are not clear: compute digest over binary nonce or base64 nonce? The formet appears to be the case: */
  1635. int noncelen;
  1636. const char *nonce = soap_base642s(soap, token->Nonce, NULL, 0, &noncelen);
  1637. /* compute HA1 = SHA1(created, nonce, password) */
  1638. calc_digest(soap, token->wsu__Created, nonce, noncelen, password, HA1);
  1639. /*
  1640. calc_digest(soap, token->wsu__Created, token->Nonce, strlen(token->Nonce), password, HA1);
  1641. */
  1642. /* get HA2 = supplied digest from base64 Password */
  1643. soap_base642s(soap, token->Password->__item, HA2, SOAP_SMD_SHA1_SIZE, NULL);
  1644. /* compare HA1 to HA2 */
  1645. if (!memcmp(HA1, HA2, SOAP_SMD_SHA1_SIZE))
  1646. { /* authorize if HA1 and HA2 identical and not replay attack */
  1647. if (!soap_wsse_session_verify(soap, HA1, token->wsu__Created, token->Nonce))
  1648. return SOAP_OK;
  1649. return soap->error;
  1650. }
  1651. }
  1652. }
  1653. else
  1654. { /* check password text */
  1655. if (!strcmp(token->Password->__item, password))
  1656. return SOAP_OK;
  1657. }
  1658. }
  1659. return soap_wsse_fault(soap, wsse__FailedAuthentication, NULL);
  1660. }
  1661. /******************************************************************************\
  1662. *
  1663. * wsse:Security/BinarySecurityToken header element
  1664. *
  1665. \******************************************************************************/
  1666. /**
  1667. @fn int soap_wsse_add_BinarySecurityToken(struct soap *soap, const char *id, const char *valueType, const unsigned char *data, int size)
  1668. @brief Adds BinarySecurityToken element.
  1669. @param soap context
  1670. @param[in] id string for signature referencing or NULL
  1671. @param[in] valueType string
  1672. @param[in] data points to binary token data
  1673. @param[in] size is length of binary token
  1674. @return SOAP_OK
  1675. */
  1676. int
  1677. soap_wsse_add_BinarySecurityToken(struct soap *soap, const char *id, const char *valueType, const unsigned char *data, int size)
  1678. { _wsse__Security *security = soap_wsse_add_Security(soap);
  1679. DBGFUN2("wsse_add_BinarySecurityToken", "id=%s", id?id:"", "valueType=%s", valueType?valueType:"");
  1680. /* allocate BinarySecurityToken if we don't already have one */
  1681. if (!security->BinarySecurityToken)
  1682. { if (!(security->BinarySecurityToken = (_wsse__BinarySecurityToken*)soap_malloc(soap, sizeof(_wsse__BinarySecurityToken))))
  1683. return soap->error = SOAP_EOM;
  1684. }
  1685. soap_default__wsse__BinarySecurityToken(soap, security->BinarySecurityToken);
  1686. /* populate the BinarySecurityToken */
  1687. security->BinarySecurityToken->wsu__Id = soap_strdup(soap, id);
  1688. security->BinarySecurityToken->ValueType = soap_strdup(soap, valueType);
  1689. security->BinarySecurityToken->EncodingType = (char*)wsse_Base64BinaryURI;
  1690. security->BinarySecurityToken->__item = soap_s2base64(soap, data, NULL, size);
  1691. return SOAP_OK;
  1692. }
  1693. /**
  1694. @fn int soap_wsse_add_BinarySecurityTokenX509(struct soap *soap, const char *id, X509 *cert)
  1695. @brief Adds BinarySecurityToken element with X509 certificate.
  1696. @param soap context
  1697. @param[in] id string for signature reference
  1698. @param[in] cert points to the X509 certificate
  1699. @return SOAP_OK or SOAP_EOM
  1700. This function uses i2d_X509 from the the OpenSSL library to convert an X509
  1701. object to binary DER format.
  1702. */
  1703. int
  1704. soap_wsse_add_BinarySecurityTokenX509(struct soap *soap, const char *id, X509 *cert)
  1705. { int derlen;
  1706. unsigned char *der, *s;
  1707. if (!cert)
  1708. return soap_wsse_fault(soap, wsse__InvalidSecurityToken, "Missing certificate");
  1709. /* determine the storage requirement */
  1710. derlen = i2d_X509(cert, NULL);
  1711. if (derlen < 0)
  1712. return soap_wsse_fault(soap, wsse__InvalidSecurityToken, "Invalid certificate");
  1713. /* use the gSOAP engine's look-aside buffer to temporarily hold the cert */
  1714. if (soap_store_lab(soap, NULL, derlen))
  1715. return SOAP_EOM;
  1716. s = der = (unsigned char*)soap->labbuf;
  1717. /* store in DER format */
  1718. i2d_X509(cert, &s);
  1719. /* populate the BinarySecurityToken with base64 certificate data */
  1720. return soap_wsse_add_BinarySecurityToken(soap, id, wsse_X509v3URI, der, derlen);
  1721. }
  1722. /**
  1723. @fn int soap_wsse_add_BinarySecurityTokenPEM(struct soap *soap, const char *id, const char *filename)
  1724. @brief Adds BinarySecurityToken element from a PEM file.
  1725. @param soap context
  1726. @param[in] id string for signature reference
  1727. @param[in] filename
  1728. @return SOAP_OK or SOAP_FAULT with wsse__InvalidSecurity fault when file cannot be read or does not contain a valid certificate
  1729. This function uses PEM_read_X509 from the the OpenSSL library to read a
  1730. certificate from a PEM formatted file.
  1731. */
  1732. int
  1733. soap_wsse_add_BinarySecurityTokenPEM(struct soap *soap, const char *id, const char *filename)
  1734. { FILE *fd;
  1735. DBGFUN2("soap_wsse_add_BinarySecurityTokenPEM", "id=%s", id?id:"", "filename=%s", filename?filename:"");
  1736. if ((fd = fopen(filename, "r")))
  1737. { /* read the certificate */
  1738. X509 *cert = PEM_read_X509(fd, NULL, NULL, NULL);
  1739. fclose(fd);
  1740. /* if okay, populate the BinarySecurityToken element */
  1741. if (cert)
  1742. { int err = soap_wsse_add_BinarySecurityTokenX509(soap, id, cert);
  1743. X509_free(cert);
  1744. return err;
  1745. }
  1746. }
  1747. return soap_wsse_fault(soap, wsse__InvalidSecurityToken, "Missing certificate");
  1748. }
  1749. /**
  1750. @fn _wsse__BinarySecurityToken* soap_wsse_BinarySecurityToken(struct soap *soap, const char *id)
  1751. @brief Returns BinarySecurityToken element if present.
  1752. @param soap context
  1753. @param[in] id string of token to get or NULL
  1754. @return _wsse__BinarySecurityToken object or NULL
  1755. */
  1756. struct _wsse__BinarySecurityToken*
  1757. soap_wsse_BinarySecurityToken(struct soap *soap, const char *id)
  1758. { _wsse__Security *security = soap_wsse_Security(soap);
  1759. if (security
  1760. && security->BinarySecurityToken
  1761. && (!id || (security->BinarySecurityToken->wsu__Id
  1762. && !strcmp(security->BinarySecurityToken->wsu__Id, id))))
  1763. return security->BinarySecurityToken;
  1764. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "No BinarySecurityToken id=%s, pointer=%p to token found\n", id, security->BinarySecurityToken));
  1765. return NULL;
  1766. }
  1767. /**
  1768. @fn int soap_wsse_get_BinarySecurityToken(struct soap *soap, const char *id, char **valueType, unsigned char **data, int *size)
  1769. @brief Get wsse:BinarySecurityToken element token data in binary form.
  1770. @param soap context
  1771. @param[in] id string of token to get or NULL
  1772. @param[out] valueType string
  1773. @param[out] data points to binary token data
  1774. @param[out] size is length of binary token
  1775. @return SOAP_OK or SOAP_FAULT with wsse:SecurityTokenUnavailable fault
  1776. */
  1777. int
  1778. soap_wsse_get_BinarySecurityToken(struct soap *soap, const char *id, char **valueType, unsigned char **data, int *size)
  1779. { _wsse__BinarySecurityToken *token = soap_wsse_BinarySecurityToken(soap, id);
  1780. DBGFUN1("soap_wsse_get_BinarySecurityToken", "id=%s", id?id:"");
  1781. if (token)
  1782. { *valueType = token->ValueType;
  1783. /* it appears we don't need HexBinary after all
  1784. if (token->EncodingType && !strcmp(token->EncodingType, wsse_HexBinaryURI))
  1785. *data = (unsigned char*)soap_hex2s(soap, token->__item, NULL, 0, size);
  1786. else
  1787. */
  1788. /* assume token is represented in base64 by default */
  1789. *data = (unsigned char*)soap_base642s(soap, token->__item, NULL, 0, size);
  1790. if (*data)
  1791. return SOAP_OK;
  1792. }
  1793. return soap_wsse_fault(soap, wsse__SecurityTokenUnavailable, "BinarySecurityToken required");
  1794. }
  1795. /**
  1796. @fn X509* soap_wsse_get_BinarySecurityTokenX509(struct soap *soap, const char *id)
  1797. @brief Get X509 wsse:BinarySecurityToken certificate and verify its content.
  1798. @param soap context
  1799. @param[in] id string of token to get or NULL
  1800. @return X509 certificate (dynamically allocated) or NULL with wsse:SecurityTokenUnavailable fault
  1801. */
  1802. X509*
  1803. soap_wsse_get_BinarySecurityTokenX509(struct soap *soap, const char *id)
  1804. { X509 *cert = NULL;
  1805. char *valueType = NULL;
  1806. #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
  1807. const unsigned char *data;
  1808. #else
  1809. unsigned char *data;
  1810. #endif
  1811. int size;
  1812. DBGFUN1("soap_wsse_get_BinarySecurityTokenX509", "id=%s", id?id:"");
  1813. if (!soap_wsse_get_BinarySecurityToken(soap, id, &valueType, (unsigned char**)&data, &size)
  1814. && valueType
  1815. && !strcmp(valueType, wsse_X509v3URI))
  1816. cert = d2i_X509(NULL, &data, size);
  1817. /* verify the certificate */
  1818. if (!cert || soap_wsse_verify_X509(soap, cert))
  1819. return NULL;
  1820. return cert;
  1821. }
  1822. /**
  1823. @fn int soap_wsse_verify_X509(struct soap *soap, X509 *cert)
  1824. @brief Verifies X509 certificate against soap->cafile, soap->capath, and soap->crlfile
  1825. @param soap context
  1826. @param[in] cert X509 certificate
  1827. @return SOAP_OK or fault
  1828. This is an expensive operation. Whenever a new soap context is created, the
  1829. cafile and objects are loaded into that context each time we need to verify a
  1830. certificate.
  1831. */
  1832. int
  1833. soap_wsse_verify_X509(struct soap *soap, X509 *cert)
  1834. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  1835. X509_STORE_CTX *verify;
  1836. DBGFUN("soap_wsse_verify_X509");
  1837. if (!data)
  1838. return soap_set_receiver_error(soap, "soap_wsse_sign", "Plugin not registered", SOAP_PLUGIN_ERROR);
  1839. if (!cert)
  1840. return soap_wsse_sender_fault(soap, "soap_wsse_verify_X509", "No certificate");
  1841. if (!data->store)
  1842. { if (!(data->store = X509_STORE_new()))
  1843. return soap_wsse_receiver_fault(soap, "soap_wsse_verify_X509", "Could not create X509_STORE object");
  1844. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Setting up a new X509 store\n"));
  1845. X509_STORE_set_verify_cb_func(data->store, soap->fsslverify);
  1846. if (soap->cafile || soap->capath)
  1847. { if (X509_STORE_load_locations(data->store, soap->cafile, soap->capath) != 1)
  1848. return soap_wsse_receiver_fault(soap, "soap_wsse_verify_X509", "Could not load CA file or path");
  1849. }
  1850. #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
  1851. if (soap->crlfile)
  1852. { X509_LOOKUP *lookup;
  1853. if (!(lookup = X509_STORE_add_lookup(data->store, X509_LOOKUP_file())))
  1854. return soap_wsse_receiver_fault(soap, "soap_wsse_verify_X509", "Could not create X509_LOOKUP object");
  1855. if (X509_load_crl_file(lookup, soap->crlfile, X509_FILETYPE_PEM) != 1)
  1856. return soap_wsse_receiver_fault(soap, "soap_wsse_verify_X509", "Could not read the CRL file");
  1857. X509_STORE_set_flags(data->store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
  1858. }
  1859. #endif
  1860. }
  1861. if (!(verify = X509_STORE_CTX_new()))
  1862. return soap_wsse_receiver_fault(soap, "soap_wsse_verify_X509", "Could not create X509_STORE_CTX object");
  1863. #if (OPENSSL_VERSION_NUMBER > 0x00907000L)
  1864. if (X509_STORE_CTX_init(verify, data->store, cert, NULL) != 1)
  1865. { X509_STORE_CTX_free(verify);
  1866. return soap_wsse_receiver_fault(soap, "soap_wsse_verify_X509", "Could not initialize X509_STORE_CTX object");
  1867. }
  1868. #else
  1869. X509_STORE_CTX_init(verify, data->store, cert, NULL);
  1870. #endif
  1871. if (X509_verify_cert(verify) != 1)
  1872. { X509_STORE_CTX_free(verify);
  1873. return soap_wsse_sender_fault(soap, "soap_wsse_verify_X509", "Invalid certificate");
  1874. }
  1875. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Certificate is valid\n"));
  1876. #ifdef SOAP_DEBUG
  1877. { char buf[1024];
  1878. X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf));
  1879. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "certificate issuer %s\n", buf));
  1880. X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
  1881. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "certificate subject %s\n", buf));
  1882. }
  1883. #endif
  1884. X509_STORE_CTX_free(verify);
  1885. return SOAP_OK;
  1886. }
  1887. /******************************************************************************\
  1888. *
  1889. * wsc:SecurityContextToken
  1890. *
  1891. \******************************************************************************/
  1892. /**
  1893. @fn int soap_wsse_add_SecurityContextToken(struct soap *soap, const char *id, const char *identifier)
  1894. @brief Adds wsc:SecurityContextToken/Identifier and SecurityTokenReference to it
  1895. @param soap context
  1896. @param[in] id string for signature reference (required)
  1897. @param[in] identifier wsc:Identifier value (required)
  1898. @return SOAP_OK or error code
  1899. */
  1900. int
  1901. soap_wsse_add_SecurityContextToken(struct soap *soap, const char *id, const char *identifier)
  1902. { char *URI;
  1903. _wsse__Security *security = soap_wsse_add_Security(soap);
  1904. DBGFUN2("soap_wsse_add_SecurityContextToken", "id=%s", id, "identifier=%s", identifier?identifier:"");
  1905. /* allocate wsc:SecurityContextToken if we don't already have one */
  1906. if (!security->wsc__SecurityContextToken)
  1907. { if (!(security->wsc__SecurityContextToken = (struct wsc__SecurityContextTokenType*)soap_malloc(soap, sizeof(struct wsc__SecurityContextTokenType))))
  1908. return soap->error = SOAP_EOM;
  1909. }
  1910. soap_default_wsc__SecurityContextTokenType(soap, security->wsc__SecurityContextToken);
  1911. /* populate the wsc:SecurityContextToken */
  1912. if (!(URI = (char*)soap_malloc(soap, strlen(id) + 2)))
  1913. return soap->error = SOAP_EOM;
  1914. *URI = '#';
  1915. security->wsc__SecurityContextToken->wsu__Id = strcpy(URI + 1, id);
  1916. security->wsc__SecurityContextToken->Identifier = soap_strdup(soap, identifier);
  1917. /* set SecurityTokenReference */
  1918. return soap_wsse_add_KeyInfo_SecurityTokenReferenceURI(soap, URI, NULL);
  1919. }
  1920. /**
  1921. @fn const char *soap_wsse_get_SecurityContextToken(struct soap *soap)
  1922. @brief Returns wsc:SecurityContextToken/Identifier string value or NULL
  1923. @param soap context
  1924. @return wsc:SecurityContextToken/Identifier string value value or NULL
  1925. */
  1926. const char *
  1927. soap_wsse_get_SecurityContextToken(struct soap *soap)
  1928. { _wsse__Security *security = soap_wsse_Security(soap);
  1929. DBGFUN("soap_wsse_SecurityContextToken");
  1930. if (security->wsc__SecurityContextToken && security->wsc__SecurityContextToken->wsu__Id)
  1931. { const char *URI = soap_wsse_get_KeyInfo_SecurityTokenReferenceURI(soap);
  1932. if (URI && !strcmp(URI, security->wsc__SecurityContextToken->wsu__Id))
  1933. return security->wsc__SecurityContextToken->Identifier;
  1934. }
  1935. return NULL;
  1936. }
  1937. /******************************************************************************\
  1938. *
  1939. * ds:Signature/SignedInfo
  1940. *
  1941. \******************************************************************************/
  1942. /**
  1943. @fn ds__SignedInfoType* soap_wsse_add_SignedInfo(struct soap *soap)
  1944. @brief Adds SignedInfo element.
  1945. @param soap context
  1946. @return ds__SignedInfoType object
  1947. */
  1948. struct ds__SignedInfoType*
  1949. soap_wsse_add_SignedInfo(struct soap *soap)
  1950. { ds__SignatureType *signature = soap_wsse_add_Signature(soap);
  1951. if (!signature->SignedInfo)
  1952. { signature->SignedInfo = (ds__SignedInfoType*)soap_malloc(soap, sizeof(ds__SignedInfoType));
  1953. if (!signature->SignedInfo)
  1954. return NULL;
  1955. soap_default_ds__SignedInfoType(soap, signature->SignedInfo);
  1956. }
  1957. return signature->SignedInfo;
  1958. }
  1959. /**
  1960. @fn int soap_wsse_add_SignedInfo_Reference(struct soap *soap, const char *URI, const char *transform, const char *inclusiveNamespaces, int alg, const char *HA)
  1961. @brief Adds SignedInfo element with Reference URI, transform algorithm used, and digest value.
  1962. @param soap context
  1963. @param[in] URI reference
  1964. @param[in] transform string should be c14n_URI for exc-c14n or NULL
  1965. @param[in] inclusiveNamespaces used by the exc-c14n transform or NULL
  1966. @param[in] alg is the digest algorithm used
  1967. @param[in] HA is the digest in binary form
  1968. @return SOAP_OK or SOAP_EOM when references exceed SOAP_WSSE_MAX_REF
  1969. This function can be called to add more references to the wsse:SignedInfo
  1970. element. A maximum number of SOAP_WSSE_MAX_REF references can be added. The
  1971. digest method is always SHA1.
  1972. Note: XPath transforms cannot be specified in this release.
  1973. */
  1974. int
  1975. soap_wsse_add_SignedInfo_Reference(struct soap *soap, const char *URI, const char *transform, const char *inclusiveNamespaces, int alg, const char *HA)
  1976. { ds__SignedInfoType *signedInfo = soap_wsse_add_SignedInfo(soap);
  1977. ds__ReferenceType *reference;
  1978. DBGFUN3("soap_wsse_add_SignedInfo_Reference", "URI=%s", URI?URI:"", "transform=%s", transform?transform:"", "alg=%x", alg);
  1979. /* if this is the first reference, allocate SOAP_WSSE_MAX_REF references */
  1980. if (signedInfo->__sizeReference == 0)
  1981. signedInfo->Reference = (ds__ReferenceType**)soap_malloc(soap, SOAP_WSSE_MAX_REF*sizeof(ds__ReferenceType*));
  1982. else
  1983. { /* maximum number of references exceeded? */
  1984. if (signedInfo->__sizeReference >= SOAP_WSSE_MAX_REF)
  1985. return soap->error = SOAP_EOM;
  1986. }
  1987. /* allocate fresh new reference */
  1988. reference = (ds__ReferenceType*)soap_malloc(soap, sizeof(ds__ReferenceType));
  1989. if (!reference)
  1990. return soap->error = SOAP_EOM;
  1991. soap_default_ds__ReferenceType(soap, reference);
  1992. /* populate the URI */
  1993. reference->URI = soap_strdup(soap, URI);
  1994. /* if a transform algorithm was used, populate the Transforms element */
  1995. if (transform)
  1996. { reference->Transforms = (ds__TransformsType*)soap_malloc(soap, sizeof(ds__TransformsType));
  1997. if (!reference->Transforms)
  1998. return soap->error = SOAP_EOM;
  1999. soap_default_ds__TransformsType(soap, reference->Transforms);
  2000. /* only one transform */
  2001. reference->Transforms->__sizeTransform = 1;
  2002. reference->Transforms->Transform = (ds__TransformType*)soap_malloc(soap, sizeof(ds__TransformType));
  2003. soap_default_ds__TransformType(soap, reference->Transforms->Transform);
  2004. reference->Transforms->Transform->Algorithm = (char*)transform;
  2005. /* populate the c14n:InclusiveNamespaces element */
  2006. if (inclusiveNamespaces && *inclusiveNamespaces)
  2007. { reference->Transforms->Transform->c14n__InclusiveNamespaces = (_c14n__InclusiveNamespaces*)soap_malloc(soap, sizeof(_c14n__InclusiveNamespaces));
  2008. if (!reference->Transforms->Transform->c14n__InclusiveNamespaces)
  2009. return soap->error = SOAP_EOM;
  2010. soap_default__c14n__InclusiveNamespaces(soap, reference->Transforms->Transform->c14n__InclusiveNamespaces);
  2011. reference->Transforms->Transform->c14n__InclusiveNamespaces->PrefixList = soap_strdup(soap, inclusiveNamespaces);
  2012. }
  2013. }
  2014. /* populate the DigestMethod element */
  2015. reference->DigestMethod = (ds__DigestMethodType*)soap_malloc(soap, sizeof(ds__DigestMethodType));
  2016. if (!reference->DigestMethod)
  2017. return soap->error = SOAP_EOM;
  2018. soap_default_ds__DigestMethodType(soap, reference->DigestMethod);
  2019. /* the DigestMethod algorithm SHA1, SHA256, SHA512 */
  2020. switch (alg & SOAP_SMD_HASH)
  2021. { case SOAP_SMD_SHA1:
  2022. reference->DigestMethod->Algorithm = (char*)ds_sha1URI;
  2023. break;
  2024. case SOAP_SMD_SHA256:
  2025. reference->DigestMethod->Algorithm = (char*)ds_sha256URI;
  2026. break;
  2027. case SOAP_SMD_SHA512:
  2028. reference->DigestMethod->Algorithm = (char*)ds_sha512URI;
  2029. break;
  2030. }
  2031. /* populate the DigestValue element */
  2032. reference->DigestValue = soap_s2base64(soap, (unsigned char*)HA, NULL, soap_smd_size(alg, NULL));
  2033. if (!reference->DigestValue)
  2034. return soap->error;
  2035. /* add the fresh new reference to the array */
  2036. signedInfo->Reference[signedInfo->__sizeReference] = reference;
  2037. signedInfo->__sizeReference++;
  2038. return SOAP_OK;
  2039. }
  2040. /**
  2041. @fn int soap_wsse_add_SignedInfo_SignatureMethod(struct soap *soap, const char *method, int canonical)
  2042. @brief Adds SignedInfo element with SignatureMethod.
  2043. @param soap context
  2044. @param[in] method is the URI of the signature algorithm (e.g. ds_rsa_sha1)
  2045. @param[in] canonical flag indicating that SignedInfo is signed in exc-c14n form
  2046. @return SOAP_OK
  2047. Note: the c14n:InclusiveNamespaces/PrefixList is set to "SOAP-ENV wsse".
  2048. */
  2049. int
  2050. soap_wsse_add_SignedInfo_SignatureMethod(struct soap *soap, const char *method, int canonical)
  2051. { ds__SignedInfoType *signedInfo = soap_wsse_add_SignedInfo(soap);
  2052. DBGFUN2("soap_wsse_add_SignedInfo_SignatureMethod", "method=%s", method?method:"", "canonical=%d", canonical);
  2053. /* if signed in exc-c14n form, populate CanonicalizationMethod element */
  2054. signedInfo->CanonicalizationMethod = (ds__CanonicalizationMethodType*)soap_malloc(soap, sizeof(ds__CanonicalizationMethodType));
  2055. if (!signedInfo->CanonicalizationMethod)
  2056. return soap->error = SOAP_EOM;
  2057. soap_default_ds__CanonicalizationMethodType(soap, signedInfo->CanonicalizationMethod);
  2058. if (canonical)
  2059. { signedInfo->CanonicalizationMethod->Algorithm = (char*)c14n_URI;
  2060. /*
  2061. signedInfo->CanonicalizationMethod->c14n__InclusiveNamespaces = (_c14n__InclusiveNamespaces*)soap_malloc(soap, sizeof(_c14n__InclusiveNamespaces));
  2062. soap_default__c14n__InclusiveNamespaces(soap, signedInfo->CanonicalizationMethod->c14n__InclusiveNamespaces);
  2063. signedInfo->CanonicalizationMethod->c14n__InclusiveNamespaces->PrefixList = "SOAP-ENV wsse";
  2064. */
  2065. }
  2066. /* populate SignatureMethod element */
  2067. signedInfo->SignatureMethod = (ds__SignatureMethodType*)soap_malloc(soap, sizeof(ds__SignatureMethodType));
  2068. if (!signedInfo->SignatureMethod)
  2069. return soap->error = SOAP_EOM;
  2070. soap_default_ds__SignatureMethodType(soap, signedInfo->SignatureMethod);
  2071. signedInfo->SignatureMethod->Algorithm = (char*)method;
  2072. return SOAP_OK;
  2073. }
  2074. /**
  2075. @fn ds__SignedInfoType* soap_wsse_SignedInfo(struct soap *soap)
  2076. @brief Returns SignedInfo element if present.
  2077. @param soap context
  2078. @return ds__SignedInfoType object or NULL
  2079. */
  2080. struct ds__SignedInfoType*
  2081. soap_wsse_SignedInfo(struct soap *soap)
  2082. { ds__SignatureType *signature = soap_wsse_Signature(soap);
  2083. if (signature)
  2084. return signature->SignedInfo;
  2085. return NULL;
  2086. }
  2087. /**
  2088. @fn int soap_wsse_get_SignedInfo_SignatureMethod(struct soap *soap, int *alg)
  2089. @brief Get SignatureMethod algorithm
  2090. @param soap context
  2091. @param[out] alg is a signature algorithm, such as SOAP_SMD_HMAC_SHA1, SOAP_SMD_VRFY_DSA_SHA1, or SOAP_SMD_VRFY_RSA_SHA1
  2092. @return SOAP_OK or SOAP_FAULT with wsse:UnsupportedAlgorithm or wsse:FailedCheck fault
  2093. */
  2094. int
  2095. soap_wsse_get_SignedInfo_SignatureMethod(struct soap *soap, int *alg)
  2096. { ds__SignedInfoType *signedInfo = soap_wsse_SignedInfo(soap);
  2097. DBGFUN("soap_wsse_get_SignedInfo_SignatureMethod");
  2098. *alg = SOAP_SMD_NONE;
  2099. /* if we have a SignedInfo element, get the algorithm */
  2100. if (signedInfo
  2101. && signedInfo->SignatureMethod
  2102. && signedInfo->SignatureMethod->Algorithm)
  2103. { const char *method = signedInfo->SignatureMethod->Algorithm;
  2104. if (!strcmp(method, ds_hmac_sha1URI))
  2105. *alg = SOAP_SMD_HMAC_SHA1;
  2106. else if (!strcmp(method, ds_hmac_sha256URI))
  2107. *alg = SOAP_SMD_HMAC_SHA256;
  2108. else if (!strcmp(method, ds_hmac_sha512URI))
  2109. *alg = SOAP_SMD_HMAC_SHA512;
  2110. else if (!strcmp(method, ds_dsa_sha1URI))
  2111. *alg = SOAP_SMD_VRFY_DSA_SHA1;
  2112. else if (!strcmp(method, ds_rsa_sha1URI))
  2113. *alg = SOAP_SMD_VRFY_RSA_SHA1;
  2114. else if (!strcmp(method, ds_rsa_sha256URI))
  2115. *alg = SOAP_SMD_VRFY_RSA_SHA256;
  2116. else if (!strcmp(method, ds_rsa_sha512URI))
  2117. *alg = SOAP_SMD_VRFY_RSA_SHA512;
  2118. else
  2119. return soap_wsse_fault(soap, wsse__UnsupportedAlgorithm, method);
  2120. return SOAP_OK;
  2121. }
  2122. return soap_wsse_fault(soap, wsse__FailedCheck, "Signature required");
  2123. }
  2124. /******************************************************************************\
  2125. *
  2126. * ds:Signature/SignatureValue
  2127. *
  2128. \******************************************************************************/
  2129. /**
  2130. @fn int soap_wsse_add_SignatureValue(struct soap *soap, int alg, const void *key, int keylen)
  2131. @brief Adds SignedInfo/SignatureMethod element, signs the SignedInfo element, and adds the resulting SignatureValue element.
  2132. @param soap context
  2133. @param[in] alg is SOAP_SMD_HMAC_SHA1, SOAP_SMD_SIGN_DSA_SHA1, or SOAP_SMD_SIGN_RSA_SHA1
  2134. @param[in] key to use to sign (HMAC or EVP_PKEY)
  2135. @param[in] keylen length of HMAC key
  2136. @return SOAP_OK, SOAP_EOM, or fault
  2137. To sign the SignedInfo element with this function, populate SignedInfo with
  2138. Reference elements first using soap_wsse_add_SignedInfo_Reference. The
  2139. SignedInfo element must not be modified after signing.
  2140. The SOAP_XML_INDENT and SOAP_XML_CANONICAL flags are used to serialize the
  2141. SignedInfo to compute the signature.
  2142. */
  2143. int
  2144. soap_wsse_add_SignatureValue(struct soap *soap, int alg, const void *key, int keylen)
  2145. { ds__SignatureType *signature = soap_wsse_add_Signature(soap);
  2146. const char *method = NULL;
  2147. char *sig;
  2148. int siglen;
  2149. int err;
  2150. DBGFUN1("soap_wsse_add_SignatureValue", "alg=%x", alg);
  2151. /* determine signature algorithm to use */
  2152. switch (alg)
  2153. { case SOAP_SMD_HMAC_SHA1:
  2154. method = ds_hmac_sha1URI;
  2155. break;
  2156. case SOAP_SMD_HMAC_SHA256:
  2157. method = ds_hmac_sha256URI;
  2158. break;
  2159. case SOAP_SMD_HMAC_SHA512:
  2160. method = ds_hmac_sha512URI;
  2161. break;
  2162. case SOAP_SMD_SIGN_DSA_SHA1:
  2163. method = ds_dsa_sha1URI;
  2164. break;
  2165. case SOAP_SMD_SIGN_RSA_SHA1:
  2166. method = ds_rsa_sha1URI;
  2167. break;
  2168. case SOAP_SMD_SIGN_RSA_SHA256:
  2169. method = ds_rsa_sha256URI;
  2170. break;
  2171. case SOAP_SMD_SIGN_RSA_SHA512:
  2172. method = ds_rsa_sha512URI;
  2173. break;
  2174. default:
  2175. return soap_wsse_fault(soap, wsse__UnsupportedAlgorithm, NULL);
  2176. }
  2177. /* populate SignedInfo/SignatureMethod based on SOAP_XML_CANONICAL flag */
  2178. soap_wsse_add_SignedInfo_SignatureMethod(soap, method, (soap->mode & SOAP_XML_CANONICAL));
  2179. /* use the gSOAP engine's look-aside buffer to temporarily hold the sig */
  2180. if (soap_store_lab(soap, NULL, soap_smd_size(alg, key)))
  2181. return soap->error = SOAP_EOM;
  2182. sig = soap->labbuf;
  2183. /* we will serialize SignedInfo as it appears exactly in the SOAP Header */
  2184. /* set indent level for XML SignedInfo as it appears in the SOAP Header */
  2185. soap->level = 4;
  2186. /* prevent xmlns:ds namespace inclusion when non-exclusive is used */
  2187. if (!(soap->mode & SOAP_XML_CANONICAL))
  2188. soap_push_namespace(soap, "ds", ds_URI);
  2189. /* use smdevp engine to sign SignedInfo */
  2190. err = soap_smd_begin(soap, alg, key, keylen);
  2191. if (!err)
  2192. err = soap_out_ds__SignedInfoType(soap, "ds:SignedInfo", 0, signature->SignedInfo, NULL);
  2193. if (soap_smd_end(soap, sig, &siglen) || err)
  2194. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Could not sign");
  2195. /* populate the SignatureValue element */
  2196. signature->SignatureValue = soap_s2base64(soap, (unsigned char*)sig, NULL, siglen);
  2197. if (!signature->SignatureValue)
  2198. return soap->error;
  2199. return SOAP_OK;
  2200. }
  2201. /**
  2202. @fn int soap_wsse_verify_SignatureValue(struct soap *soap, int alg, const void *key, int keylen)
  2203. @brief Verifies the SignatureValue of a SignedInfo element.
  2204. @param soap context
  2205. @param[in] alg is a signature algorith, such as SOAP_SMD_HMAC_SHA1, SOAP_SMD_VRFY_DSA_SHA1, or SOAP_SMD_VRFY_RSA_SHA1 determined by the SignedInfo/SignatureMethod
  2206. @param[in] key to use to verify (HMAC or EVP_PKEY)
  2207. @param[in] keylen length of HMAC key
  2208. @return SOAP_OK, SOAP_EOM, or fault
  2209. This function searches for the SignedInfo element in the soap->dom DOM tree to
  2210. verify the signature in the SignatureValue element. Using the DOM ensures we
  2211. will verify the signature of a SignedInfo as it was exactly received by the
  2212. parser, by using the -DWITH_DOM compile flag and SOAP_XML_DOM runtime flag. If
  2213. there is no DOM, it verifies the signature of the deserialized SignedInfo
  2214. element in the SOAP Header. However, serializing deserialized data may change
  2215. the octet stream that was signed, unless we're using gSOAP as producers and
  2216. consumers (with the SOAP_XML_INDENT flag reset).
  2217. */
  2218. int
  2219. soap_wsse_verify_SignatureValue(struct soap *soap, int alg, const void *key, int keylen)
  2220. { ds__SignatureType *signature = soap_wsse_Signature(soap);
  2221. DBGFUN1("soap_wsse_verify_SignatureValue", "alg=%x", alg);
  2222. /* always need an HMAC secret key or DSA/RSA public key to verify */
  2223. if (!key)
  2224. return soap_wsse_fault(soap, wsse__SecurityTokenUnavailable, NULL);
  2225. /* verify the SignedInfo element with the SignatureValue element */
  2226. if (signature
  2227. && signature->SignedInfo
  2228. && signature->SignatureValue)
  2229. { char *sig;
  2230. const char *sigval;
  2231. int method, siglen, sigvallen;
  2232. /* check that we are using the intended signature algorithm */
  2233. if (soap_wsse_get_SignedInfo_SignatureMethod(soap, &method))
  2234. return soap->error;
  2235. if (alg != method)
  2236. return soap_wsse_fault(soap, wsse__FailedCheck, "Incorrect signature algorithm used");
  2237. /* retrieve the signature */
  2238. sigval = soap_base642s(soap, signature->SignatureValue, NULL, 0, &sigvallen);
  2239. /* search the DOM for SignedInfo */
  2240. if (soap->dom)
  2241. { struct soap_dom_element *elt;
  2242. /* traverse the DOM while searching for SignedInfo in the ds namespace */
  2243. for (elt = soap->dom; elt; elt = soap_dom_next_element(elt))
  2244. { if (elt->name
  2245. && elt->nstr
  2246. && !strcmp(elt->nstr, ds_URI)
  2247. && (!strcmp(elt->name, "SignedInfo") || !soap_tag_cmp(elt->name, "*:SignedInfo")))
  2248. break;
  2249. }
  2250. /* found it? */
  2251. if (elt)
  2252. { int err = SOAP_OK;
  2253. /* should not include leading whitespace in signature verification */
  2254. elt->head = NULL;
  2255. /* use smdevp engine to verify SignedInfo */
  2256. if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC)
  2257. sig = (char*)soap_malloc(soap, soap_smd_size(alg, key));
  2258. else
  2259. { sig = (char*)sigval;
  2260. siglen = sigvallen;
  2261. }
  2262. if (signature->SignedInfo->CanonicalizationMethod
  2263. && signature->SignedInfo->CanonicalizationMethod->Algorithm
  2264. && !strcmp(signature->SignedInfo->CanonicalizationMethod->Algorithm, c14n_URI))
  2265. { struct soap_dom_element *prt;
  2266. struct soap_dom_attribute *att;
  2267. /* recanonicalize DOM while keeping content "as is" */
  2268. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Verifying signed canonicalized DOM\n"));
  2269. soap->mode &= ~SOAP_XML_DOM;
  2270. soap->mode |= SOAP_XML_CANONICAL | SOAP_DOM_ASIS;
  2271. err = soap_smd_begin(soap, alg, key, keylen);
  2272. /* emit all xmlns attributes of ancestors */
  2273. while (soap->nlist)
  2274. { register struct soap_nlist *np = soap->nlist->next;
  2275. SOAP_FREE(soap, soap->nlist);
  2276. soap->nlist = np;
  2277. }
  2278. /* TODO: consider moving this into dom.cpp */
  2279. for (prt = elt->prnt; prt; prt = prt->prnt)
  2280. { for (att = prt->atts; att; att = att->next)
  2281. if (!strncmp(att->name, "xmlns:", 6) && !soap_lookup_ns(soap, att->name + 6, strlen(att->name + 6)))
  2282. soap_attribute(soap, att->name, att->data);
  2283. }
  2284. for (prt = elt->prnt; prt; prt = prt->prnt)
  2285. { for (att = prt->atts; att; att = att->next)
  2286. if (!strcmp(att->name, "xmlns"))
  2287. { soap_attribute(soap, att->name, att->data);
  2288. break;
  2289. }
  2290. }
  2291. }
  2292. else
  2293. { /* compute digest over DOM "as is" */
  2294. soap->mode &= ~(SOAP_XML_CANONICAL | SOAP_XML_DOM);
  2295. soap->mode |= SOAP_DOM_ASIS;
  2296. err = soap_smd_begin(soap, alg, key, keylen);
  2297. }
  2298. /* do not dump namespace table xmlns bindings */
  2299. soap->ns = 2;
  2300. /* compute digest */
  2301. soap->feltbegout = NULL;
  2302. soap->feltendout = NULL;
  2303. if (!err)
  2304. err = soap_out_xsd__anyType(soap, NULL, 0, elt, NULL);
  2305. if (soap_smd_end(soap, sig, &siglen) || err)
  2306. return soap_wsse_fault(soap, wsse__FailedCheck, "The signed SignedInfo SignatureValue is invalid");
  2307. if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC)
  2308. { if (siglen != sigvallen || memcmp(sig, sigval, siglen))
  2309. return soap_wsse_fault(soap, wsse__FailedCheck, "The HMAC-signed SignedInfo is invalid");
  2310. }
  2311. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Signature in DOM is valid\n"));
  2312. return SOAP_OK;
  2313. }
  2314. }
  2315. else
  2316. { int err = SOAP_OK;
  2317. const char *c14nexclude;
  2318. soap_mode mode;
  2319. /* serialize the SignedInfo element as it appeared in the SOAP Header */
  2320. soap->level = 4;
  2321. c14nexclude = soap->c14nexclude;
  2322. soap->c14nexclude = "ds";
  2323. mode = soap->mode;
  2324. if (signature->SignedInfo->CanonicalizationMethod)
  2325. soap->mode |= SOAP_XML_CANONICAL;
  2326. else
  2327. soap->mode &= ~SOAP_XML_CANONICAL;
  2328. if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC)
  2329. sig = (char*)soap_malloc(soap, soap_smd_size(alg, key));
  2330. else
  2331. { sig = (char*)sigval;
  2332. siglen = sigvallen;
  2333. }
  2334. err = soap_smd_begin(soap, alg, key, keylen);
  2335. if (!err)
  2336. err = soap_out_ds__SignedInfoType(soap, "ds:SignedInfo", 0, signature->SignedInfo, NULL);
  2337. soap->mode = mode;
  2338. soap->c14nexclude = c14nexclude;
  2339. if (soap_smd_end(soap, sig, &siglen) || err)
  2340. return soap_wsse_fault(soap, wsse__FailedCheck, "The signed serialized SignedInfo SignatureValue is invalid");
  2341. if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC)
  2342. { if (siglen != sigvallen || memcmp(sig, sigval, siglen))
  2343. return soap_wsse_fault(soap, wsse__FailedCheck, "The HMAC-signed serialized SignedInfo is invalid");
  2344. }
  2345. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Signature is valid\n"));
  2346. return SOAP_OK;
  2347. }
  2348. }
  2349. return soap_wsse_fault(soap, wsse__FailedCheck, "SignedInfo required");
  2350. }
  2351. /**
  2352. @fn int soap_wsse_verify_SignedInfo(struct soap *soap)
  2353. @brief Verifies the digest values of the XML elements referenced by the SignedInfo References.
  2354. @param soap context
  2355. @return SOAP_OK or fault
  2356. This function searches for the SignedInfo element in the soap->dom DOM tree to
  2357. verify the digests contained therein. Using the DOM ensures we will verify the
  2358. digests of the locally signed elements as they were exactly received by the
  2359. parser, by using the -DWITH_DOM compile flag and SOAP_XML_DOM runtime flag. If
  2360. there is no DOM, the function fails.
  2361. */
  2362. int
  2363. soap_wsse_verify_SignedInfo(struct soap *soap)
  2364. { ds__SignedInfoType *signedInfo = soap_wsse_SignedInfo(soap);
  2365. DBGFUN("soap_wsse_verify_SignedInfo");
  2366. if (signedInfo)
  2367. { int i;
  2368. /* must have at least one reference element */
  2369. if (signedInfo->__sizeReference == 0)
  2370. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Missing SignedInfo/Reference");
  2371. /* As an alternative to the current implementatin, this might be a good place to re-canonicalize the entire DOM to improve interop. Two DOMs can be used: one with non-c14n XML and one with c14n XML so we can handle multiple different transforms. */
  2372. /* for each reference element, check the digest */
  2373. for (i = 0; i < signedInfo->__sizeReference; i++)
  2374. { ds__ReferenceType *reference = signedInfo->Reference[i];
  2375. /* reference element is complete? */
  2376. if (!reference->URI
  2377. || !reference->DigestMethod
  2378. || !reference->DigestMethod->Algorithm
  2379. || !reference->DigestValue)
  2380. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Incomplete SignedInfo/Reference");
  2381. /* reference is local? */
  2382. if (*reference->URI == '#')
  2383. { int alg, canonical;
  2384. unsigned char hash[SOAP_SMD_MAX_SIZE];
  2385. /* digest algorithm */
  2386. if (!strcmp(reference->DigestMethod->Algorithm, ds_sha1URI))
  2387. alg = SOAP_SMD_DGST_SHA1;
  2388. else if (!strcmp(reference->DigestMethod->Algorithm, ds_sha256URI))
  2389. alg = SOAP_SMD_DGST_SHA256;
  2390. else if (!strcmp(reference->DigestMethod->Algorithm, ds_sha512URI))
  2391. alg = SOAP_SMD_DGST_SHA512;
  2392. else
  2393. return soap_wsse_fault(soap, wsse__UnsupportedAlgorithm, reference->DigestMethod->Algorithm);
  2394. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Verifying digest of locally referenced data %s alg=%x\n", reference->URI, alg));
  2395. /* if reference has a transform, it should be an exc-c14n transform */
  2396. if (reference->Transforms)
  2397. { if (reference->Transforms->__sizeTransform != 1
  2398. || !reference->Transforms->Transform[0].Algorithm
  2399. || strcmp(reference->Transforms->Transform[0].Algorithm, c14n_URI))
  2400. return soap_wsse_fault(soap, wsse__UnsupportedAlgorithm, reference->Transforms->Transform[0].Algorithm);
  2401. canonical = 1;
  2402. }
  2403. else
  2404. canonical = 0;
  2405. /* convert base64 digest to binary */
  2406. soap_base642s(soap, reference->DigestValue, (char*)hash, SOAP_SMD_MAX_SIZE, NULL);
  2407. /* verify the digest of a locally signed element */
  2408. if (soap_wsse_verify_digest(soap, alg, canonical, reference->URI + 1, hash))
  2409. return soap->error;
  2410. }
  2411. }
  2412. return SOAP_OK;
  2413. }
  2414. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Missing SignedInfo");
  2415. }
  2416. /**
  2417. @fn int soap_wsse_verify_digest(struct soap *soap, int alg, int canonical, const char *id, unsigned char hash[SOAP_SMD_MAX_SIZE])
  2418. @brief Verifies the digest value of an XML element referenced by id against the hash.
  2419. @param soap context
  2420. @param[in] alg digest algorithm
  2421. @param[in] canonical flag indicating that element is signed in exc-c14n form
  2422. @param[in] id string of the XML element to verify
  2423. @param[in] hash digest value to verify against
  2424. @return SOAP_OK or fault
  2425. */
  2426. int
  2427. soap_wsse_verify_digest(struct soap *soap, int alg, int canonical, const char *id, unsigned char hash[SOAP_SMD_MAX_SIZE])
  2428. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  2429. struct soap_dom_element *elt, *dom = NULL;
  2430. DBGFUN3("soap_wsse_verify_digest", "alg=%x", alg, "canonical=%d", canonical, "id=%s", id);
  2431. if (!data)
  2432. return soap_set_receiver_error(soap, "soap_wsse_verify_digest", "Plugin not registered", SOAP_PLUGIN_ERROR);
  2433. /* traverse the DOM to find the element with matching wsu:Id or ds:Id */
  2434. for (elt = soap->dom; elt; elt = soap_dom_next_element(elt))
  2435. { struct soap_dom_attribute *att;
  2436. for (att = elt->atts; att; att = att->next)
  2437. { /* check attribute */
  2438. if (att->name
  2439. && att->nstr
  2440. && (!strcmp(att->nstr, wsu_URI) || !strcmp(att->nstr, ds_URI))
  2441. && (!strcmp(att->name, "Id") || !soap_tag_cmp(att->name, "*:Id")))
  2442. { /* found a match, compare attribute value with id */
  2443. if (att->data && !strcmp(att->data, id))
  2444. { if (dom)
  2445. return soap_wsse_fault(soap, wsse__FailedCheck, "SignedInfo duplicate Id");
  2446. dom = elt;
  2447. /* elt = NULL; break; */ /* improves speed but skips duplicate Id check */
  2448. }
  2449. }
  2450. }
  2451. }
  2452. if (dom)
  2453. { unsigned char HA[SOAP_SMD_MAX_SIZE];
  2454. int len, err = SOAP_OK;
  2455. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Computing digest for Id=%s\n", id));
  2456. /* do not hash leading whitespace */
  2457. dom->head = NULL;
  2458. /* canonical or as-is? */
  2459. if (canonical)
  2460. { struct soap_dom_element *prt;
  2461. struct soap_dom_attribute *att;
  2462. soap->mode |= SOAP_XML_CANONICAL | SOAP_DOM_ASIS;
  2463. err = soap_smd_begin(soap, alg, NULL, 0);
  2464. /* emit all xmlns attributes of ancestors */
  2465. while (soap->nlist)
  2466. { register struct soap_nlist *np = soap->nlist->next;
  2467. SOAP_FREE(soap, soap->nlist);
  2468. soap->nlist = np;
  2469. }
  2470. /* TODO: consider moving this into dom.cpp */
  2471. for (prt = dom->prnt; prt; prt = prt->prnt)
  2472. { for (att = prt->atts; att; att = att->next)
  2473. { if (!strncmp(att->name, "xmlns:", 6) && !soap_lookup_ns(soap, att->name + 6, strlen(att->name + 6)))
  2474. { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attribute=%s\n", att->name));
  2475. soap_attribute(soap, att->name, att->data);
  2476. }
  2477. }
  2478. }
  2479. for (prt = dom->prnt; prt; prt = prt->prnt)
  2480. { for (att = prt->atts; att; att = att->next)
  2481. { if (!strcmp(att->name, "xmlns"))
  2482. { soap_attribute(soap, att->name, att->data);
  2483. break;
  2484. }
  2485. }
  2486. }
  2487. }
  2488. else
  2489. { /* compute digest over DOM "as is" */
  2490. soap->mode &= ~SOAP_XML_CANONICAL;
  2491. soap->mode |= SOAP_DOM_ASIS;
  2492. err = soap_smd_begin(soap, alg, NULL, 0);
  2493. }
  2494. /* do not dump namespace table xmlns bindings */
  2495. soap->ns = 2;
  2496. /* compute digest */
  2497. soap->feltbegout = NULL;
  2498. soap->feltendout = NULL;
  2499. if (!err)
  2500. err = soap_out_xsd__anyType(soap, NULL, 0, dom, NULL);
  2501. if (soap_smd_end(soap, (char*)HA, &len) || err)
  2502. return soap_wsse_fault(soap, wsse__FailedCheck, "Digest computation failed");
  2503. /* compare digests, success if identical */
  2504. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Comparing digest hashes\n"));
  2505. DBGHEX(TEST, hash, len);
  2506. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n--\n"));
  2507. DBGHEX(TEST, HA, len);
  2508. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\n"));
  2509. if (!memcmp(hash, HA, (size_t)len))
  2510. return SOAP_OK;
  2511. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  2512. }
  2513. if (data->vrfy_alg & SOAP_WSSE_IGNORE_EXTRA_REFS)
  2514. return SOAP_OK;
  2515. return soap_wsse_fault(soap, wsse__FailedCheck, "SignedInfo reference URI target not found");
  2516. }
  2517. /******************************************************************************\
  2518. *
  2519. * ds:Signature/KeyInfo
  2520. *
  2521. \******************************************************************************/
  2522. /**
  2523. @fn ds__KeyInfoType* soap_wsse_add_KeyInfo(struct soap *soap)
  2524. @brief Adds KeyInfo element.
  2525. @param soap context
  2526. @return ds__KeyInfo object
  2527. */
  2528. struct ds__KeyInfoType*
  2529. soap_wsse_add_KeyInfo(struct soap *soap)
  2530. { ds__SignatureType *signature = soap_wsse_add_Signature(soap);
  2531. if (!signature->KeyInfo)
  2532. { signature->KeyInfo = (ds__KeyInfoType*)soap_malloc(soap, sizeof(ds__KeyInfoType));
  2533. if (!signature->KeyInfo)
  2534. return NULL;
  2535. }
  2536. soap_default_ds__KeyInfoType(soap, signature->KeyInfo);
  2537. return signature->KeyInfo;
  2538. }
  2539. /**
  2540. @fn ds__KeyInfoType* soap_wsse_KeyInfo(struct soap *soap)
  2541. @brief Returns KeyInfo element if present.
  2542. @param soap context
  2543. @return ds__KeyInfo object or NULL
  2544. */
  2545. struct ds__KeyInfoType*
  2546. soap_wsse_KeyInfo(struct soap *soap)
  2547. { ds__SignatureType *signature = soap_wsse_Signature(soap);
  2548. if (signature)
  2549. return signature->KeyInfo;
  2550. return NULL;
  2551. }
  2552. /******************************************************************************\
  2553. *
  2554. * ds:Signature/KeyInfo/KeyName
  2555. *
  2556. \******************************************************************************/
  2557. /**
  2558. @fn int soap_wsse_add_KeyInfo_KeyName(struct soap *soap, const char *name)
  2559. @brief Adds KeyName element.
  2560. @param soap context
  2561. @param[in] name string of the KeyName
  2562. @return SOAP_OK
  2563. Note: the recommended method to add Key information is to utilize KeyIdentifier
  2564. instead of KeyName. A KeyName is useful mainly for internal use.
  2565. */
  2566. int
  2567. soap_wsse_add_KeyInfo_KeyName(struct soap *soap, const char *name)
  2568. { ds__KeyInfoType *keyInfo = soap_wsse_add_KeyInfo(soap);
  2569. DBGFUN1("soap_wsse_add_KeyInfo_KeyName", "name=%s", name);
  2570. /* populate the KeyName element */
  2571. keyInfo->KeyName = soap_strdup(soap, name);
  2572. return SOAP_OK;
  2573. }
  2574. /**
  2575. @fn int soap_wsse_get_KeyInfo_KeyName(struct soap *soap)
  2576. @brief Returns KeyName element if present.
  2577. @param soap context
  2578. @return string or NULL
  2579. */
  2580. const char*
  2581. soap_wsse_get_KeyInfo_KeyName(struct soap *soap)
  2582. { ds__KeyInfoType *keyInfo = soap_wsse_KeyInfo(soap);
  2583. DBGFUN("soap_wsse_get_KeyInfo_KeyName");
  2584. if (!keyInfo)
  2585. return NULL;
  2586. return keyInfo->KeyName;
  2587. }
  2588. /******************************************************************************\
  2589. *
  2590. * ds:Signature/KeyInfo/wsse:SecurityTokenReference/Reference/@URI
  2591. *
  2592. \******************************************************************************/
  2593. /**
  2594. @fn int soap_wsse_add_KeyInfo_SecurityTokenReferenceURI(struct soap *soap, const char *URI, const char *valueType)
  2595. @brief Adds KeyInfo element with SecurityTokenReference URI.
  2596. @param soap context
  2597. @param[in] URI string referencing a security token
  2598. @param[in] valueType string or NULL
  2599. @return SOAP_OK
  2600. */
  2601. int
  2602. soap_wsse_add_KeyInfo_SecurityTokenReferenceURI(struct soap *soap, const char *URI, const char *valueType)
  2603. { ds__KeyInfoType *keyInfo = soap_wsse_add_KeyInfo(soap);
  2604. DBGFUN2("soap_wsse_add_KeyInfo_SecurityTokenReferenceURI", "URI=%s", URI?URI:"", "valueType=%s", valueType?valueType:"");
  2605. /* allocate SecurityTokenReference element if we don't have one already */
  2606. if (!keyInfo->wsse__SecurityTokenReference)
  2607. { keyInfo->wsse__SecurityTokenReference = (_wsse__SecurityTokenReference*)soap_malloc(soap, sizeof(_wsse__SecurityTokenReference));
  2608. if (!keyInfo->wsse__SecurityTokenReference)
  2609. return soap->error = SOAP_EOM;
  2610. }
  2611. soap_default__wsse__SecurityTokenReference(soap, keyInfo->wsse__SecurityTokenReference);
  2612. /* allocate Reference element */
  2613. keyInfo->wsse__SecurityTokenReference->Reference = (_wsse__Reference*)soap_malloc(soap, sizeof(_wsse__Reference));
  2614. soap_default__wsse__Reference(soap, keyInfo->wsse__SecurityTokenReference->Reference);
  2615. /* populate the Reference element */
  2616. keyInfo->wsse__SecurityTokenReference->Reference->URI = soap_strdup(soap, URI);
  2617. keyInfo->wsse__SecurityTokenReference->Reference->ValueType = soap_strdup(soap, valueType);
  2618. return SOAP_OK;
  2619. }
  2620. /**
  2621. @fn int soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(struct soap *soap, const char *URI)
  2622. @brief Adds KeyInfo element with SecurityTokenReference URI to an X509 cert.
  2623. @param soap context
  2624. @param[in] URI string referencing an X509 certificate
  2625. @return SOAP_OK
  2626. */
  2627. int
  2628. soap_wsse_add_KeyInfo_SecurityTokenReferenceX509(struct soap *soap, const char *URI)
  2629. { return soap_wsse_add_KeyInfo_SecurityTokenReferenceURI(soap, URI, wsse_X509v3URI);
  2630. }
  2631. /**
  2632. @fn const char* soap_wsse_get_KeyInfo_SecurityTokenReferenceURI(struct soap *soap)
  2633. @brief Returns a SecurityTokenReference URI if present.
  2634. @param soap context
  2635. @return string or NULL
  2636. */
  2637. const char*
  2638. soap_wsse_get_KeyInfo_SecurityTokenReferenceURI(struct soap *soap)
  2639. { ds__KeyInfoType *keyInfo = soap_wsse_KeyInfo(soap);
  2640. if (keyInfo
  2641. && keyInfo->wsse__SecurityTokenReference
  2642. && keyInfo->wsse__SecurityTokenReference->Reference)
  2643. return keyInfo->wsse__SecurityTokenReference->Reference->URI;
  2644. return NULL;
  2645. }
  2646. /**
  2647. @fn const char* soap_wsse_get_KeyInfo_SecurityTokenReferenceValueType(struct soap *soap)
  2648. @brief Returns a SecurityTokenReference ValueType if present.
  2649. @param soap context
  2650. @return string or NULL
  2651. */
  2652. const char*
  2653. soap_wsse_get_KeyInfo_SecurityTokenReferenceValueType(struct soap *soap)
  2654. { ds__KeyInfoType *keyInfo = soap_wsse_KeyInfo(soap);
  2655. if (keyInfo
  2656. && keyInfo->wsse__SecurityTokenReference
  2657. && keyInfo->wsse__SecurityTokenReference->Reference)
  2658. return keyInfo->wsse__SecurityTokenReference->Reference->ValueType;
  2659. return NULL;
  2660. }
  2661. /**
  2662. @fn X509* soap_wsse_get_KeyInfo_SecurityTokenReferenceX509(struct soap *soap)
  2663. @brief Returns a X509 certificate if present as a BinarySecurity token.
  2664. @param soap context
  2665. @return X509 object or NULL with wsse:SecurityTokenUnavailable fault
  2666. */
  2667. X509*
  2668. soap_wsse_get_KeyInfo_SecurityTokenReferenceX509(struct soap *soap)
  2669. { const char *URI = soap_wsse_get_KeyInfo_SecurityTokenReferenceURI(soap);
  2670. X509 *cert = NULL;
  2671. DBGFUN("soap_wsse_get_KeyInfo_SecurityTokenReferenceX509");
  2672. if (URI && *URI == '#')
  2673. { const char *valueType;
  2674. valueType = soap_wsse_get_KeyInfo_SecurityTokenReferenceValueType(soap);
  2675. if (!valueType || !strcmp(valueType, wsse_X509v3URI))
  2676. cert = soap_wsse_get_BinarySecurityTokenX509(soap, URI + 1);
  2677. }
  2678. return cert;
  2679. }
  2680. /**
  2681. @fn struct ds__X509IssuerSerialType *soap_wsse_get_KeyInfo_SecurityTokenReferenceX509Data(struct soap *soap)
  2682. @brief Returns ds__X509IssuerSerialType with non-NULL X509IssuerName and non-NULL X509SerialNumber of a X509Data element when present and set.
  2683. @param soap context
  2684. @return pointer to ds__X509IssuerSerialType struct or NULL
  2685. */
  2686. struct ds__X509IssuerSerialType *
  2687. soap_wsse_get_KeyInfo_SecurityTokenReferenceX509Data(struct soap *soap)
  2688. { ds__KeyInfoType *keyInfo = soap_wsse_KeyInfo(soap);
  2689. if (keyInfo
  2690. && keyInfo->wsse__SecurityTokenReference
  2691. && keyInfo->wsse__SecurityTokenReference->ds__X509Data
  2692. && keyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial
  2693. && keyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial->X509IssuerName
  2694. && keyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial->X509SerialNumber)
  2695. return keyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial;
  2696. return NULL;
  2697. }
  2698. /******************************************************************************\
  2699. *
  2700. * ds:Signature/KeyInfo/wsse:SecurityTokenReference/Reference/KeyIdentifier
  2701. *
  2702. \******************************************************************************/
  2703. /**
  2704. @fn int soap_wsse_add_KeyInfo_SecurityTokenReferenceKeyIdentifier(struct soap *soap, const char *id, const char *valueType, unsigned char *data, int size)
  2705. @brief Adds KeyInfo element with SecurityTokenReference/KeyIdentifier binary data
  2706. @param soap context
  2707. @param[in] id string for signature reference
  2708. @param[in] valueType string
  2709. @param[in] data binary data
  2710. @param[in] size of binary data
  2711. @return SOAP_OK
  2712. */
  2713. int
  2714. soap_wsse_add_KeyInfo_SecurityTokenReferenceKeyIdentifier(struct soap *soap, const char *id, const char *valueType, unsigned char *data, int size)
  2715. { ds__KeyInfoType *keyInfo = soap_wsse_add_KeyInfo(soap);
  2716. DBGFUN2("soap_wsse_add_KeyInfo_SecurityTokenReferenceKeyIdentifier", "id=%s", id?id:"", "valueType=%s", valueType?valueType:"");
  2717. /* allocate SecurityTokenReference if we don't have one already */
  2718. if (!keyInfo->wsse__SecurityTokenReference)
  2719. { keyInfo->wsse__SecurityTokenReference = (_wsse__SecurityTokenReference*)soap_malloc(soap, sizeof(_wsse__SecurityTokenReference));
  2720. if (!keyInfo->wsse__SecurityTokenReference)
  2721. return soap->error = SOAP_EOM;
  2722. }
  2723. soap_default__wsse__SecurityTokenReference(soap, keyInfo->wsse__SecurityTokenReference);
  2724. /* allocate KeyIdentifier */
  2725. keyInfo->wsse__SecurityTokenReference->KeyIdentifier = (_wsse__KeyIdentifier*)soap_malloc(soap, sizeof(_wsse__KeyIdentifier));
  2726. if (!keyInfo->wsse__SecurityTokenReference->KeyIdentifier)
  2727. return soap->error = SOAP_EOM;
  2728. soap_default__wsse__KeyIdentifier(soap, keyInfo->wsse__SecurityTokenReference->KeyIdentifier);
  2729. /* populate KeyIdentifier */
  2730. keyInfo->wsse__SecurityTokenReference->KeyIdentifier->wsu__Id = soap_strdup(soap, id);
  2731. keyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType = soap_strdup(soap, valueType);
  2732. keyInfo->wsse__SecurityTokenReference->KeyIdentifier->EncodingType = (char*)wsse_Base64BinaryURI;
  2733. keyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item = soap_s2base64(soap, data, NULL, size);
  2734. return SOAP_OK;
  2735. }
  2736. /**
  2737. @fn const char* soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifierValueType(struct soap *soap)
  2738. @brief Returns KeyInfo/SecurityTokenReference/KeyIdentifier/ValueType if present
  2739. @param soap context
  2740. @return string or NULL
  2741. */
  2742. const char*
  2743. soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifierValueType(struct soap *soap)
  2744. { ds__KeyInfoType *keyInfo = soap_wsse_KeyInfo(soap);
  2745. DBGFUN("soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifierValueType");
  2746. if (!keyInfo
  2747. || !keyInfo->wsse__SecurityTokenReference
  2748. || !keyInfo->wsse__SecurityTokenReference->KeyIdentifier)
  2749. return NULL;
  2750. return keyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType;
  2751. }
  2752. /**
  2753. @fn const unsigned char* soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifier(struct soap *soap, int *size)
  2754. @brief Returns KeyInfo/SecurityTokenReference/KeyIdentifier binary data
  2755. @param soap context
  2756. @param[out] size is set to the size of the decoded data
  2757. @return data or NULL
  2758. */
  2759. const unsigned char*
  2760. soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifier(struct soap *soap, int *size)
  2761. { ds__KeyInfoType *keyInfo = soap_wsse_KeyInfo(soap);
  2762. DBGFUN("soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifier");
  2763. if (!keyInfo
  2764. || !keyInfo->wsse__SecurityTokenReference
  2765. || !keyInfo->wsse__SecurityTokenReference->KeyIdentifier)
  2766. return NULL;
  2767. return (unsigned char*)soap_base642s(soap, keyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item, NULL, 0, size);
  2768. }
  2769. /******************************************************************************\
  2770. *
  2771. * ds:Signature/KeyInfo/wsse:SecurityTokenReference/Reference/Embedded
  2772. *
  2773. \******************************************************************************/
  2774. /**
  2775. @fn int soap_wsse_add_KeyInfo_SecurityTokenReferenceEmbedded(struct soap *soap, const char *id, const char *valueType)
  2776. @brief Adds KeyInfo element with Embedded SecurityTokenReference.
  2777. @param soap context
  2778. @param[in] id string for signature reference
  2779. @param[in] valueType string
  2780. @return SOAP_OK
  2781. Note: this function does not add embedded tokens automatically. See code for comments.
  2782. */
  2783. int
  2784. soap_wsse_add_KeyInfo_SecurityTokenReferenceEmbedded(struct soap *soap, const char *id, const char *valueType)
  2785. { ds__KeyInfoType *keyInfo = soap_wsse_add_KeyInfo(soap);
  2786. DBGFUN("soap_wsse_get_KeyInfo_SecurityTokenReferenceEmbedded");
  2787. /* allocate SecurityTokenReference if we don't have one already */
  2788. if (!keyInfo->wsse__SecurityTokenReference)
  2789. { keyInfo->wsse__SecurityTokenReference = (_wsse__SecurityTokenReference*)soap_malloc(soap, sizeof(_wsse__SecurityTokenReference));
  2790. if (!keyInfo->wsse__SecurityTokenReference)
  2791. return soap->error = SOAP_EOM;
  2792. }
  2793. soap_default__wsse__SecurityTokenReference(soap, keyInfo->wsse__SecurityTokenReference);
  2794. /* allocate Embedded element */
  2795. keyInfo->wsse__SecurityTokenReference->Embedded = (_wsse__Embedded*)soap_malloc(soap, sizeof(_wsse__Embedded));
  2796. if (!keyInfo->wsse__SecurityTokenReference->Embedded)
  2797. return soap->error = SOAP_EOM;
  2798. soap_default__wsse__Embedded(soap, keyInfo->wsse__SecurityTokenReference->Embedded);
  2799. /* populate Embedded element */
  2800. keyInfo->wsse__SecurityTokenReference->Embedded->wsu__Id = soap_strdup(soap, id);
  2801. keyInfo->wsse__SecurityTokenReference->Embedded->ValueType = soap_strdup(soap, valueType);
  2802. /* TODO: Add embedded tokens and assertions. Could use DOM here?
  2803. keyInfo->wsse__SecurityTokenReference->Embedded->xyz = ...;
  2804. */
  2805. return SOAP_OK;
  2806. }
  2807. /******************************************************************************\
  2808. *
  2809. * wsse:Security/xenc:EncryptedKey header element
  2810. *
  2811. \******************************************************************************/
  2812. /**
  2813. @fn int soap_wsse_add_EncryptedKey(struct soap *soap, int alg, const char *URI, X509 *cert, const char *subjectkeyid, const char *issuer, const char *serial)
  2814. @brief Adds EncryptedKey header element and initiates the encryption of the
  2815. SOAP Body.
  2816. @param soap context
  2817. @param[in] alg algorithm to use, SOAP_MEC_ENV_ENC_DES_CBC or SOAP_MEC_ENV_ENC_AEAS256_CBC
  2818. @param[in] URI a unique identifier for the key, required for interoperability
  2819. @param[in] cert the X509 certificate with public key or NULL
  2820. @param[in] subjectkeyid string identification of the subject which when set to non-NULL is used instead of embedding the public key in the message
  2821. @param[in] issuer string to include SecurityTokenReference/X509Data
  2822. @param[in] serial string to include SecurityTokenReference/X509Data
  2823. @return SOAP_OK or error code
  2824. This function adds the encrypted key or subject key ID to the WS-Security
  2825. header and initiates encryption of the SOAP Body. An X509 certificate may be
  2826. provided, or the subjectkeyid, or the issuer and serial number. The certificate
  2827. is embedded in the WS-Security EncryptedKey header. If the subjectkeyid string
  2828. is non-NULL the subject key ID is used in the EncryptedKey header instead of
  2829. the X509 certificate content.
  2830. */
  2831. int
  2832. soap_wsse_add_EncryptedKey(struct soap *soap, int alg, const char *URI, X509 *cert, const char *subjectkeyid, const char *issuer, const char *serial)
  2833. { return soap_wsse_add_EncryptedKey_encrypt_only(soap, alg, URI, cert, subjectkeyid, issuer, serial, NULL);
  2834. }
  2835. /**
  2836. @fn int soap_wsse_add_EncryptedKey_encrypt_only(struct soap *soap, int alg, const char *URI, X509 *cert, const char *subjectkeyid, const char *issuer, const char *serial, const char *tags)
  2837. @brief Adds EncryptedKey header element and initiates encryption of the given
  2838. XML elements specified in the tags string. Should be used in combination with
  2839. soap_wsse_set_wsu_id to set wsu:Id for given XML element tags.
  2840. @param soap context
  2841. @param[in] alg algorithm to use, SOAP_MEC_ENV_ENC_DES_CBC or SOAP_MEC_ENV_ENC_AEAS256_CBC
  2842. @param[in] URI a unique identifier for the key, required for interoperability
  2843. @param[in] cert the X509 certificate with public key or NULL
  2844. @param[in] subjectkeyid string identification of the subject which when set to non-NULL is used instead of embedding the public key in the message
  2845. @param[in] issuer string to include SecurityTokenReference/X509Data
  2846. @param[in] serial string to include SecurityTokenReference/X509Data
  2847. @param[in] tags space-separated string of element tag names to encrypt
  2848. @return xenc__EncryptedKeyType object
  2849. This function adds the encrypted key or subject key ID to the WS-Security
  2850. header and initiates encryption of the SOAP Body. An X509 certificate may be
  2851. provided, or the subjectkeyid, or the issuer and serial number. The certificate
  2852. is embedded in the WS-Security EncryptedKey header. If the subjectkeyid string
  2853. is non-NULL the subject key ID is used in the EncryptedKey header instead of
  2854. the X509 certificate content. Only the XML elements given in the 'tags' string
  2855. as wsu:Id attributed elements are encrypted.
  2856. WARNING:
  2857. Use @ref soap_wsse_add_EncryptedKey_encrypt_only only in combination with
  2858. @ref soap_wsse_set_wsu_id with the tag names of the elements to be encrypted.
  2859. OTHERWISE THE GIVEN XML ELEMENTS ARE NOT ENCRYPTED AND WILL BE SENT IN THE
  2860. CLEAR.
  2861. WARNING:
  2862. The elements identified with @ref soap_wsse_set_wsu_id to encrypt MUST occur
  2863. EXACTLY ONCE in the SOAP Body.
  2864. WARNING:
  2865. Encryption/decryption of elements with simple content (CDATA content) IS NOT
  2866. SUPPORTED. This means that elements you want to encrypt with this function must
  2867. have complex content. That is, only encrypt elements with sub elements or
  2868. encrypt the entire SOAP Body.
  2869. */
  2870. int
  2871. soap_wsse_add_EncryptedKey_encrypt_only(struct soap *soap, int alg, const char *URI, X509 *cert, const char *subjectkeyid, const char *issuer, const char *serial, const char *tags)
  2872. { EVP_PKEY *pubk;
  2873. unsigned char *key;
  2874. int keylen;
  2875. _wsse__Security *security;
  2876. struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  2877. DBGFUN("soap_wsse_add_EncryptedKey");
  2878. if (!data)
  2879. return soap_set_receiver_error(soap, "soap_wsse_add_EncryptedKey", "Plugin not registered", SOAP_PLUGIN_ERROR);
  2880. security = soap_wsse_add_Security(soap);
  2881. /* if we don't have a xenc:EncryptedKey, create one */
  2882. if (!security->xenc__EncryptedKey)
  2883. { if (!(security->xenc__EncryptedKey = (xenc__EncryptedKeyType*)soap_malloc(soap, sizeof(xenc__EncryptedKeyType))))
  2884. return soap->error = SOAP_EOM;
  2885. }
  2886. soap_default_xenc__EncryptedKeyType(soap, security->xenc__EncryptedKey);
  2887. security->xenc__EncryptedKey->Id = soap_strdup(soap, URI);
  2888. if (!(security->xenc__EncryptedKey->EncryptionMethod = (xenc__EncryptionMethodType*)soap_malloc(soap, sizeof(struct xenc__EncryptionMethodType))))
  2889. return soap->error = SOAP_EOM;
  2890. soap_default_xenc__EncryptionMethodType(soap, security->xenc__EncryptedKey->EncryptionMethod);
  2891. /* RSA Version 1.5 or RSA-OAEP */
  2892. alg |= (SOAP_MEC_ENV | SOAP_MEC_ENC);
  2893. if (alg & SOAP_MEC_OAEP)
  2894. { security->xenc__EncryptedKey->EncryptionMethod->Algorithm = (char*)xenc_rsaesURI;
  2895. security->xenc__EncryptedKey->EncryptionMethod->OAEPparams = NULL;
  2896. if (!(security->xenc__EncryptedKey->EncryptionMethod->ds__DigestMethod = (struct ds__DigestMethodType*)soap_malloc(soap, sizeof(struct ds__DigestMethodType))))
  2897. return soap->error = SOAP_EOM;
  2898. soap_default_ds__DigestMethodType(soap, security->xenc__EncryptedKey->EncryptionMethod->ds__DigestMethod);
  2899. security->xenc__EncryptedKey->EncryptionMethod->ds__DigestMethod->Algorithm = (char*)ds_sha1URI;
  2900. }
  2901. else
  2902. security->xenc__EncryptedKey->EncryptionMethod->Algorithm = (char*)xenc_rsa15URI;
  2903. /* KeyInfo */
  2904. if (!(security->xenc__EncryptedKey->ds__KeyInfo = (_ds__KeyInfo*)soap_malloc(soap, sizeof(_ds__KeyInfo))))
  2905. return soap->error = SOAP_EOM;
  2906. soap_default__ds__KeyInfo(soap, security->xenc__EncryptedKey->ds__KeyInfo);
  2907. /* allocate SecurityTokenReference */
  2908. if (!(security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference = (_wsse__SecurityTokenReference*)soap_malloc(soap, sizeof(_wsse__SecurityTokenReference))))
  2909. return soap->error = SOAP_EOM;
  2910. soap_default__wsse__SecurityTokenReference(soap, security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference);
  2911. if (issuer && serial)
  2912. { if (!(security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->ds__X509Data = (struct ds__X509DataType*)soap_malloc(soap, sizeof(struct ds__X509DataType))))
  2913. return soap->error = SOAP_EOM;
  2914. soap_default_ds__X509DataType(soap, security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->ds__X509Data);
  2915. if (!(security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial = (struct ds__X509IssuerSerialType*)soap_malloc(soap, sizeof(struct ds__X509IssuerSerialType))))
  2916. return soap->error = SOAP_EOM;
  2917. soap_default_ds__X509IssuerSerialType(soap, security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial);
  2918. security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial->X509IssuerName = soap_strdup(soap, issuer);
  2919. security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->ds__X509Data->X509IssuerSerial->X509SerialNumber = soap_strdup(soap, serial);
  2920. }
  2921. else
  2922. { /* allocate KeyIdentifier */
  2923. if (!(security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier = (_wsse__KeyIdentifier*)soap_malloc(soap, sizeof(_wsse__KeyIdentifier))))
  2924. return soap->error = SOAP_EOM;
  2925. soap_default__wsse__KeyIdentifier(soap, security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier);
  2926. /* populate KeyIdentifier */
  2927. security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->EncodingType = (char*)wsse_Base64BinaryURI;
  2928. if (subjectkeyid)
  2929. { security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType = (char*)wsse_X509v3SubjectKeyIdentifierURI;
  2930. security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item = soap_s2base64(soap, (unsigned char*)subjectkeyid, NULL, strlen(subjectkeyid));
  2931. }
  2932. else if (cert)
  2933. { unsigned char *der, *s;
  2934. int derlen;
  2935. security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType = (char*)wsse_X509v3URI;
  2936. /* determine the storage requirement */
  2937. derlen = i2d_X509(cert, NULL);
  2938. if (derlen < 0)
  2939. return soap_wsse_fault(soap, wsse__InvalidSecurityToken, "Invalid certificate passed to soap_wsse_add_EncryptedKey_encrypt_only");
  2940. /* use the gSOAP engine's look-aside buffer to temporarily hold the cert */
  2941. if (soap_store_lab(soap, NULL, derlen))
  2942. return SOAP_EOM;
  2943. s = der = (unsigned char*)soap->labbuf;
  2944. /* store in DER format */
  2945. i2d_X509(cert, &s);
  2946. security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item = soap_s2base64(soap, der, NULL, derlen);
  2947. }
  2948. }
  2949. /* CipherData */
  2950. if (!(security->xenc__EncryptedKey->CipherData = (xenc__CipherDataType*)soap_malloc(soap, sizeof(struct xenc__CipherDataType))))
  2951. return soap->error = SOAP_EOM;
  2952. soap_default_xenc__CipherDataType(soap, security->xenc__EncryptedKey->CipherData);
  2953. /* get the public key */
  2954. pubk = X509_get_pubkey(cert);
  2955. if (!pubk)
  2956. return soap_wsse_fault(soap, wsse__InvalidSecurityToken, "Invalid certificate passed to soap_wsse_add_EncryptedKey_encrypt_only");
  2957. /* start encryption engine, get the encrypted secret key */
  2958. key = (unsigned char*)soap_malloc(soap, soap_mec_size(alg, pubk));
  2959. if (data->mec)
  2960. soap_mec_cleanup(soap, data->mec);
  2961. else
  2962. data->mec = (struct soap_mec_data*)SOAP_MALLOC(soap, sizeof(struct soap_mec_data));
  2963. if (soap_mec_begin(soap, data->mec, alg, pubk, key, &keylen))
  2964. { EVP_PKEY_free(pubk);
  2965. return soap->error;
  2966. }
  2967. EVP_PKEY_free(pubk);
  2968. data->enco_alg = alg;
  2969. data->enco_keyname = NULL;
  2970. data->enco_key = key;
  2971. data->enco_keylen = keylen;
  2972. if (!(security->xenc__EncryptedKey->CipherData->CipherValue = soap_s2base64(soap, key, NULL, keylen)))
  2973. return soap->error = SOAP_EOM;
  2974. data->encid = soap_strdup(soap, tags);
  2975. if (!tags)
  2976. { soap->omode |= SOAP_SEC_WSUID;
  2977. if (soap_wsse_add_EncryptedKey_DataReferenceURI(soap, "#Body"))
  2978. return soap->error;
  2979. }
  2980. else
  2981. { char *s, *t;
  2982. /* make space to insert # to each id converted from a tag name */
  2983. t = (char*)soap_malloc(soap, strlen(tags) + 2);
  2984. if (!t)
  2985. return soap->error = SOAP_EOM;
  2986. *t = '#';
  2987. strcpy(t + 1, tags);
  2988. s = soap_wsse_ids(soap, t);
  2989. if (!s)
  2990. return soap->error = SOAP_EOM;
  2991. s++;
  2992. do
  2993. { t = strchr(s, ' ');
  2994. if (t)
  2995. { *t = '\0';
  2996. while (*++t == ' ')
  2997. ;
  2998. }
  2999. *--s = '#';
  3000. if (soap_wsse_add_EncryptedKey_DataReferenceURI(soap, s))
  3001. return soap->error;
  3002. s = t;
  3003. } while (s);
  3004. }
  3005. soap->feltbegout = soap_wsse_element_begin_out;
  3006. soap->feltendout = soap_wsse_element_end_out;
  3007. return SOAP_OK;
  3008. }
  3009. /**
  3010. @fn int soap_wsse_verify_EncryptedKey(struct soap *soap)
  3011. @brief Verifies the EncryptedKey header information (certificate validity
  3012. requires soap->cacert to be set). Retrieves the decryption key from the token
  3013. handler callback to decrypt the decryption key.
  3014. @param soap context
  3015. @return SOAP_OK or error code
  3016. */
  3017. int
  3018. soap_wsse_verify_EncryptedKey(struct soap *soap)
  3019. { _wsse__Security *security = soap_wsse_Security(soap);
  3020. struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3021. DBGFUN("soap_wsse_verify_EncryptedKey");
  3022. if (!data)
  3023. return soap_set_receiver_error(soap, "soap_wsse_verify_EncryptedKey", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3024. /* if we have a xenc:EncryptedKey, check it and start envelope decryption */
  3025. if (security && security->xenc__EncryptedKey)
  3026. { if (!security->xenc__EncryptedKey->EncryptionMethod
  3027. || !security->xenc__EncryptedKey->EncryptionMethod->Algorithm)
  3028. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Invalid Encryption algorithm or key");
  3029. /* verify encrypted key */
  3030. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Verify EncryptedKey alg=%x\n", data->deco_alg));
  3031. if (security->xenc__EncryptedKey->ds__KeyInfo)
  3032. { int keylen;
  3033. if (security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference
  3034. && security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier
  3035. && security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType
  3036. && security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item)
  3037. { if (!strcmp(security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType, wsse_X509v3URI))
  3038. { X509 *cert = NULL;
  3039. const unsigned char *der;
  3040. int derlen;
  3041. der = (unsigned char*)soap_base642s(soap, security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item, NULL, 0, &derlen);
  3042. if (!der)
  3043. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Invalid Encryption algorithm or key");
  3044. cert = d2i_X509(&cert, &der, derlen);
  3045. if (soap_wsse_verify_X509(soap, cert))
  3046. { if (cert)
  3047. X509_free(cert);
  3048. return soap->error;
  3049. }
  3050. /* get the private key from subject name of cert, if not set */
  3051. if (!data->deco_key && data->security_token_handler)
  3052. { char buf[1024];
  3053. data->deco_alg = SOAP_MEC_ENV_DEC_DES_CBC;
  3054. data->deco_key = data->security_token_handler(soap, &data->deco_alg, X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)), &keylen);
  3055. data->deco_keylen = 0;
  3056. }
  3057. if (cert)
  3058. X509_free(cert);
  3059. }
  3060. else if (!data->deco_key && data->security_token_handler && !strcmp(security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->ValueType, wsse_X509v3SubjectKeyIdentifierURI))
  3061. { int subjectkeyidlen;
  3062. const char *subjectkeyid = (char*)soap_base642s(soap, security->xenc__EncryptedKey->ds__KeyInfo->wsse__SecurityTokenReference->KeyIdentifier->__item, NULL, 0, &subjectkeyidlen);
  3063. /* get the private key from subject key id */
  3064. data->deco_alg = SOAP_MEC_ENV_DEC_DES_CBC;
  3065. data->deco_key = data->security_token_handler(soap, &data->deco_alg, subjectkeyid, &keylen);
  3066. data->deco_keylen = 0;
  3067. }
  3068. }
  3069. else if (!data->deco_key && data->security_token_handler)
  3070. { const char *name = NULL;
  3071. /* get the private key from key name or subject name */
  3072. if (security->xenc__EncryptedKey->ds__KeyInfo->KeyName)
  3073. name = security->xenc__EncryptedKey->ds__KeyInfo->KeyName;
  3074. else if (security->xenc__EncryptedKey->ds__KeyInfo->X509Data && security->xenc__EncryptedKey->ds__KeyInfo->X509Data->X509SubjectName)
  3075. name = security->xenc__EncryptedKey->ds__KeyInfo->X509Data->X509SubjectName;
  3076. if (name)
  3077. { data->deco_alg = SOAP_MEC_ENV_DEC_DES_CBC;
  3078. data->deco_key = data->security_token_handler(soap, &data->deco_alg, name, &keylen);
  3079. data->deco_keylen = 0;
  3080. }
  3081. }
  3082. }
  3083. /* start decryption */
  3084. if (data->deco_key && security->xenc__EncryptedKey->CipherData && security->xenc__EncryptedKey->CipherData->CipherValue)
  3085. { int keylen;
  3086. unsigned char *key = (unsigned char*)soap_base642s(soap, security->xenc__EncryptedKey->CipherData->CipherValue, NULL, 0, &keylen);
  3087. if (!strcmp(security->xenc__EncryptedKey->EncryptionMethod->Algorithm, xenc_rsaesURI))
  3088. data->deco_alg |= SOAP_MEC_OAEP;
  3089. else if (strcmp(security->xenc__EncryptedKey->EncryptionMethod->Algorithm, xenc_rsa15URI))
  3090. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Invalid Encryption algorithm or key");
  3091. if (data->mec)
  3092. soap_mec_cleanup(soap, data->mec);
  3093. else
  3094. data->mec = (struct soap_mec_data*)SOAP_MALLOC(soap, sizeof(struct soap_mec_data));
  3095. if (soap_mec_begin(soap, data->mec, data->deco_alg, (SOAP_MEC_KEY_TYPE*)data->deco_key, key, &keylen))
  3096. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  3097. }
  3098. /* do not process EncryptedKey again */
  3099. security->xenc__EncryptedKey = NULL;
  3100. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Verified EncryptedKey alg=%x\n", data->deco_alg));
  3101. }
  3102. return SOAP_OK;
  3103. }
  3104. /**
  3105. @fn void soap_wsse_delete_EncryptedKey(struct soap *soap)
  3106. @brief Deletes EncryptedKey header element.
  3107. @param soap context
  3108. */
  3109. void
  3110. soap_wsse_delete_EncryptedKey(struct soap *soap)
  3111. { _wsse__Security *security = soap_wsse_Security(soap);
  3112. DBGFUN("soap_wsse_delete_EncryptedKey");
  3113. if (security)
  3114. security->xenc__EncryptedKey = NULL;
  3115. }
  3116. /**
  3117. @fn xenc__EncryptedKeyType* soap_wsse_EncryptedKey(struct soap *soap)
  3118. @brief Returns EncryptedKey header element if present.
  3119. @param soap context
  3120. @return xenc__EncryptedKeyType object or NULL
  3121. */
  3122. struct xenc__EncryptedKeyType*
  3123. soap_wsse_EncryptedKey(struct soap *soap)
  3124. { _wsse__Security *security = soap_wsse_Security(soap);
  3125. if (security)
  3126. return security->xenc__EncryptedKey;
  3127. return NULL;
  3128. }
  3129. /******************************************************************************\
  3130. *
  3131. * wsse:Security/xenc:EncryptedKey/ReferenceList/DataReference
  3132. *
  3133. \******************************************************************************/
  3134. /**
  3135. @fn int soap_wsse_add_EncryptedKey_DataReferenceURI(struct soap *soap, const char *URI)
  3136. @brief Adds a DataReference URI to the EncryptedKey header element.
  3137. @param soap context
  3138. @param[in] URI value of the URI ID
  3139. @return SOAP_OK or error code
  3140. */
  3141. int
  3142. soap_wsse_add_EncryptedKey_DataReferenceURI(struct soap *soap, const char *URI)
  3143. { _wsse__Security *security = soap_wsse_add_Security(soap);
  3144. _xenc__ReferenceList *ref;
  3145. int k, n = 0;
  3146. DBGFUN1("soap_wsse_add_EncryptedKey_DataReferenceURI", "URI=%s", URI?URI:"");
  3147. if (!security->xenc__EncryptedKey)
  3148. { if (!(security->xenc__EncryptedKey = (xenc__EncryptedKeyType*)soap_malloc(soap, sizeof(xenc__EncryptedKeyType))))
  3149. return soap->error = SOAP_EOM;
  3150. soap_default_xenc__EncryptedKeyType(soap, security->xenc__EncryptedKey);
  3151. }
  3152. if (!security->xenc__EncryptedKey->ReferenceList)
  3153. { if (!(security->xenc__EncryptedKey->ReferenceList = (struct _xenc__ReferenceList*)soap_malloc(soap, sizeof(struct _xenc__ReferenceList))))
  3154. return soap->error = SOAP_EOM;
  3155. soap_default__xenc__ReferenceList(soap, security->xenc__EncryptedKey->ReferenceList);
  3156. }
  3157. ref = security->xenc__EncryptedKey->ReferenceList;
  3158. k = ref->__size_ReferenceList++;
  3159. /* need to increase space? */
  3160. if (k < 0)
  3161. return soap->error = SOAP_EOM;
  3162. if (k == 0)
  3163. n = 1;
  3164. else if (k >= 1 && (k & (k - 1)) == 0)
  3165. n = 2 * k;
  3166. /* yes we do */
  3167. if (n)
  3168. { struct __xenc__union_ReferenceList *tmp = (struct __xenc__union_ReferenceList*)soap_malloc(soap, n * sizeof(struct __xenc__union_ReferenceList));
  3169. int i;
  3170. if (!tmp)
  3171. return soap->error = SOAP_EOM;
  3172. for (i = 0; i < k; i++)
  3173. tmp[i] = ref->__union_ReferenceList[i];
  3174. security->xenc__EncryptedKey->ReferenceList->__union_ReferenceList = tmp;
  3175. ref = security->xenc__EncryptedKey->ReferenceList;
  3176. }
  3177. /* add entry */
  3178. soap_default___xenc__union_ReferenceList(soap, &ref->__union_ReferenceList[k]);
  3179. if (!(ref->__union_ReferenceList[k].DataReference = (struct xenc__ReferenceType*)soap_malloc(soap, sizeof(struct xenc__ReferenceType))))
  3180. return soap->error = SOAP_EOM;
  3181. soap_default_xenc__ReferenceType(soap, ref->__union_ReferenceList[k].DataReference);
  3182. ref->__union_ReferenceList[k].DataReference->URI = soap_strdup(soap, URI);
  3183. return SOAP_OK;
  3184. }
  3185. /**
  3186. @fn int soap_wsse_add_DataReferenceURI(struct soap *soap, const char *URI)
  3187. @brief Adds a DataReference URI to the WS-Security header element.
  3188. @param soap context
  3189. @param[in] URI value of the URI ID
  3190. @return SOAP_OK or error code
  3191. */
  3192. int
  3193. soap_wsse_add_DataReferenceURI(struct soap *soap, const char *URI)
  3194. { _wsse__Security *security = soap_wsse_add_Security(soap);
  3195. _xenc__ReferenceList *ref;
  3196. int k, n = 0;
  3197. DBGFUN1("soap_wsse_add_DataReferenceURI", "URI=%s", URI?URI:"");
  3198. /* initial alloc */
  3199. if (!security->xenc__ReferenceList)
  3200. { if (!(security->xenc__ReferenceList = (struct _xenc__ReferenceList*)soap_malloc(soap, sizeof(struct _xenc__ReferenceList))))
  3201. return soap->error = SOAP_EOM;
  3202. soap_default__xenc__ReferenceList(soap, security->xenc__ReferenceList);
  3203. }
  3204. ref = security->xenc__ReferenceList;
  3205. k = ref->__size_ReferenceList++;
  3206. /* need to increase space? */
  3207. if (k < 0)
  3208. return soap->error = SOAP_EOM;
  3209. if (k == 0)
  3210. n = 1;
  3211. else if (k >= 1 && (k & (k - 1)) == 0)
  3212. n = 2 * k;
  3213. /* yes we do */
  3214. if (n)
  3215. { struct __xenc__union_ReferenceList *tmp = (struct __xenc__union_ReferenceList*)soap_malloc(soap, n * sizeof(struct __xenc__union_ReferenceList));
  3216. int i;
  3217. if (!tmp)
  3218. return soap->error = SOAP_EOM;
  3219. for (i = 0; i < k; i++)
  3220. tmp[i] = ref->__union_ReferenceList[i];
  3221. security->xenc__ReferenceList->__union_ReferenceList = tmp;
  3222. ref = security->xenc__ReferenceList;
  3223. }
  3224. /* add entry */
  3225. soap_default___xenc__union_ReferenceList(soap, &ref->__union_ReferenceList[k]);
  3226. if (!(ref->__union_ReferenceList[k].DataReference = (struct xenc__ReferenceType*)soap_malloc(soap, sizeof(struct xenc__ReferenceType))))
  3227. return soap->error = SOAP_EOM;
  3228. soap_default_xenc__ReferenceType(soap, ref->__union_ReferenceList[k].DataReference);
  3229. ref->__union_ReferenceList[k].DataReference->URI = soap_strdup(soap, URI);
  3230. return SOAP_OK;
  3231. }
  3232. /******************************************************************************\
  3233. *
  3234. * xenc:EncryptedData
  3235. *
  3236. \******************************************************************************/
  3237. /**
  3238. @fn int soap_wsse_add_EncryptedData_KeyInfo_KeyName(struct soap *soap, const char *keyname)
  3239. @brief Adds EncryptedData/ds:KeyInfo/Keyname elements.
  3240. @param soap context
  3241. @param[in] keyname name of the key
  3242. @return SOAP_OK or error code
  3243. This function adds the name of the key to each EncryptedData element to
  3244. identify the shared secret key used for encryption.
  3245. */
  3246. int
  3247. soap_wsse_add_EncryptedData_KeyInfo_KeyName(struct soap *soap, const char *keyname)
  3248. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3249. DBGFUN("soap_wsse_add_EncryptedData_KeyInfo_KeyName");
  3250. if (!data)
  3251. return soap_set_receiver_error(soap, "soap_wsse_add_EncryptedData_KeyInfo_KeyName", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3252. data->enco_keyname = soap_strdup(soap, keyname);
  3253. return SOAP_OK;
  3254. }
  3255. /******************************************************************************\
  3256. *
  3257. * Faults
  3258. *
  3259. \******************************************************************************/
  3260. /**
  3261. @fn int soap_wsse_sender_fault_subcode(struct soap *soap, const char *faultsubcode, const char *faultstring, const char *faultdetail)
  3262. @brief Sets sender SOAP Fault (sub)code for server fault response.
  3263. @param soap context
  3264. @param[in] faultsubcode sub code string
  3265. @param[in] faultstring fault string
  3266. @param[in] faultdetail detail string
  3267. @return SOAP_FAULT
  3268. */
  3269. int
  3270. soap_wsse_sender_fault_subcode(struct soap *soap, const char *faultsubcode, const char *faultstring, const char *faultdetail)
  3271. {
  3272. #if defined(SOAP_WSA_2003) || defined(SOAP_WSA_2004) || defined(SOAP_WSA_200408) || defined(SOAP_WSA_2005)
  3273. return soap_wsa_sender_fault_subcode(soap, faultsubcode, faultstring, faultdetail);
  3274. #else
  3275. return soap_sender_fault_subcode(soap, faultsubcode, faultstring, faultdetail);
  3276. #endif
  3277. }
  3278. /**
  3279. @fn int soap_wsse_receiver_fault_subcode(struct soap *soap, const char *faultsubcode, const char *faultstring, const char *faultdetail)
  3280. @brief Sets receiver SOAP Fault (sub)code for server fault response.
  3281. @param soap context
  3282. @param[in] faultsubcode sub code string
  3283. @param[in] faultstring fault string
  3284. @param[in] faultdetail detail string
  3285. @return SOAP_FAULT
  3286. */
  3287. int
  3288. soap_wsse_receiver_fault_subcode(struct soap *soap, const char *faultsubcode, const char *faultstring, const char *faultdetail)
  3289. {
  3290. #if defined(SOAP_WSA_2003) || defined(SOAP_WSA_2004) || defined(SOAP_WSA_200408) || defined(SOAP_WSA_2005)
  3291. return soap_wsa_receiver_fault_subcode(soap, faultsubcode, faultstring, faultdetail);
  3292. #else
  3293. return soap_receiver_fault_subcode(soap, faultsubcode, faultstring, faultdetail);
  3294. #endif
  3295. }
  3296. /**
  3297. @fn int soap_wsse_sender_fault(struct soap *soap, const char *faultstring, const char *faultdetail)
  3298. @brief Sets sender SOAP Fault for server fault response.
  3299. @param soap context
  3300. @param[in] faultstring fault string
  3301. @param[in] faultdetail detail string
  3302. @return SOAP_FAULT
  3303. */
  3304. int
  3305. soap_wsse_sender_fault(struct soap *soap, const char *faultstring, const char *faultdetail)
  3306. { return soap_wsse_sender_fault_subcode(soap, NULL, faultstring, faultdetail);
  3307. }
  3308. /**
  3309. @fn int soap_wsse_receiver_fault(struct soap *soap, const char *faultstring, const char *faultdetail)
  3310. @brief Sets receiver SOAP Fault for server fault response.
  3311. @param soap context
  3312. @param[in] faultstring fault string
  3313. @param[in] faultdetail detail string
  3314. @return SOAP_FAULT
  3315. */
  3316. int
  3317. soap_wsse_receiver_fault(struct soap *soap, const char *faultstring, const char *faultdetail)
  3318. { return soap_wsse_receiver_fault_subcode(soap, NULL, faultstring, faultdetail);
  3319. }
  3320. /**
  3321. @fn int soap_wsse_fault(struct soap *soap, wsse__FaultcodeEnum fault, const char *detail)
  3322. @brief Sets SOAP Fault (sub)code for server response.
  3323. @param soap context
  3324. @param[in] fault is one of wsse:FaultcodeEnum
  3325. @param[in] detail string with optional text message
  3326. @return SOAP_FAULT
  3327. */
  3328. int
  3329. soap_wsse_fault(struct soap *soap, wsse__FaultcodeEnum fault, const char *detail)
  3330. { const char *code = soap_wsse__FaultcodeEnum2s(soap, fault);
  3331. DBGFUN2("soap_wsse_fault", "fault=%s", code?code:"", "detail=%s", detail?detail:"");
  3332. /* remove incorrect or incomplete Security header */
  3333. soap_wsse_delete_Security(soap);
  3334. /* populate the SOAP Fault as per WS-Security spec */
  3335. /* detail = NULL; */ /* uncomment when detail text not recommended */
  3336. /* use WSA to populate the SOAP Header when WSA is used */
  3337. switch (fault)
  3338. { case wsse__UnsupportedSecurityToken:
  3339. return soap_wsse_sender_fault_subcode(soap, code, "An unsupported token was provided", detail);
  3340. case wsse__UnsupportedAlgorithm:
  3341. return soap_wsse_sender_fault_subcode(soap, code, "An unsupported signature or encryption algorithm was used", detail);
  3342. case wsse__InvalidSecurity:
  3343. return soap_wsse_sender_fault_subcode(soap, code, "An error was discovered processing the <wsse:Security> header", detail);
  3344. case wsse__InvalidSecurityToken:
  3345. return soap_wsse_sender_fault_subcode(soap, code, "An invalid security token was provided", detail);
  3346. case wsse__FailedAuthentication:
  3347. return soap_wsse_sender_fault_subcode(soap, code, "The security token could not be authenticated or authorized", detail);
  3348. case wsse__FailedCheck:
  3349. return soap_wsse_sender_fault_subcode(soap, code, "The signature or decryption was invalid", detail);
  3350. case wsse__SecurityTokenUnavailable:
  3351. return soap_wsse_sender_fault_subcode(soap, code, "Referenced security token could not be retrieved", detail);
  3352. }
  3353. return SOAP_FAULT;
  3354. }
  3355. /******************************************************************************\
  3356. *
  3357. * Digest authentication session management
  3358. *
  3359. \******************************************************************************/
  3360. /**
  3361. @fn static int soap_wsse_session_verify(struct soap *soap, const char hash[SOAP_SMD_SHA1_SIZE], const char *created, const char *nonce)
  3362. @brief Verifies and updates the digest, nonce, and creation time against the digest authentication session database to prevent replay attacks.
  3363. @param soap context
  3364. @param[in] hash binary digest value of PasswordDigest
  3365. @param[in] created string
  3366. @param[in] nonce string (base64)
  3367. @return SOAP_OK or SOAP_FAULT
  3368. */
  3369. static int
  3370. soap_wsse_session_verify(struct soap *soap, const char hash[SOAP_SMD_SHA1_SIZE], const char *created, const char *nonce)
  3371. { struct soap_wsse_session *session;
  3372. time_t expired, now = time(NULL);
  3373. DBGFUN("soap_wsse_session_verify");
  3374. soap_s2dateTime(soap, created, &expired);
  3375. /* creation time in the future? */
  3376. if (expired > now + SOAP_WSSE_CLKSKEW)
  3377. return soap_wsse_fault(soap, wsse__FailedAuthentication, "Authorization request in future");
  3378. expired += SOAP_WSSE_NONCETIME;
  3379. /* expired? */
  3380. if (expired <= now)
  3381. return soap_wsse_fault(soap, wsse__FailedAuthentication, "Authentication expired");
  3382. /* purge expired messages, but don't do this all the time to improve efficiency */
  3383. if (now % 10 == 0)
  3384. soap_wsse_session_cleanup(soap);
  3385. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Verifying session nonce=%s\n", nonce));
  3386. /* enter mutex to check and update session */
  3387. MUTEX_LOCK(soap_wsse_session_lock);
  3388. for (session = soap_wsse_session; session; session = session->next)
  3389. { if (!memcmp(session->hash, hash, SOAP_SMD_SHA1_SIZE) && !strcmp(session->nonce, nonce))
  3390. break;
  3391. }
  3392. /* if not found, allocate new session data */
  3393. if (!session)
  3394. { session = (struct soap_wsse_session*)malloc(sizeof(struct soap_wsse_session) + strlen(nonce));
  3395. if (session)
  3396. { session->next = soap_wsse_session;
  3397. session->expired = expired;
  3398. memcpy(session->hash, hash, SOAP_SMD_SHA1_SIZE);
  3399. strcpy(session->nonce, nonce);
  3400. soap_wsse_session = session;
  3401. }
  3402. session = NULL;
  3403. }
  3404. /* exit mutex */
  3405. MUTEX_UNLOCK(soap_wsse_session_lock);
  3406. /* if replay attack, return non-descript failure */
  3407. if (session)
  3408. return soap_wsse_fault(soap, wsse__FailedAuthentication, NULL);
  3409. return SOAP_OK;
  3410. }
  3411. /**
  3412. @fn static void soap_wsse_session_cleanup(struct soap *soap)
  3413. @brief Removes expired authentication data from the digest authentication session database.
  3414. @param soap context
  3415. */
  3416. static void
  3417. soap_wsse_session_cleanup(struct soap *soap)
  3418. { struct soap_wsse_session **session;
  3419. time_t now = time(NULL);
  3420. DBGFUN("soap_wsse_session_cleanup");
  3421. /* enter mutex to purge expired session data */
  3422. MUTEX_LOCK(soap_wsse_session_lock);
  3423. session = &soap_wsse_session;
  3424. while (*session)
  3425. { if ((*session)->expired < now)
  3426. { struct soap_wsse_session *p = *session;
  3427. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deleting session nonce=%s\n", p->nonce));
  3428. *session = p->next;
  3429. free(p);
  3430. }
  3431. else
  3432. session = &(*session)->next;
  3433. }
  3434. /* exit mutex */
  3435. MUTEX_UNLOCK(soap_wsse_session_lock);
  3436. }
  3437. /******************************************************************************\
  3438. *
  3439. * Calculate SHA1(created, nonce, password) digest
  3440. *
  3441. \******************************************************************************/
  3442. /**
  3443. @fn static void calc_digest(struct soap *soap, const char *created, const char *nonce, int noncelen, const char *password, char hash[SOAP_SMD_SHA1_SIZE])
  3444. @brief Calculates digest value SHA1(created, nonce, password)
  3445. @param soap context
  3446. @param[in] created string (XSD dateTime format)
  3447. @param[in] nonce value
  3448. @param[in] noncelen length of nonce value
  3449. @param[in] password string
  3450. @param[out] hash SHA1 digest
  3451. */
  3452. static void
  3453. calc_digest(struct soap *soap, const char *created, const char *nonce, int noncelen, const char *password, char hash[SOAP_SMD_SHA1_SIZE])
  3454. { struct soap_smd_data context;
  3455. /* use smdevp engine */
  3456. soap_smd_init(soap, &context, SOAP_SMD_DGST_SHA1, NULL, 0);
  3457. soap_smd_update(soap, &context, nonce, noncelen);
  3458. soap_smd_update(soap, &context, created, strlen(created));
  3459. soap_smd_update(soap, &context, password, strlen(password));
  3460. soap_smd_final(soap, &context, hash, NULL);
  3461. }
  3462. /******************************************************************************\
  3463. *
  3464. * Calculate randomized hex nonce
  3465. *
  3466. \******************************************************************************/
  3467. /**
  3468. @fn static void calc_nonce(struct soap *soap, char nonce[SOAP_WSSE_NONCELEN])
  3469. @brief Calculates randomized nonce (also uses time() in case a poorly seeded PRNG is used)
  3470. @param soap context
  3471. @param[out] nonce value
  3472. */
  3473. static void
  3474. calc_nonce(struct soap *soap, char nonce[SOAP_WSSE_NONCELEN])
  3475. { int i;
  3476. time_t r = time(NULL);
  3477. memcpy(nonce, &r, 4);
  3478. for (i = 4; i < SOAP_WSSE_NONCELEN; i += 4)
  3479. { r = soap_random;
  3480. memcpy(nonce + i, &r, 4);
  3481. }
  3482. }
  3483. /******************************************************************************\
  3484. *
  3485. * Plugin registry functions
  3486. *
  3487. \******************************************************************************/
  3488. /**
  3489. @fn int soap_wsse(struct soap *soap, struct soap_plugin *p, void *arg)
  3490. @brief Plugin registry function, used with soap_register_plugin.
  3491. @param soap context
  3492. @param[in,out] p plugin created in registry
  3493. @param[in] arg passed from soap_register_plugin_arg is an optional security token handler callback
  3494. @return SOAP_OK
  3495. */
  3496. int
  3497. soap_wsse(struct soap *soap, struct soap_plugin *p, void *arg)
  3498. { static int done = 0;
  3499. DBGFUN("soap_wsse");
  3500. p->id = soap_wsse_id;
  3501. p->data = (void*)SOAP_MALLOC(soap, sizeof(struct soap_wsse_data));
  3502. p->fcopy = soap_wsse_copy;
  3503. p->fdelete = soap_wsse_delete;
  3504. if (p->data)
  3505. { if (soap_wsse_init(soap, (struct soap_wsse_data*)p->data, (const void *(*)(struct soap*, int*, const char*, int*))arg))
  3506. { SOAP_FREE(soap, p->data);
  3507. return SOAP_EOM;
  3508. }
  3509. }
  3510. if (!done)
  3511. {
  3512. #if 0
  3513. #ifdef WIN32
  3514. /* now uses CreateMutex() for static lock initialization */
  3515. static volatile long spinlock = 0;
  3516. DWORD s = 0;
  3517. /* Initialize soap_wsse_session_lock with a spinlock */
  3518. while (InterlockedExchange(&spinlock, 1) == 1)
  3519. { Sleep(s);
  3520. s = !s;
  3521. }
  3522. if (!done)
  3523. MUTEX_SETUP(soap_wsse_session_lock);
  3524. done = 1;
  3525. spinlock = 0;
  3526. #else
  3527. done = 1;
  3528. #endif
  3529. #endif
  3530. #ifdef WITH_OPENSSL
  3531. /* moved to stdsoap2.c
  3532. MUTEX_LOCK(soap_wsse_session_lock);
  3533. OpenSSL_add_all_digests();
  3534. OpenSSL_add_all_algorithms();
  3535. MUTEX_UNLOCK(soap_wsse_session_lock);
  3536. */
  3537. #endif
  3538. }
  3539. return SOAP_OK;
  3540. }
  3541. /**
  3542. @fn int soap_wsse_init(struct soap *soap, struct soap_wsse_data *data, const void *(*arg)(struct soap*, int*, const char*, int*))
  3543. @brief Initializes plugin data.
  3544. @param soap context
  3545. @param[in,out] data plugin data
  3546. @param arg security token handler callback
  3547. @return SOAP_OK
  3548. */
  3549. static int
  3550. soap_wsse_init(struct soap *soap, struct soap_wsse_data *data, const void *(*arg)(struct soap*, int *alg, const char *keyname, int *keylen))
  3551. { DBGFUN("soap_wsse_init");
  3552. data->sigid = NULL;
  3553. data->encid = NULL;
  3554. data->sign_alg = SOAP_SMD_NONE;
  3555. data->sign_key = NULL;
  3556. data->sign_keylen = 0;
  3557. data->vrfy_alg = SOAP_SMD_NONE;
  3558. data->vrfy_key = NULL;
  3559. data->vrfy_keylen = 0;
  3560. data->enco_alg = SOAP_MEC_NONE;
  3561. data->enco_keyname = NULL;
  3562. data->enco_key = NULL;
  3563. data->enco_keylen = 0;
  3564. data->deco_alg = SOAP_MEC_NONE;
  3565. data->deco_key = NULL;
  3566. data->deco_keylen = 0;
  3567. data->digest = NULL;
  3568. data->fpreparesend = NULL;
  3569. data->fpreparefinalsend = NULL;
  3570. data->fpreparefinalrecv = NULL;
  3571. data->fheader = soap->fheader;
  3572. soap->fheader = soap_wsse_header;
  3573. data->mec = NULL;
  3574. data->store = NULL;
  3575. data->security_token_handler = arg;
  3576. soap->feltbegin = soap_wsse_element_begin_in;
  3577. soap->feltendin = soap_wsse_element_end_in;
  3578. return SOAP_OK;
  3579. }
  3580. /**
  3581. @fn int soap_wsse_copy(struct soap *soap, struct soap_plugin *dst, struct soap_plugin *src)
  3582. @brief Copies plugin data to localize plugin data for threads.
  3583. @param soap context
  3584. @param[out] dst target plugin
  3585. @param[in] src source plugin
  3586. @return SOAP_OK
  3587. */
  3588. static int
  3589. soap_wsse_copy(struct soap *soap, struct soap_plugin *dst, struct soap_plugin *src)
  3590. { DBGFUN("soap_wsse_copy");
  3591. *dst = *src;
  3592. dst->data = (void*)SOAP_MALLOC(soap, sizeof(struct soap_wsse_data));
  3593. soap_wsse_init(soap, (struct soap_wsse_data*)dst->data, ((struct soap_wsse_data*)src->data)->security_token_handler);
  3594. return SOAP_OK;
  3595. }
  3596. /**
  3597. @fn void soap_wsse_delete(struct soap *soap, struct soap_plugin *p)
  3598. @brief Deletes plugin data.
  3599. @param soap context
  3600. @param[in,out] p plugin
  3601. @return SOAP_OK
  3602. */
  3603. static void
  3604. soap_wsse_delete(struct soap *soap, struct soap_plugin *p)
  3605. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3606. DBGFUN("soap_wsse_delete");
  3607. if (data)
  3608. { soap_wsse_preparecleanup(soap, data);
  3609. if (data->mec)
  3610. { soap_mec_cleanup(soap, data->mec);
  3611. SOAP_FREE(soap, data->mec);
  3612. data->mec = NULL;
  3613. }
  3614. if (data->store)
  3615. { X509_STORE_free(data->store);
  3616. data->store = NULL;
  3617. }
  3618. SOAP_FREE(soap, data);
  3619. }
  3620. }
  3621. /******************************************************************************\
  3622. *
  3623. * Plugin-specific functions
  3624. *
  3625. \******************************************************************************/
  3626. /**
  3627. @fn int soap_wsse_set_wsu_id(struct soap *soap, const char *tags)
  3628. @brief Sets the elements that are to be extended with wsu:Id attributes. The
  3629. wsu:Id attribute values are set to the string value of the tag's QName by
  3630. replacing colons with hyphens to produce an xsd:ID value.
  3631. @param soap context
  3632. @param[in] tags string of space-separated qualified and unqualified element tag names
  3633. @return SOAP_OK
  3634. */
  3635. int
  3636. soap_wsse_set_wsu_id(struct soap *soap, const char *tags)
  3637. { DBGFUN1("soap_wsse_set_wsu_id", "tags=%s", tags?tags:"(null)");
  3638. soap->wsuid = soap_strdup(soap, tags);
  3639. return SOAP_OK;
  3640. }
  3641. /**
  3642. @fn int soap_wsse_sign_only(struct soap *soap, const char *tags)
  3643. @brief Filters only the specified wsu:Id names for signing. Can be used with soap_wsse_set_wsu_id() and if so should use the element tag names.
  3644. @param soap context
  3645. @param[in] tags string of space-separated qualified and unqualified tag names
  3646. @return SOAP_OK
  3647. */
  3648. int
  3649. soap_wsse_sign_only(struct soap *soap, const char *tags)
  3650. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3651. DBGFUN1("soap_wsse_sign_only", "tags=%s", tags?tags:"(null)");
  3652. if (data)
  3653. data->sigid = soap_wsse_ids(soap, tags);
  3654. return SOAP_OK;
  3655. }
  3656. /**
  3657. @fn static char* soap_wsse_ids(struct soap *soap, const char *tags)
  3658. @brief converts tag name(s) to id name(s)
  3659. @param soap context
  3660. @param[in] tags string of space-separated (un)qualified tag names
  3661. @return string of ids
  3662. */
  3663. static char*
  3664. soap_wsse_ids(struct soap *soap, const char *tags)
  3665. { char *s, *t;
  3666. s = t = soap_strdup(soap, tags);
  3667. while (s && *s)
  3668. { if (*s == ':')
  3669. *s = '-';
  3670. s++;
  3671. }
  3672. return t;
  3673. }
  3674. /**
  3675. @fn int soap_wsse_sign(struct soap *soap, int alg, const void *key, int keylen)
  3676. @brief Uses the wsse plugin to sign all wsu:Id attributed elements.
  3677. @param soap context
  3678. @param[in] alg is the signature algorithm, such as SOAP_SMD_HMAC_SHA1, SOAP_SMD_SIGN_DSA_SHA1, or SOAP_SMD_SIGN_RSA_SHA1
  3679. @param[in] key is the HMAC secret key or DSA/RSA private EVP_PKEY
  3680. @param[in] keylen is the HMAC key length
  3681. @return SOAP_OK or fault
  3682. This function does not actually sign the message, but initiates the plugin's
  3683. signature algorithm to sign the message upon message transfer.
  3684. */
  3685. int
  3686. soap_wsse_sign(struct soap *soap, int alg, const void *key, int keylen)
  3687. { struct soap_wsse_digest *digest, *next;
  3688. struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3689. DBGFUN1("soap_wsse_sign", "alg=%x", alg);
  3690. if (!data)
  3691. return soap_set_receiver_error(soap, "soap_wsse_sign", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3692. if (!alg || !key)
  3693. return soap_wsse_fault(soap, wsse__InvalidSecurity, "Invalid signature algorithm or key");
  3694. /* store alg and key in plugin data */
  3695. data->sign_alg = alg;
  3696. data->sign_key = key;
  3697. data->sign_keylen = keylen;
  3698. /* save and set the plugin's callbacks to preprocess outbound messages */
  3699. if (soap->fpreparesend != soap_wsse_preparesend)
  3700. { data->fpreparesend = soap->fpreparesend;
  3701. data->fpreparefinalsend = soap->fpreparefinalsend;
  3702. }
  3703. if (soap->fpreparefinalsend != soap_wsse_preparefinalsend)
  3704. { soap->fpreparesend = soap_wsse_preparesend;
  3705. soap->fpreparefinalsend = soap_wsse_preparefinalsend;
  3706. }
  3707. /* support HTTP compression only with HTTP chunking to allow signing XML */
  3708. if ((soap->omode & SOAP_ENC_ZLIB))
  3709. soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_CHUNK;
  3710. else if ((soap->omode & SOAP_IO) == SOAP_IO_STORE) /* no store buffering */
  3711. soap->omode = (soap->omode & ~SOAP_IO) | SOAP_IO_BUFFER;
  3712. /* cleanup the digest data */
  3713. for (digest = data->digest; digest; digest = next)
  3714. { next = digest->next;
  3715. SOAP_FREE(soap, digest);
  3716. }
  3717. data->digest = NULL;
  3718. return SOAP_OK;
  3719. }
  3720. /**
  3721. @fn int soap_wsse_sign_body(struct soap *soap, int alg, const void *key, int keylen)
  3722. @brief Uses the wsse plugin to sign all wsu:Id attributed elements, including the SOAP Body (by adding a wsu:Id="Body" attribute).
  3723. @param soap context
  3724. @param[in] alg is the signature algorithm, such as SOAP_SMD_HMAC_SHA1, SOAP_SMD_SIGN_DSA_SHA1, or SOAP_SMD_SIGN_RSA_SHA1
  3725. @param[in] key is the HMAC secret key or DSA/RSA private EVP_PKEY
  3726. @param[in] keylen is the HMAC key length
  3727. @return SOAP_OK
  3728. This function does not actually sign the message, but initiates the plugin's
  3729. signature algorithm to sign the message upon message transfer.
  3730. */
  3731. int
  3732. soap_wsse_sign_body(struct soap *soap, int alg, const void *key, int keylen)
  3733. { DBGFUN1("soap_wsse_sign_body", "alg=%x", alg);
  3734. soap_wsse_add_Security(soap);
  3735. soap->omode |= SOAP_SEC_WSUID;
  3736. return soap_wsse_sign(soap, alg, key, keylen);
  3737. }
  3738. /**
  3739. @fn int soap_wsse_verify_init(struct soap *soap)
  3740. @brief Uses the wsse plugin to initiate the verification of the signature and SignedInfo Reference digests.
  3741. @param soap context
  3742. @return SOAP_OK
  3743. This function does not actually verify the message, but initiates the plugin's
  3744. data to store the message in a DOM to verify the signature. The signature and
  3745. digests in the DOM must be verified manually.
  3746. */
  3747. int
  3748. soap_wsse_verify_init(struct soap *soap)
  3749. { DBGFUN("soap_wsse_verify_init");
  3750. /* deserialize inbound message to DOM */
  3751. soap->imode |= SOAP_XML_DOM;
  3752. return SOAP_OK;
  3753. }
  3754. /**
  3755. @fn int soap_wsse_verify_auto(struct soap *soap, int alg, const void *key, size_t keylen)
  3756. @brief Uses the wsse plugin to initiate the automatic verification of the signature and SignedInfo Reference digests.
  3757. @param soap context
  3758. @param[in] alg to verify signature if signature has no secret or public key, use SOAP_SMD_NONE to omit
  3759. @param[in] key is HMAC key or EVP_PKEY or NULL
  3760. @param[in] keylen is HMAC key length or 0
  3761. @return SOAP_OK
  3762. This function does not actually verify the message, but initiates the plugin's
  3763. algorithm to store the message in a DOM to automatically verify the signature
  3764. and digests. If the message does not contain a key to verify the signature,
  3765. the alg, key, and keylen parameters are used. It is important that the X509
  3766. certificate used to verify the signature, which requires soap->cafile and/or
  3767. soap->capath to be set.
  3768. */
  3769. int
  3770. soap_wsse_verify_auto(struct soap *soap, int alg, const void *key, size_t keylen)
  3771. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3772. DBGFUN("soap_wsse_verify_auto");
  3773. if (!data)
  3774. return soap_set_receiver_error(soap, "soap_wsse_verify_auto", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3775. data->vrfy_alg = alg;
  3776. data->vrfy_key = key;
  3777. data->vrfy_keylen = keylen;
  3778. if (soap->fpreparefinalrecv != soap_wsse_preparefinalrecv)
  3779. { data->fpreparefinalrecv = soap->fpreparefinalrecv;
  3780. soap->fpreparefinalrecv = soap_wsse_preparefinalrecv;
  3781. }
  3782. return soap_wsse_verify_init(soap);
  3783. }
  3784. /**
  3785. @fn int soap_wsse_verify_done(struct soap *soap)
  3786. @brief Terminates the automatic verification of signatures.
  3787. @param soap context
  3788. @return SOAP_OK
  3789. */
  3790. int
  3791. soap_wsse_verify_done(struct soap *soap)
  3792. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3793. DBGFUN("soap_wsse_verify_done");
  3794. if (!data)
  3795. return soap_set_receiver_error(soap, "soap_wsse_verify_done", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3796. soap->imode &= ~SOAP_XML_DOM;
  3797. soap->omode &= ~SOAP_SEC_WSUID;
  3798. if (soap->fpreparefinalrecv == soap_wsse_preparefinalrecv)
  3799. soap->fpreparefinalrecv = data->fpreparefinalrecv;
  3800. return SOAP_OK;
  3801. }
  3802. /**
  3803. @fn size_t soap_wsse_verify_element(struct soap *soap, const char *URI, const char *tag)
  3804. @brief Post-checks the presence of signed element(s). Does not verify the
  3805. signature of these elements, which is done with @ref soap_wsse_verify_auto.
  3806. @param soap context
  3807. @param URI namespace of element(s)
  3808. @param tag name of element(s)
  3809. @return number of matching elements signed.
  3810. This function does not actually verify the signature of each element, but
  3811. checks whether the elements are signed and thus their integrity is preserved.
  3812. Signed element nesting rules are obeyed, so if the matching element is a
  3813. descendent of a signed element, it is signed as well. Thus, the verification
  3814. process follows nesting rules.
  3815. Client should call this function after invocation. Services should call this
  3816. function inside a service operation. This function traverses the entire DOM, so
  3817. performance is determined by the size of a message.
  3818. To check the SOAP Body (either using SOAP 1.1 or 1.2), @ref soap_wsse_verify_element(soap, namespaces[0].ns, "Body"). To check whether the Timestamp was signed (assuming it is present and message expiration checked with @ref soap_wsse_verify_Timestamp), use @ref soap_wsse_verify_element(soap, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Timestamp").
  3819. Note: for future releases XPath queries (or forms of these) will be considered.
  3820. */
  3821. size_t
  3822. soap_wsse_verify_element(struct soap *soap, const char *URI, const char *tag)
  3823. { ds__SignedInfoType *signedInfo = soap_wsse_SignedInfo(soap);
  3824. size_t count = 0;
  3825. DBGFUN("soap_wsse_verify_element");
  3826. if (signedInfo && soap->dom)
  3827. { struct soap_dom_element *elt;
  3828. /* traverse the DOM */
  3829. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SignedInfo and DOM found\n"));
  3830. elt = soap->dom;
  3831. while (elt)
  3832. { /* find wsu:Id or ds:Id and check for Id in signedInfo */
  3833. int ok = 0;
  3834. struct soap_dom_attribute *att;
  3835. for (att = elt->atts; att; att = att->next)
  3836. { if (att->name
  3837. && att->nstr
  3838. && (!strcmp(att->nstr, wsu_URI) || !strcmp(att->nstr, ds_URI))
  3839. && (!strcmp(att->name, "Id") || !soap_tag_cmp(att->name, "*:Id")))
  3840. { /* Id attribute found, search Id value in ds:Reference/@URI */
  3841. int i;
  3842. for (i = 0; i < signedInfo->__sizeReference; i++)
  3843. { ds__ReferenceType *reference = signedInfo->Reference[i];
  3844. if (reference->URI && *reference->URI == '#' && !strcmp(reference->URI + 1, att->data))
  3845. { ok = 1;
  3846. break;
  3847. }
  3848. }
  3849. if (ok)
  3850. break;
  3851. }
  3852. }
  3853. /* the current element is signed, count this and the matching nested */
  3854. if (ok)
  3855. { count += soap_wsse_verify_nested(soap, elt, URI, tag);
  3856. /* go to next sibling or back up */
  3857. if (elt->next)
  3858. elt = elt->next;
  3859. else
  3860. { do elt = elt->prnt;
  3861. while (elt && !elt->next);
  3862. if (elt)
  3863. elt = elt->next;
  3864. }
  3865. }
  3866. else
  3867. elt = soap_dom_next_element(elt);
  3868. }
  3869. }
  3870. return count;
  3871. }
  3872. /**
  3873. @fn size_t soap_wsse_verify_nested(struct soap *soap, struct soap_dom_element *dom, const char *URI, const char *tag)
  3874. @brief Counts signed matching elements from the dom node and down
  3875. @param soap context
  3876. @param dom node to check and down
  3877. @param URI namespace of element(s)
  3878. @param tag name of element(s)
  3879. @return number of matching elements.
  3880. */
  3881. static size_t
  3882. soap_wsse_verify_nested(struct soap *soap, struct soap_dom_element *dom, const char *URI, const char *tag)
  3883. { size_t count = 0;
  3884. /* search the DOM node and descendants for matching elements */
  3885. struct soap_dom_element *elt = dom;
  3886. for (elt = dom; elt && elt != dom->next && elt != dom->prnt; elt = soap_dom_next_element(elt))
  3887. { if (elt->name && ((!elt->nstr && !URI) || (elt->nstr && URI && !strcmp(elt->nstr, URI))))
  3888. { const char *s = strchr(elt->name, ':');
  3889. if (s)
  3890. s++;
  3891. else
  3892. s = elt->name;
  3893. /* found element? */
  3894. if (!strcmp(s, tag))
  3895. count++;
  3896. }
  3897. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element '%s' (\"%s\":%s) is signed\n", elt->name, elt->nstr, elt->name));
  3898. }
  3899. return count;
  3900. }
  3901. /**
  3902. @fn int soap_wsse_verify_body(struct soap *soap)
  3903. @brief Post-checks the presence of signed SOAP Body. Does not verify the
  3904. signature of the Body, which is done with @ref soap_wsse_verify_auto.
  3905. @param soap context
  3906. @return SOAP_OK (signed) or SOAP_FAULT
  3907. This function does not actually verify the signature of the Body. It checks
  3908. whether the Body is signed and thus its integrity is preserved. Clients should
  3909. call this function after invocation. Services should call this function inside
  3910. a service operation. This function traverses the entire DOM, so performance is
  3911. determined by the size of a message.
  3912. */
  3913. int
  3914. soap_wsse_verify_body(struct soap *soap)
  3915. { const char *ns = NULL;
  3916. /* Are we using SOAP 1.1 or 1.2? Check first row of namespace table */
  3917. if (soap->local_namespaces)
  3918. { if (soap->local_namespaces->out)
  3919. ns = soap->local_namespaces->out;
  3920. else if (soap->local_namespaces->ns)
  3921. ns = soap->local_namespaces->ns;
  3922. }
  3923. /* We don't know if we're using SOAP 1.1 or 1.2, so assume it is 1.2 */
  3924. if (!ns)
  3925. ns = "http://www.w3.org/2003/05/soap-envelope";
  3926. if (soap_wsse_verify_element(soap, ns, "Body") > 0)
  3927. return SOAP_OK;
  3928. return soap_wsse_sender_fault(soap, "Message body not signed", NULL);
  3929. }
  3930. /**
  3931. @fn int soap_wsse_encrypt_body(struct soap *soap, int alg, const void *key, int keylen)
  3932. @brief Initiates the encryption of the SOAP Body. The algorithm should be
  3933. SOAP_MEC_ENC_DES_CBC or one of SOAP_MEC_ENC_AESxxx_CBC for symmetric
  3934. encryption. Use soap_wsse_add_EncryptedKey for public key encryption.
  3935. @param soap context
  3936. @param[in] alg the encryption algorithm, should be SOAP_MEC_ENC_DES_CBC or one
  3937. of SOAP_MEC_ENC_AESxxx_CBC
  3938. @param[in] key a certificate with public key for encryption, a DES CBC 160-bit key or AES key
  3939. @param[in] keylen the symmetric encryption key length, 20 bytes for a DES CBC 160-bit key
  3940. @return SOAP_OK or error code
  3941. This function initiates the encryption of the SOAP Body using an RSA public key
  3942. or a symmetric shared secret key. No WS-Security EncryptedKey header will be
  3943. set. Use soap_wsse_add_EncryptedKey instead for public key encryption.
  3944. */
  3945. int
  3946. soap_wsse_encrypt_body(struct soap *soap, int alg, const void *key, int keylen)
  3947. { struct soap_wsse_data *data;
  3948. DBGFUN1("soap_wsse_encrypt_body", "alg=%x", alg);
  3949. data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3950. if (!data)
  3951. return soap_set_receiver_error(soap, "soap_wsse_encrypt_body", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3952. data->encid = NULL;
  3953. soap->omode |= SOAP_SEC_WSUID;
  3954. soap_wsse_add_DataReferenceURI(soap, "#Body");
  3955. return soap_wsse_encrypt(soap, alg, key, keylen);
  3956. }
  3957. /**
  3958. @fn int soap_wsse_encrypt_only(struct soap *soap, int alg, const void *key, int keylen, const char *tags)
  3959. @brief Initiates the encryption of XML elements specified in the tags string.
  3960. Should be used in combination with soap_wsse_set_wsu_id to set wsu:Id for given
  3961. XML element tags. The algorithm should be SOAP_MEC_ENC_DES_CBC or one of
  3962. SOAP_MEC_ENC_AESxxx_CBC for symmetric encryption. Use
  3963. soap_wsse_add_EncryptedKey_encrypt_only for public key encryption.
  3964. @param soap context
  3965. @param[in] alg the encryption algorithm, should be SOAP_MEC_ENC_DES_CBC or one
  3966. of SOAP_MEC_ENC_AESxxx_CBC
  3967. @param[in] key a certificate with public key for encryption, a DES CBC 160-bit key or AES key
  3968. @param[in] keylen the symmetric encryption key length, 20 bytes for a DES CBC 160-bit key
  3969. @param[in] tags string of space-separated qualified and unqualified tag names
  3970. @return SOAP_OK or error code
  3971. This function initiates the encryption using an RSA public key or a symmetric
  3972. shared secret key. No WS-Security EncryptedKey header will be set. Use
  3973. soap_wsse_add_EncryptedKey instead for public key encryption.
  3974. WARNING:
  3975. Use @ref soap_wsse_add_EncryptedKey_encrypt_only only in combination with
  3976. @ref soap_wsse_set_wsu_id with the tag names of the elements to be encrypted.
  3977. OTHERWISE THE GIVEN XML ELEMENTS ARE NOT ENCRYPTED AND WILL BE SENT IN THE
  3978. CLEAR.
  3979. WARNING:
  3980. The elements identified with @ref soap_wsse_set_wsu_id to encrypt MUST occur
  3981. EXACTLY ONCE in the SOAP Body.
  3982. WARNING:
  3983. Encryption/decryption of elements with simple content (CDATA content) IS NOT
  3984. SUPPORTED. This means that elements you want to encrypt with this function must
  3985. have complex content. That is, only encrypt elements with sub elements or
  3986. encrypt the entire SOAP Body.
  3987. */
  3988. int
  3989. soap_wsse_encrypt_only(struct soap *soap, int alg, const void *key, int keylen, const char *tags)
  3990. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  3991. DBGFUN2("soap_wsse_encrypt_only", "alg=%x", alg, "tags=%s", tags?tags:"(null)");
  3992. if (!data)
  3993. return soap_set_receiver_error(soap, "soap_wsse_encrypt_only", "Plugin not registered", SOAP_PLUGIN_ERROR);
  3994. data->encid = soap_strdup(soap, tags);
  3995. if (tags)
  3996. { char *s, *t;
  3997. /* make space to insert # to each id converted from a tag name */
  3998. t = (char*)soap_malloc(soap, strlen(tags) + 2);
  3999. if (!t)
  4000. return soap->error = SOAP_EOM;
  4001. *t = '#';
  4002. strcpy(t + 1, tags);
  4003. s = soap_wsse_ids(soap, t);
  4004. if (!s)
  4005. return soap->error = SOAP_EOM;
  4006. s++;
  4007. do
  4008. { t = strchr(s, ' ');
  4009. if (t)
  4010. *t = '\0';
  4011. s--;
  4012. *s = '#';
  4013. if (soap_wsse_add_DataReferenceURI(soap, s))
  4014. return soap->error;
  4015. s = t;
  4016. while (s && *s == ' ')
  4017. s++;
  4018. } while (s);
  4019. }
  4020. return soap_wsse_encrypt(soap, alg, key, keylen);
  4021. }
  4022. /**
  4023. @fn int soap_wsse_encrypt(struct soap *soap, int alg, const void *key, int keylen)
  4024. @brief Start encryption. This function is supposed to be used internally only.
  4025. The algorithm should be SOAP_MEC_ENC_DES_CBC or one of SOAP_MEC_ENC_AESxxx_CBC
  4026. for symmetric encryption. Use soap_wsse_add_EncryptedKey for public key
  4027. encryption.
  4028. @param soap context
  4029. @param[in] alg the encryption algorithm, should be SOAP_MEC_ENC_DES_CBC or one
  4030. of SOAP_MEC_ENC_AESxxx_CBC
  4031. @param[in] key a certificate with public key for encryption, a DES CBC 160-bit key or AES key
  4032. @param[in] keylen the symmetric encryption key length, 20 bytes for a DES CBC 160-bit key
  4033. @return SOAP_OK or error code
  4034. */
  4035. int
  4036. soap_wsse_encrypt(struct soap *soap, int alg, const void *key, int keylen)
  4037. { struct soap_wsse_data *data;
  4038. DBGFUN1("soap_wsse_encrypt", "alg=%x", alg);
  4039. data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4040. if (!data)
  4041. return soap_set_receiver_error(soap, "soap_wsse_encrypt", "Plugin not registered", SOAP_PLUGIN_ERROR);
  4042. if (!alg || !key)
  4043. return soap_wsse_fault(soap, wsse__UnsupportedAlgorithm, "An unsupported signature or encryption algorithm was used");
  4044. if (alg & SOAP_MEC_ENV)
  4045. return soap_wsse_add_EncryptedKey(soap, alg, NULL, (X509*)key, NULL, NULL, NULL);
  4046. /* store alg and key in plugin data */
  4047. data->enco_alg = (alg | SOAP_MEC_ENC);
  4048. data->enco_key = key;
  4049. data->enco_keylen = keylen;
  4050. if (data->mec)
  4051. soap_mec_cleanup(soap, data->mec);
  4052. else
  4053. data->mec = (struct soap_mec_data*)SOAP_MALLOC(soap, sizeof(struct soap_mec_data));
  4054. if (soap_mec_begin(soap, data->mec, alg, NULL, (unsigned char*)key, &keylen))
  4055. return soap->error;
  4056. soap->feltbegout = soap_wsse_element_begin_out;
  4057. soap->feltendout = soap_wsse_element_end_out;
  4058. return SOAP_OK;
  4059. }
  4060. /**
  4061. @fn int soap_wsse_decrypt_auto(struct soap *soap, int alg, const void *key, int keylen)
  4062. @brief Start automatic decryption when needed using the specified key. This
  4063. function should be used just once. The algorithm should be
  4064. SOAP_MEC_ENV_DEC_DES_CBC for public key encryption/decryption and
  4065. SOAP_MEC_DEC_DES_CBC for symmetric shared secret keys.
  4066. @param soap context
  4067. @param[in] alg the decryption algorithm,
  4068. @param[in] key a persistent decryption key for the algorithm, a private RSA key or a shared symmetric secret key
  4069. @param[in] keylen use 0 for public-key encryption/decryption
  4070. or the shared secret decryption key length, 20 bytes for a DES CBC 160-bit key
  4071. @return SOAP_OK or error code
  4072. This function can be called once before multiple messages are received with
  4073. WS-Security encrypted content, where only one key is used for encryption
  4074. (public key or shared secret key). The default decryption key is set. If
  4075. multiple decryption keys should be used, do NOT use this function but set the
  4076. security_token_handler callback of the wsse plugin. See @ref wsse_9_2. Use a
  4077. NULL key to remove the default decryption key.
  4078. */
  4079. int
  4080. soap_wsse_decrypt_auto(struct soap *soap, int alg, const void *key, int keylen)
  4081. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4082. DBGFUN1("soap_wsse_decrypt_auto", "alg=%x", alg);
  4083. if (!data)
  4084. return soap_set_receiver_error(soap, "soap_wsse_decrypt_auto", "Plugin not registered", SOAP_PLUGIN_ERROR);
  4085. /* store alg and key in plugin data */
  4086. data->deco_alg = (alg & ~SOAP_MEC_ENC);
  4087. /* TODO add? data->enco_alg = (alg & ~(SOAP_MEC_ENC|SOAP_MEC_ENV)); */
  4088. data->deco_key = key;
  4089. data->deco_keylen = keylen;
  4090. return SOAP_OK;
  4091. }
  4092. /**
  4093. @fn int soap_wsse_encrypt_begin(struct soap *soap, const char *id, int alg, const char *URI, const char *keyname, const unsigned char *key)
  4094. @brief Emit XML encryption tags and start encryption of the XML element content.
  4095. @param soap context
  4096. @param[in] id string for the EncryptedData element Id attribute
  4097. @param[in] alg algorithm used, or SOAP_MEC_NONE to ignore
  4098. @param[in] URI string for the encrypted element wsu:Id attribute
  4099. @param[in] keyname optional subject key name
  4100. @param[in] key optional DES/AES key for encryption (to override the current key)
  4101. @return SOAP_OK or error code
  4102. */
  4103. int
  4104. soap_wsse_encrypt_begin(struct soap *soap, const char *id, int alg, const char *URI, const char *keyname, const unsigned char *key)
  4105. { int event;
  4106. const char *algURI = NULL;
  4107. DBGFUN("soap_wsse_encrypt_begin");
  4108. if ((soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_IO) == SOAP_IO_CHUNK)
  4109. return SOAP_OK;
  4110. /* disable digest */
  4111. event = soap->event;
  4112. soap->event = 0;
  4113. if (soap_set_attr(soap, "Id", id, 1)
  4114. || soap_set_attr(soap, "Type", xenc_contentURI, 1)
  4115. || soap_element(soap, "xenc:EncryptedData", 0, NULL)
  4116. || soap_element_start_end_out(soap, NULL))
  4117. return soap->error;
  4118. switch (alg & SOAP_MEC_MASK & ~SOAP_MEC_ENV)
  4119. { case SOAP_MEC_ENC_DES_CBC:
  4120. algURI = xenc_3desURI;
  4121. break;
  4122. case SOAP_MEC_ENC_AES128_CBC:
  4123. algURI = xenc_aes128URI;
  4124. break;
  4125. case SOAP_MEC_ENC_AES192_CBC:
  4126. algURI = xenc_aes192URI;
  4127. break;
  4128. case SOAP_MEC_ENC_AES256_CBC:
  4129. algURI = xenc_aes256URI;
  4130. break;
  4131. case SOAP_MEC_ENC_AES512_CBC:
  4132. algURI = xenc_aes512URI;
  4133. break;
  4134. }
  4135. if (algURI)
  4136. { if (soap_set_attr(soap, "Algorithm", algURI, 1)
  4137. || soap_element(soap, "xenc:EncryptionMethod", 0, NULL)
  4138. || soap_element_start_end_out(soap, "xenc:EncryptionMethod"))
  4139. return soap->error;
  4140. }
  4141. if (URI)
  4142. { if (soap_element(soap, "ds:KeyInfo", 0, NULL)
  4143. || soap_element_start_end_out(soap, NULL)
  4144. || soap_element(soap, "wsse:SecurityTokenReference", 0, NULL)
  4145. || soap_element_start_end_out(soap, NULL)
  4146. || soap_set_attr(soap, "URI", URI, 1)
  4147. || soap_element(soap, "wsse:Reference", 0, NULL)
  4148. || soap_element_start_end_out(soap, NULL)
  4149. || soap_element_end_out(soap, "wsse:Reference")
  4150. || soap_element_end_out(soap, "wsse:SecurityTokenReference")
  4151. || soap_element_end_out(soap, "ds:KeyInfo"))
  4152. return soap->error;
  4153. }
  4154. else if (keyname)
  4155. { if (soap_element(soap, "ds:KeyInfo", 0, NULL)
  4156. || soap_element_start_end_out(soap, NULL)
  4157. || soap_element(soap, "ds:KeyName", 0, NULL)
  4158. || soap_element_start_end_out(soap, NULL)
  4159. || soap_string_out(soap, keyname, 0)
  4160. || soap_element_end_out(soap, "ds:KeyName")
  4161. || soap_element_end_out(soap, "ds:KeyInfo"))
  4162. return soap->error;
  4163. }
  4164. if (soap_element(soap, "xenc:CipherData", 0, NULL)
  4165. || soap_element_start_end_out(soap, NULL)
  4166. || soap_element(soap, "xenc:CipherValue", 0, NULL)
  4167. || soap_element_start_end_out(soap, NULL))
  4168. return soap->error;
  4169. /* re-enable digest */
  4170. soap->event = event;
  4171. /* adjust level, hiding xenc elements */
  4172. soap->level -= 3;
  4173. return soap_mec_start(soap, key);
  4174. }
  4175. /**
  4176. @fn int soap_wsse_encrypt_end(struct soap *soap)
  4177. @brief Emit XML encryption end tags and stop encryption of the XML element content.
  4178. @param soap context
  4179. @return SOAP_OK or error code
  4180. */
  4181. int
  4182. soap_wsse_encrypt_end(struct soap *soap)
  4183. { int event;
  4184. DBGFUN("soap_wsse_encrypt_end");
  4185. if ((soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_IO) == SOAP_IO_CHUNK)
  4186. return SOAP_OK;
  4187. /* disable digest */
  4188. event = soap->event;
  4189. soap->event = 0;
  4190. /* adjust level, hiding xenc elements */
  4191. soap->level += 3;
  4192. if (soap_mec_stop(soap)
  4193. || soap_element_end_out(soap, "xenc:CipherValue")
  4194. || soap_element_end_out(soap, "xenc:CipherData")
  4195. || soap_element_end_out(soap, "xenc:EncryptedData"))
  4196. return soap->error;
  4197. /* re-enable digest */
  4198. soap->event = event;
  4199. return SOAP_OK;
  4200. }
  4201. /**
  4202. @fn int soap_wsse_decrypt_begin(struct soap *soap, const unsigned char *key)
  4203. @brief Check for XML encryption tags and start decryption of the XML element
  4204. content. If the KeyInfo element is present, the security_token_handler callback
  4205. will be used to obtain a decryption key based on the key name. Otherwise the
  4206. current decryption key will be used.
  4207. @param soap context
  4208. @param[in] key optional triple DES key for decryption (to override the current key)
  4209. @return SOAP_OK or error code
  4210. */
  4211. int
  4212. soap_wsse_decrypt_begin(struct soap *soap, const unsigned char *key)
  4213. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4214. struct ds__KeyInfoType info;
  4215. struct xenc__EncryptionMethodType meth;
  4216. int alg;
  4217. int keylen;
  4218. DBGFUN("soap_wsse_decrypt_begin");
  4219. if (!data)
  4220. return soap_set_receiver_error(soap, "soap_wsse_decrypt_begin", "Plugin not registered", SOAP_PLUGIN_ERROR);
  4221. if (soap_wsse_verify_EncryptedKey(soap))
  4222. return soap->error;
  4223. alg = data->deco_alg;
  4224. keylen = data->deco_keylen;
  4225. if (soap_element_begin_in(soap, "xenc:EncryptedData", 0, NULL))
  4226. return soap->error;
  4227. /* TODO: use Type attribute */
  4228. soap_default_xenc__EncryptionMethodType(soap, &meth);
  4229. if (soap_in_xenc__EncryptionMethodType(soap, "xenc:EncryptionMethod", &meth, NULL))
  4230. { if (meth.Algorithm)
  4231. { if (!strcmp(meth.Algorithm, xenc_3desURI))
  4232. alg = (alg & (~SOAP_MEC_MASK | SOAP_MEC_ENV)) | SOAP_MEC_DEC_DES_CBC;
  4233. else if (!strcmp(meth.Algorithm, xenc_aes128URI))
  4234. alg = (alg & (~SOAP_MEC_MASK | SOAP_MEC_ENV)) | SOAP_MEC_DEC_AES128_CBC;
  4235. else if (!strcmp(meth.Algorithm, xenc_aes192URI))
  4236. alg = (alg & (~SOAP_MEC_MASK | SOAP_MEC_ENV)) | SOAP_MEC_DEC_AES192_CBC;
  4237. else if (!strcmp(meth.Algorithm, xenc_aes256URI))
  4238. alg = (alg & (~SOAP_MEC_MASK | SOAP_MEC_ENV)) | SOAP_MEC_DEC_AES256_CBC;
  4239. else if (!strcmp(meth.Algorithm, xenc_aes512URI))
  4240. alg = (alg & (~SOAP_MEC_MASK | SOAP_MEC_ENV)) | SOAP_MEC_DEC_AES512_CBC;
  4241. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "EncryptionMethod alg=%x\n", alg));
  4242. }
  4243. }
  4244. if (soap_in_ds__KeyInfoType(soap, "ds:KeyInfo", &info, NULL))
  4245. { if (data->security_token_handler && info.KeyName)
  4246. { /* retrieve key from token handler callback */
  4247. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting shared secret key '%s' through security_token_handler callback\n", info.KeyName));
  4248. key = (const unsigned char*)data->security_token_handler(soap, &alg, info.KeyName, &keylen);
  4249. }
  4250. }
  4251. if (soap_element_begin_in(soap, "xenc:CipherData", 0, NULL)
  4252. || soap_element_begin_in(soap, "xenc:CipherValue", 0, NULL))
  4253. return soap->error;
  4254. /* if non-envelope decryption and default secret key is set, use it */
  4255. if (!(alg & SOAP_MEC_ENV))
  4256. { if (alg != data->deco_alg)
  4257. { if (data->security_token_handler)
  4258. { /* retrieve key from token handler callback */
  4259. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting shared secret key for alg=%x through security_token_handler callback\n", alg));
  4260. data->deco_key = (const unsigned char*)data->security_token_handler(soap, &alg, NULL, &keylen);
  4261. }
  4262. }
  4263. if (!key)
  4264. key = (const unsigned char*)data->deco_key;
  4265. if (key)
  4266. { if (data->mec)
  4267. soap_mec_cleanup(soap, data->mec);
  4268. else
  4269. data->mec = (struct soap_mec_data*)SOAP_MALLOC(soap, sizeof(struct soap_mec_data));
  4270. if (soap_mec_begin(soap, data->mec, alg, NULL, (unsigned char*)key, &keylen))
  4271. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  4272. }
  4273. }
  4274. data->deco_alg = alg;
  4275. data->deco_keylen = keylen;
  4276. if (soap_mec_start_alg(soap, alg, key))
  4277. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  4278. return SOAP_OK;
  4279. }
  4280. /**
  4281. @fn int soap_wsse_decrypt_end(struct soap *soap)
  4282. @brief Check for XML encryption ending tags and stop decryption of the XML
  4283. element content.
  4284. @param soap context
  4285. @return SOAP_OK or error code
  4286. */
  4287. int
  4288. soap_wsse_decrypt_end(struct soap *soap)
  4289. { DBGFUN("soap_wsse_decrypt_end");
  4290. if (soap_mec_stop(soap)
  4291. || soap_element_end_in(soap, "xenc:CipherValue")
  4292. || soap_element_end_in(soap, "xenc:CipherData")
  4293. || soap_element_end_in(soap, "xenc:EncryptedData"))
  4294. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  4295. return SOAP_OK;
  4296. }
  4297. /******************************************************************************\
  4298. *
  4299. * Callbacks registered by plugin
  4300. *
  4301. \******************************************************************************/
  4302. /**
  4303. @fn int soap_wsse_header(struct soap *soap)
  4304. @brief This callback is invoked as soon as the SOAP Header is received, we need
  4305. to obtain the encrypted key when the message is encrypted to start decryption.
  4306. @param soap context
  4307. @return SOAP_OK or error code
  4308. */
  4309. static int
  4310. soap_wsse_header(struct soap *soap)
  4311. { /* look for encrypted elements in Body */
  4312. /* soap->feltbegin = soap_wsse_element_begin_in; Moved, now always set */
  4313. /* soap->feltendin = soap_wsse_element_end_in; Moved, now always set */
  4314. /* get the encrypted key, if present */
  4315. return soap_wsse_verify_EncryptedKey(soap);
  4316. }
  4317. /**
  4318. @fn int soap_wsse_element_begin_in(struct soap *soap, const char *tag)
  4319. @brief This callback is invoked as soon as a starting tag of an element is
  4320. received by the XML parser.
  4321. @param soap context
  4322. @param[in] tag name of the element parsed
  4323. @return SOAP_OK or error code
  4324. */
  4325. static int
  4326. soap_wsse_element_begin_in(struct soap *soap, const char *tag)
  4327. { /* make sure we always have a header allocated */
  4328. if (soap->part == SOAP_IN_ENVELOPE)
  4329. soap_header(soap);
  4330. if (!soap_match_tag(soap, tag, "xenc:EncryptedData"))
  4331. { struct soap_dom_element *dom = soap->dom;
  4332. /* disable DOM */
  4333. soap->dom = NULL;
  4334. /* parse encryption tags */
  4335. if (soap_wsse_decrypt_begin(soap, NULL))
  4336. return soap->error;
  4337. /* adjust DOM tree to skip encryption elements */
  4338. soap->dom = dom->prnt;
  4339. soap->dom->elts = NULL;
  4340. /* adjust nesting level */
  4341. soap->level -= 3;
  4342. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Decryption started, parsing decrypted XML\n"));
  4343. soap->event = SOAP_SEC_DECRYPT;
  4344. return soap_peek_element(soap);
  4345. }
  4346. return SOAP_OK;
  4347. }
  4348. /**
  4349. @fn int soap_wsse_element_end_in(struct soap *soap, const char *tag1, const char *tag2)
  4350. @brief This callback is invoked as soon as an ending tag of an element is
  4351. received by the XML parser.
  4352. @param soap context
  4353. @param[in] tag1 name of the element parsed
  4354. @param[in] tag2 name of the element that was expected by the parser's state, or NULL
  4355. @return SOAP_OK or error code
  4356. */
  4357. static int
  4358. soap_wsse_element_end_in(struct soap *soap, const char *tag1, const char *tag2)
  4359. { if (soap->event == SOAP_SEC_DECRYPT
  4360. && soap->dom
  4361. && soap->dom->elts
  4362. && !soap_match_tag(soap, tag1, ":CipherValue"))
  4363. { struct soap_dom_element *dom = soap->dom->elts;
  4364. soap->event = 0;
  4365. /* disable DOM */
  4366. soap->dom = NULL;
  4367. /* adjust nesting level */
  4368. soap->level += 3;
  4369. /* parse ending tags */
  4370. if (soap_mec_stop(soap)
  4371. || soap_element_end_in(soap, ":CipherData")
  4372. || soap_element_end_in(soap, ":EncryptedData"))
  4373. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  4374. /* adjust DOM tree to skip encryption elements */
  4375. while (dom->next)
  4376. dom = dom->next;
  4377. soap->dom = dom;
  4378. return soap_element_end_in(soap, tag2);
  4379. }
  4380. return SOAP_OK;
  4381. }
  4382. /**
  4383. @fn int soap_wsse_element_begin_out(struct soap *soap, const char *tag)
  4384. @brief This callback is invoked as soon as a starting tag of an element is
  4385. to be sent by the XML generator.
  4386. @param soap context
  4387. @param[in] tag name of the element
  4388. @return SOAP_OK or error code
  4389. */
  4390. static int
  4391. soap_wsse_element_begin_out(struct soap *soap, const char *tag)
  4392. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4393. if (data && !data->encid && !strcmp(tag, "SOAP-ENV:Body"))
  4394. { _wsse__Security *security = soap_wsse_Security(soap);
  4395. char *URI = NULL;
  4396. if (security && security->xenc__EncryptedKey && security->xenc__EncryptedKey->Id)
  4397. { const char *Id = security->xenc__EncryptedKey->Id;
  4398. if (!(URI = (char*)soap_malloc(soap, strlen(Id) + 1)))
  4399. return soap->error = SOAP_EOM;
  4400. *URI = '#';
  4401. strcpy(URI + 1, Id);
  4402. }
  4403. /* this only encrypts the Body, so stop the callback */
  4404. if (!(soap->mode & SOAP_IO_LENGTH))
  4405. soap->feltbegout = NULL;
  4406. return soap_wsse_encrypt_begin(soap, "Body", data->enco_alg, URI, data->enco_keyname, NULL);
  4407. }
  4408. else if (data && data->encid && soap_tagsearch(data->encid, tag))
  4409. { _wsse__Security *security = soap_wsse_Security(soap);
  4410. char *URI = NULL;
  4411. if (security && security->xenc__EncryptedKey && security->xenc__EncryptedKey->Id)
  4412. { const char *Id = security->xenc__EncryptedKey->Id;
  4413. if (!(URI = (char*)soap_malloc(soap, strlen(Id) + 1)))
  4414. return soap->error = SOAP_EOM;
  4415. *URI = '#';
  4416. strcpy(URI + 1, Id);
  4417. }
  4418. return soap_wsse_encrypt_begin(soap, soap_wsse_ids(soap, tag), data->enco_alg, URI, data->enco_keyname, NULL);
  4419. }
  4420. return SOAP_OK;
  4421. }
  4422. /**
  4423. @fn int soap_wsse_element_end_out(struct soap *soap, const char *tag)
  4424. @brief This callback is invoked as soon as an ending tag of an element is
  4425. to be sent by the XML generator.
  4426. @param soap context
  4427. @param[in] tag name of the element
  4428. @return SOAP_OK or error code
  4429. */
  4430. static int
  4431. soap_wsse_element_end_out(struct soap *soap, const char *tag)
  4432. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4433. if (data && !data->encid && !strcmp(tag, "SOAP-ENV:Body"))
  4434. { if (soap_wsse_encrypt_end(soap))
  4435. return soap->error;
  4436. /* this version only encrypts Body, so stop the callback */
  4437. if (!(soap->mode & SOAP_IO_LENGTH))
  4438. soap->feltendout = NULL;
  4439. }
  4440. else if (data && data->encid && soap_tagsearch(data->encid, tag))
  4441. { if (soap_wsse_encrypt_end(soap))
  4442. return soap->error;
  4443. }
  4444. return SOAP_OK;
  4445. }
  4446. /**
  4447. @fn int soap_wsse_preparesend(struct soap *soap, const char *buf, size_t len)
  4448. @brief Takes a piece of the XML message (tokenized) to compute digest.
  4449. @param soap context
  4450. @param[in] buf string (XML "tokenized") to be sent
  4451. @param[in] len buf length
  4452. @return SOAP_OK or fault
  4453. This callback is invoked to analyze a message (usually during the HTTP content
  4454. length phase). Note: nested elements with wsu:Id attributes cannot be
  4455. individually signed.
  4456. */
  4457. static int
  4458. soap_wsse_preparesend(struct soap *soap, const char *buf, size_t len)
  4459. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4460. DBGFUN("soap_wsse_preparesend");
  4461. if (!data)
  4462. return SOAP_PLUGIN_ERROR;
  4463. /* the gSOAP engine signals the start of a wsu:Id element */
  4464. if (soap->event == SOAP_SEC_BEGIN)
  4465. { int alg;
  4466. /* start new digest or continue? */
  4467. if (data->digest && data->digest->level)
  4468. soap->event = SOAP_SEC_SIGN;
  4469. else if (!data->sigid || soap_tagsearch(data->sigid, soap->id))
  4470. { /* initialize smdevp engine */
  4471. struct soap_wsse_digest *digest;
  4472. soap->event = SOAP_SEC_SIGN;
  4473. digest = (struct soap_wsse_digest*)SOAP_MALLOC(soap, sizeof(struct soap_wsse_digest) + strlen(soap->id) + 1);
  4474. digest->next = data->digest;
  4475. digest->level = soap->level;
  4476. /* digest hash strength is same as signature strength */
  4477. alg = (SOAP_SMD_DGST | (data->sign_alg & SOAP_SMD_HASH));
  4478. soap_smd_init(soap, &digest->smd, alg, NULL, 0);
  4479. memset(digest->hash, 0, sizeof(digest->hash));
  4480. digest->id[0] = '#';
  4481. strcpy(digest->id + 1, soap->id);
  4482. data->digest = digest;
  4483. /* omit indent for indented XML (next time around, we will catch '<') */
  4484. if (*buf != '<')
  4485. goto end;
  4486. }
  4487. }
  4488. if (soap->event == SOAP_SEC_SIGN)
  4489. { /* update smdevp engine */
  4490. if (data->digest && data->digest->level)
  4491. { soap_smd_update(soap, &data->digest->smd, buf, len);
  4492. if (soap->level < data->digest->level)
  4493. { soap->event = 0;
  4494. soap_smd_final(soap, &data->digest->smd, (char*)data->digest->hash, NULL);
  4495. data->digest->level = 0;
  4496. }
  4497. }
  4498. }
  4499. end:
  4500. if (data->fpreparesend)
  4501. return data->fpreparesend(soap, buf, len);
  4502. return SOAP_OK;
  4503. }
  4504. /**
  4505. @fn int soap_wsse_preparefinalsend(struct soap *soap)
  4506. @brief Collects the digests of all the wsu:Id elements and populates the SignedInfo.
  4507. @param soap context
  4508. @return SOAP_OK or fault
  4509. This callback is invoked just before the message is sent.
  4510. */
  4511. static int
  4512. soap_wsse_preparefinalsend(struct soap *soap)
  4513. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4514. DBGFUN("soap_wsse_preparefinalsend");
  4515. if (!data)
  4516. return SOAP_PLUGIN_ERROR;
  4517. if (data->digest)
  4518. { ds__SignatureType *signature = soap_wsse_Signature(soap);
  4519. struct soap_wsse_digest *digest;
  4520. const char *transform;
  4521. int alg, signature_added = 0;
  4522. /* if message is canonicalized populate transform element accordingly */
  4523. if (soap->mode & SOAP_XML_CANONICAL)
  4524. transform = c14n_URI;
  4525. else
  4526. transform = NULL;
  4527. /* to increase the message length counter we need to emit the Signature,
  4528. SignedInfo and SignatureValue elements. However, this does not work if
  4529. we already populated the wsse:Signature with SignedInfo and should never
  4530. happen! */
  4531. if (!signature)
  4532. { signature = soap_wsse_add_Signature(soap);
  4533. signature_added = 1;
  4534. }
  4535. else if (signature->SignedInfo)
  4536. return soap_set_receiver_error(soap, "wsse error", "Cannot use soap_wsse_sign with populated SignedInfo", SOAP_SSL_ERROR);
  4537. /* digest hash strength is same as signature strength */
  4538. alg = (SOAP_SMD_DGST | (data->sign_alg & SOAP_SMD_HASH));
  4539. /* add the SignedInfo/Reference elements for each digest */
  4540. for (digest = data->digest; digest; digest = digest->next)
  4541. if (soap_wsse_add_SignedInfo_Reference(soap, digest->id, transform, NULL, alg, (char*)digest->hash))
  4542. return soap->error;
  4543. /* then compute the signature and add it */
  4544. if (soap_wsse_add_SignatureValue(soap, data->sign_alg, data->sign_key, data->sign_keylen))
  4545. return soap->error;
  4546. /* Reset the callbacks and cleanup digests */
  4547. soap_wsse_preparecleanup(soap, data);
  4548. /* if non-chunked, adjust content length */
  4549. if ((soap->mode & SOAP_IO) != SOAP_IO_CHUNK)
  4550. { /* the code below ensures we increase the HTTP length counter */
  4551. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Counting the size of additional SOAP Header elements, mode=0x%x\n", soap->mode));
  4552. if (signature_added)
  4553. { soap->level = 3; /* indent level for XML Signature */
  4554. if (soap->mode & SOAP_XML_CANONICAL && soap->mode & SOAP_XML_INDENT)
  4555. { soap->ns = 0; /* need namespaces for canonicalization */
  4556. soap->count += 4; /* correction for soap->ns = 0: add \n+indent */
  4557. }
  4558. soap_out_ds__SignatureType(soap, "ds:Signature", 0, signature, NULL);
  4559. }
  4560. else
  4561. { const char *c14nexclude = soap->c14nexclude;
  4562. soap->c14nexclude = "ds"; /* don't add xmlns:ds to count msg len */
  4563. soap->level = 4; /* indent level for XML SignedInfo */
  4564. if (soap->mode & SOAP_XML_CANONICAL && soap->mode & SOAP_XML_INDENT)
  4565. { soap->ns = 0; /* need namespaces for canonicalization */
  4566. soap->count += 5; /* correction for soap->ns = 0: add \n+indent */
  4567. }
  4568. soap_out_ds__SignedInfoType(soap, "ds:SignedInfo", 0, signature->SignedInfo, NULL);
  4569. soap_outstring(soap, "ds:SignatureValue", 0, &signature->SignatureValue, NULL, 0);
  4570. soap->c14nexclude = c14nexclude;
  4571. }
  4572. }
  4573. }
  4574. else /* Reset the callbacks and cleanup digests */
  4575. soap_wsse_preparecleanup(soap, data);
  4576. if (soap->fpreparefinalsend)
  4577. return soap->fpreparefinalsend(soap);
  4578. return SOAP_OK;
  4579. }
  4580. /**
  4581. @fn void soap_wsse_preparecleanup(struct soap *soap, struct soap_wsse_data *data)
  4582. @brief Restores engine state.
  4583. @param soap context
  4584. @param[in,out] data plugin data
  4585. */
  4586. static void
  4587. soap_wsse_preparecleanup(struct soap *soap, struct soap_wsse_data *data)
  4588. { struct soap_wsse_digest *digest, *next;
  4589. DBGFUN("soap_wsse_preparecleanup");
  4590. data->sign_alg = SOAP_SMD_NONE;
  4591. data->sign_key = NULL;
  4592. data->sign_keylen = 0;
  4593. if (soap->fpreparesend == soap_wsse_preparesend)
  4594. soap->fpreparesend = data->fpreparesend;
  4595. if (soap->fpreparefinalsend == soap_wsse_preparefinalsend)
  4596. soap->fpreparefinalsend = data->fpreparefinalsend;
  4597. data->fpreparesend = NULL;
  4598. data->fpreparefinalsend = NULL;
  4599. for (digest = data->digest; digest; digest = next)
  4600. { next = digest->next;
  4601. SOAP_FREE(soap, digest);
  4602. }
  4603. data->digest = NULL;
  4604. }
  4605. /**
  4606. @fn int soap_wsse_preparefinalrecv(struct soap *soap)
  4607. @brief Verify signature and SignedInfo digests initiated with soap_wsse_verify_auto.
  4608. @param soap context
  4609. @return SOAP_OK or fault
  4610. @see soap_wsse_verify_auto
  4611. This callback is invoked just after a message was received.
  4612. */
  4613. static int
  4614. soap_wsse_preparefinalrecv(struct soap *soap)
  4615. { struct soap_wsse_data *data = (struct soap_wsse_data*)soap_lookup_plugin(soap, soap_wsse_id);
  4616. ds__SignedInfoType *signedInfo = soap_wsse_SignedInfo(soap);
  4617. soap->omode &= ~SOAP_SEC_WSUID;
  4618. data->sigid = NULL; /* so we must set again before next send */
  4619. data->encid = NULL; /* so we must set again before next send */
  4620. DBGFUN("soap_wsse_preparefinalrecv");
  4621. if (!data)
  4622. return SOAP_PLUGIN_ERROR;
  4623. if (data->deco_alg != SOAP_MEC_NONE && data->mec)
  4624. if (soap_mec_end(soap, data->mec))
  4625. return soap_wsse_fault(soap, wsse__FailedCheck, NULL);
  4626. data->deco_alg = SOAP_MEC_NONE;
  4627. if (signedInfo)
  4628. { int err = SOAP_OK, alg, keylen = 0;
  4629. EVP_PKEY *pkey = NULL;
  4630. const void *key = NULL;
  4631. /* determine which signature algorithm was used */
  4632. if (soap_wsse_get_SignedInfo_SignatureMethod(soap, &alg))
  4633. return soap->error;
  4634. /* for HMAC-SHA1, the secret key might be stored in the KeyIdentifier */
  4635. if ((alg & SOAP_SMD_ALGO) == SOAP_SMD_HMAC)
  4636. { const char *valueType = soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifierValueType(soap);
  4637. /* if in the KeyIdentifier, retrieve it */
  4638. if (valueType && !strcmp(valueType, ds_hmac_sha1URI))
  4639. { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Using HMAC key from KeyIdentifier to verify signature\n"));
  4640. key = soap_wsse_get_KeyInfo_SecurityTokenReferenceKeyIdentifier(soap, &keylen);
  4641. }
  4642. /* next, try the plugin's security token handler */
  4643. if (!key)
  4644. { if (data->security_token_handler)
  4645. { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting HMAC key through security_token_handler callback\n"));
  4646. key = data->security_token_handler(soap, &alg, NULL, &keylen);
  4647. }
  4648. }
  4649. /* still no key: try to get it from the plugin */
  4650. if (!key && alg == (data->vrfy_alg & SOAP_SMD_MASK))
  4651. { /* get the HMAC secret key from the plugin */
  4652. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Using HMAC key from plugin to verify signature\n"));
  4653. key = data->vrfy_key;
  4654. keylen = data->vrfy_keylen;
  4655. }
  4656. }
  4657. else
  4658. { /* get the certificate from the KeyInfo reference */
  4659. X509 *cert, *cert1;
  4660. cert = cert1 = soap_wsse_get_KeyInfo_SecurityTokenReferenceX509(soap);
  4661. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got cert=%p\n", cert));
  4662. /* next, try the plugin's security token handler */
  4663. if (!cert)
  4664. { if (data->security_token_handler)
  4665. { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting certificate through security_token_handler callback\n"));
  4666. cert = (X509*)data->security_token_handler(soap, &alg, NULL, &keylen);
  4667. }
  4668. }
  4669. /* obtain the public key from the cert */
  4670. if (cert)
  4671. { pkey = X509_get_pubkey((X509*)cert);
  4672. key = (void*)pkey;
  4673. }
  4674. else if (alg == (data->vrfy_alg & SOAP_SMD_MASK))
  4675. { /* get the public key from the plugin */
  4676. DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Using public key from plugin to verify signature\n"));
  4677. key = data->vrfy_key;
  4678. soap->error = SOAP_OK;
  4679. }
  4680. if (cert1)
  4681. X509_free(cert1);
  4682. }
  4683. /* if still no key, fault */
  4684. if (!key)
  4685. err = soap_wsse_fault(soap, wsse__SecurityTokenUnavailable, NULL);
  4686. /* verify SignedInfo with signature and check digests of local elements */
  4687. else if (soap_wsse_verify_SignatureValue(soap, alg, key, keylen)
  4688. || soap_wsse_verify_SignedInfo(soap))
  4689. err = soap->error;
  4690. if (pkey)
  4691. EVP_PKEY_free(pkey);
  4692. if (err)
  4693. return err;
  4694. if (data->fpreparefinalrecv && data->fpreparefinalrecv != soap_wsse_preparefinalrecv)
  4695. return data->fpreparefinalrecv(soap);
  4696. }
  4697. else if (!soap->fault)
  4698. return soap_wsse_fault(soap, wsse__FailedCheck, "Signature required");
  4699. return SOAP_OK;
  4700. }
  4701. #ifdef __cplusplus
  4702. }
  4703. #endif