Guest User

Untitled

a guest
Sep 24th, 2020
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.15 KB | None | 0 0
  1. #!/bin/bash -e
  2.  
  3. # Copyright 2020 Pyckle
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. #     http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15.  
  16. IMG_TO_SIGN=$1
  17. SIGNED_IMG_OUT=${2:-"$IMG_TO_SIGN.signed.bin"}
  18.  
  19. SALT_SIG_1="57c5375741c30ca9ebcb36713db4ba51"
  20. SALT_SIG_2="ab0dff19af8842cdb70a86b4b68d23f7"
  21. MAGIC_COFFEE=00c0ffee
  22.  
  23. if [ -z "$IMG_TO_SIGN" ] || [ ! -f "$IMG_TO_SIGN" ] ; then
  24.     echo "Usage $0 <image to sign> <out img>"
  25.     exit
  26. fi
  27. if [ -f "$SIGNED_IMG_OUT" ] ; then
  28.     echo "Cowardly refusing to clobber $SIGNED_IMG_OUT"
  29.     exit
  30. fi
  31.  
  32. SECOND_TO_LAST_COFFEE=$(tail -c 24 "$IMG_TO_SIGN"|head -c4|xxd -p)
  33. LAST_COFFEE=$(tail -c 4 "$IMG_TO_SIGN"|xxd -p)
  34.  
  35. INPUT_SIZE="$(stat --printf="%s" "$IMG_TO_SIGN")"
  36. if [ "$LAST_COFFEE" == "$MAGIC_COFFEE" ] ; then
  37.     echo "Image is already single signed. Removing first signature."
  38.     INPUT_SIZE=$(expr $INPUT_SIZE - 20)
  39.     if [ $SECOND_TO_LAST_COFFEE == "$MAGIC_COFFEE" ] ; then
  40.         echo "Image is already double signed. Removing second signature."
  41.         INPUT_SIZE=$(expr $INPUT_SIZE - 20)
  42.     fi
  43. else
  44.     echo "Image is unsigned. Adding both signatures."
  45. fi
  46.  
  47. head -c "$INPUT_SIZE" "$IMG_TO_SIGN" > "$SIGNED_IMG_OUT"
  48.  
  49. # add some extra padding. This is done on all of the firmware that is on D-link's site.
  50. # if it is already there, it hopefully shouldn't hurt things
  51. echo -n "c0ffeesign" >> "$SIGNED_IMG_OUT"
  52.  
  53. function addSignature()
  54. {
  55.     SALT="$1"
  56.     SIGNATURE=$( (echo "$SALT" | xxd -r -p ; cat "$SIGNED_IMG_OUT") | md5sum -b | awk '{print $1}')
  57.     echo "Salted MD5 Signature is $SIGNATURE"
  58.     echo -n "$SIGNATURE$MAGIC_COFFEE" | xxd -r -p >> "$SIGNED_IMG_OUT"
  59. }
  60.  
  61. addSignature $SALT_SIG_1
  62. addSignature $SALT_SIG_2
  63.  
  64. echo "Signing complete. Signed firmware written to $SIGNED_IMG_OUT"
  65.  
Add Comment
Please, Sign In to add comment