acme.sh 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362
  1. #!/usr/bin/env sh
  2. VER=2.2.3
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  13. END_CSR="-----END CERTIFICATE REQUEST-----"
  14. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  15. END_CERT="-----END CERTIFICATE-----"
  16. if [ -z "$AGREEMENT" ] ; then
  17. AGREEMENT="$DEFAULT_AGREEMENT"
  18. fi
  19. _URGLY_PRINTF=""
  20. if [ "$(printf '\x41')" != 'A' ] ; then
  21. _URGLY_PRINTF=1
  22. fi
  23. _info() {
  24. if [ -z "$2" ] ; then
  25. echo "[$(date)] $1"
  26. else
  27. echo "[$(date)] $1"="'$2'"
  28. fi
  29. }
  30. _err() {
  31. _info "$@" >&2
  32. return 1
  33. }
  34. _debug() {
  35. if [ -z "$DEBUG" ] ; then
  36. return
  37. fi
  38. _err "$@"
  39. return 0
  40. }
  41. _debug2() {
  42. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  43. _debug "$@"
  44. fi
  45. return
  46. }
  47. _startswith(){
  48. _str="$1"
  49. _sub="$2"
  50. echo $_str | grep ^$_sub >/dev/null 2>&1
  51. }
  52. _contains(){
  53. _str="$1"
  54. _sub="$2"
  55. echo $_str | grep $_sub >/dev/null 2>&1
  56. }
  57. _exists(){
  58. cmd="$1"
  59. if [ -z "$cmd" ] ; then
  60. _err "Usage: _exists cmd"
  61. return 1
  62. fi
  63. if type command >/dev/null 2>&1 ; then
  64. command -v $cmd >/dev/null 2>&1
  65. else
  66. type $cmd >/dev/null 2>&1
  67. fi
  68. ret="$?"
  69. _debug2 "$cmd exists=$ret"
  70. return $ret
  71. }
  72. #a + b
  73. _math(){
  74. expr "$@"
  75. }
  76. _h_char_2_dec() {
  77. _ch=$1
  78. case "${_ch}" in
  79. a|A)
  80. echo -n 10
  81. ;;
  82. b|B)
  83. echo -n 11
  84. ;;
  85. c|C)
  86. echo -n 12
  87. ;;
  88. d|D)
  89. echo -n 13
  90. ;;
  91. e|E)
  92. echo -n 14
  93. ;;
  94. f|F)
  95. echo -n 15
  96. ;;
  97. *)
  98. echo -n $_ch
  99. ;;
  100. esac
  101. }
  102. _h2b() {
  103. hex=$(cat)
  104. i=1
  105. j=2
  106. if _exists let ; then
  107. uselet="1"
  108. fi
  109. _debug uselet "$uselet"
  110. _debug _URGLY_PRINTF "$_URGLY_PRINTF"
  111. while [ '1' ] ; do
  112. if [ -z "$_URGLY_PRINTF" ] ; then
  113. h=$(printf $hex | cut -c $i-$j)
  114. if [ -z "$h" ] ; then
  115. break;
  116. fi
  117. printf "\x$h"
  118. else
  119. ic=$(printf $hex | cut -c $i)
  120. jc=$(printf $hex | cut -c $j)
  121. if [ -z "$ic$jc" ] ; then
  122. break;
  123. fi
  124. ic="$(_h_char_2_dec $ic)"
  125. jc="$(_h_char_2_dec $jc)"
  126. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  127. fi
  128. if [ "$uselet" ] ; then
  129. let "i+=2" >/dev/null
  130. let "j+=2" >/dev/null
  131. else
  132. i="$(_math $i + 2)"
  133. j="$(_math $j + 2)"
  134. fi
  135. done
  136. }
  137. #options file
  138. _sed_i() {
  139. options="$1"
  140. filename="$2"
  141. if [ -z "$filename" ] ; then
  142. _err "Usage:_sed_i options filename"
  143. return 1
  144. fi
  145. _debug2 options "$options"
  146. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  147. _debug "Using sed -i"
  148. sed -i "$options" "$filename"
  149. else
  150. _debug "No -i support in sed"
  151. text="$(cat $filename)"
  152. echo "$text" | sed "$options" > "$filename"
  153. fi
  154. }
  155. #Usage: file startline endline
  156. _getfile() {
  157. filename="$1"
  158. startline="$2"
  159. endline="$3"
  160. if [ -z "$endline" ] ; then
  161. _err "Usage: file startline endline"
  162. return 1
  163. fi
  164. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  165. if [ -z "$i" ] ; then
  166. _err "Can not find start line: $startline"
  167. return 1
  168. fi
  169. i="$(_math $i + 1)"
  170. _debug i $i
  171. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  172. if [ -z "$j" ] ; then
  173. _err "Can not find end line: $endline"
  174. return 1
  175. fi
  176. j="$(_math $j - 1)"
  177. _debug j $j
  178. sed -n $i,${j}p "$filename"
  179. }
  180. #Usage: multiline
  181. _base64() {
  182. if [ "$1" ] ; then
  183. openssl base64 -e
  184. else
  185. openssl base64 -e | tr -d '\r\n'
  186. fi
  187. }
  188. #Usage: multiline
  189. _dbase64() {
  190. if [ "$1" ] ; then
  191. openssl base64 -d -A
  192. else
  193. openssl base64 -d
  194. fi
  195. }
  196. #Usage: hashalg
  197. #Output Base64-encoded digest
  198. _digest() {
  199. alg="$1"
  200. if [ -z "$alg" ] ; then
  201. _err "Usage: _digest hashalg"
  202. return 1
  203. fi
  204. if [ "$alg" = "sha256" ] ; then
  205. openssl dgst -sha256 -binary | _base64
  206. else
  207. _err "$alg is not supported yet"
  208. return 1
  209. fi
  210. }
  211. #Usage: keyfile hashalg
  212. #Output: Base64-encoded signature value
  213. _sign() {
  214. keyfile="$1"
  215. alg="$2"
  216. if [ -z "$alg" ] ; then
  217. _err "Usage: _sign keyfile hashalg"
  218. return 1
  219. fi
  220. if [ "$alg" = "sha256" ] ; then
  221. openssl dgst -sha256 -sign "$keyfile" | _base64
  222. else
  223. _err "$alg is not supported yet"
  224. return 1
  225. fi
  226. }
  227. _ss() {
  228. _port="$1"
  229. if _exists "ss" ; then
  230. _debug "Using: ss"
  231. ss -ntpl | grep :$_port" "
  232. return 0
  233. fi
  234. if _exists "netstat" ; then
  235. _debug "Using: netstat"
  236. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  237. #for windows version netstat tool
  238. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  239. else
  240. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  241. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  242. else
  243. netstat -ntpl | grep :$_port" "
  244. fi
  245. fi
  246. return 0
  247. fi
  248. return 1
  249. }
  250. toPkcs() {
  251. domain="$1"
  252. pfxPassword="$2"
  253. if [ -z "$domain" ] ; then
  254. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  255. return 1
  256. fi
  257. _initpath "$domain"
  258. if [ "$pfxPassword" ] ; then
  259. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  260. else
  261. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  262. fi
  263. if [ "$?" = "0" ] ; then
  264. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  265. fi
  266. }
  267. #domain [2048]
  268. createAccountKey() {
  269. _info "Creating account key"
  270. if [ -z "$1" ] ; then
  271. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  272. return
  273. fi
  274. account=$1
  275. length=$2
  276. _debug account "$account"
  277. _debug length "$length"
  278. if _startswith "$length" "ec-" ; then
  279. length=2048
  280. fi
  281. if [ -z "$2" ] || [ "$2" = "no" ] ; then
  282. _info "Use default length 2048"
  283. length=2048
  284. fi
  285. _initpath
  286. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  287. _info "Account key exists, skip"
  288. return
  289. else
  290. #generate account key
  291. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  292. fi
  293. }
  294. #domain length
  295. createDomainKey() {
  296. _info "Creating domain key"
  297. if [ -z "$1" ] ; then
  298. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  299. return
  300. fi
  301. domain=$1
  302. length=$2
  303. isec=""
  304. if _startswith "$length" "ec-" ; then
  305. isec="1"
  306. length=$(printf $length | cut -d '-' -f 2-100)
  307. eccname="$length"
  308. fi
  309. if [ -z "$length" ] ; then
  310. if [ "$isec" ] ; then
  311. length=256
  312. else
  313. length=2048
  314. fi
  315. fi
  316. _info "Use length $length"
  317. if [ "$isec" ] ; then
  318. if [ "$length" = "256" ] ; then
  319. eccname="prime256v1"
  320. fi
  321. if [ "$length" = "384" ] ; then
  322. eccname="secp384r1"
  323. fi
  324. if [ "$length" = "521" ] ; then
  325. eccname="secp521r1"
  326. fi
  327. _info "Using ec name: $eccname"
  328. fi
  329. _initpath $domain
  330. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  331. #generate account key
  332. if [ "$isec" ] ; then
  333. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  334. else
  335. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  336. fi
  337. else
  338. if [ "$IS_RENEW" ] ; then
  339. _info "Domain key exists, skip"
  340. return 0
  341. else
  342. _err "Domain key exists, do you want to overwrite the key?"
  343. _err "Add '--force', and try again."
  344. return 1
  345. fi
  346. fi
  347. }
  348. # domain domainlist
  349. createCSR() {
  350. _info "Creating csr"
  351. if [ -z "$1" ] ; then
  352. echo Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]
  353. return
  354. fi
  355. domain=$1
  356. _initpath $domain
  357. domainlist=$2
  358. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  359. _info "CSR exists, skip"
  360. return
  361. fi
  362. if [ -z "$domainlist" ] || [ "$domainlist" = "no" ]; then
  363. #single domain
  364. _info "Single domain" $domain
  365. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  366. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  367. else
  368. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  369. #multi
  370. _info "Multi domain" "$alt"
  371. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  372. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  373. fi
  374. }
  375. _urlencode() {
  376. __n=$(cat)
  377. echo $__n | tr '/+' '_-' | tr -d '= '
  378. }
  379. _time2str() {
  380. #BSD
  381. if date -u -d@$1 2>/dev/null ; then
  382. return
  383. fi
  384. #Linux
  385. if date -u -r $1 2>/dev/null ; then
  386. return
  387. fi
  388. }
  389. _stat() {
  390. #Linux
  391. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  392. return
  393. fi
  394. #BSD
  395. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  396. return
  397. fi
  398. }
  399. #keyfile
  400. _calcjwk() {
  401. keyfile="$1"
  402. if [ -z "$keyfile" ] ; then
  403. _err "Usage: _calcjwk keyfile"
  404. return 1
  405. fi
  406. EC_SIGN=""
  407. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  408. _debug "RSA key"
  409. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  410. if [ "${#pub_exp}" = "5" ] ; then
  411. pub_exp=0$pub_exp
  412. fi
  413. _debug2 pub_exp "$pub_exp"
  414. e=$(echo $pub_exp | _h2b | _base64)
  415. _debug2 e "$e"
  416. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  417. _debug2 modulus "$modulus"
  418. n=$(echo -n $modulus| _h2b | _base64 | _urlencode )
  419. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  420. _debug2 jwk "$jwk"
  421. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  422. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  423. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  424. _debug "EC key"
  425. EC_SIGN="1"
  426. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  427. _debug2 crv $crv
  428. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  429. pubi=$(_math $pubi + 1)
  430. _debug2 pubi $pubi
  431. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  432. pubj=$(_math $pubj + 1)
  433. _debug2 pubj $pubj
  434. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  435. _debug2 pubtext "$pubtext"
  436. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  437. xlen=$(_math $xlen / 4)
  438. _debug2 xlen $xlen
  439. xend=$(_math $xend + 1)
  440. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  441. _debug2 x $x
  442. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  443. _debug2 x64 $x64
  444. xend=$(_math $xend + 1)
  445. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  446. _debug2 y $y
  447. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  448. _debug2 y64 $y64
  449. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  450. _debug2 jwk "$jwk"
  451. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  452. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  453. else
  454. _err "Only RSA or EC key is supported."
  455. return 1
  456. fi
  457. _debug2 HEADER "$HEADER"
  458. }
  459. # body url [needbase64]
  460. _post() {
  461. body="$1"
  462. url="$2"
  463. needbase64="$3"
  464. if _exists "curl" ; then
  465. CURL="$CURL --dump-header $HTTP_HEADER "
  466. if [ "$needbase64" ] ; then
  467. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  468. else
  469. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  470. fi
  471. else
  472. if [ "$needbase64" ] ; then
  473. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  474. else
  475. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  476. fi
  477. _sed_i "s/^ *//g" "$HTTP_HEADER"
  478. fi
  479. echo -n "$response"
  480. }
  481. # url getheader
  482. _get() {
  483. url="$1"
  484. onlyheader="$2"
  485. _debug url $url
  486. if _exists "curl" ; then
  487. if [ "$onlyheader" ] ; then
  488. $CURL -I -A "User-Agent: $USER_AGENT" $url
  489. else
  490. $CURL -A "User-Agent: $USER_AGENT" $url
  491. fi
  492. else
  493. _debug "WGET" "$WGET"
  494. if [ "$onlyheader" ] ; then
  495. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  496. else
  497. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  498. fi
  499. fi
  500. ret=$?
  501. return $ret
  502. }
  503. # url payload needbase64 keyfile
  504. _send_signed_request() {
  505. url=$1
  506. payload=$2
  507. needbase64=$3
  508. keyfile=$4
  509. if [ -z "$keyfile" ] ; then
  510. keyfile="$ACCOUNT_KEY_PATH"
  511. fi
  512. _debug url $url
  513. _debug payload "$payload"
  514. if ! _calcjwk "$keyfile" ; then
  515. return 1
  516. fi
  517. payload64=$(echo -n $payload | _base64 | _urlencode)
  518. _debug2 payload64 $payload64
  519. nonceurl="$API/directory"
  520. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  521. _debug nonce "$nonce"
  522. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  523. _debug2 protected "$protected"
  524. protected64="$(printf "$protected" | _base64 | _urlencode)"
  525. _debug2 protected64 "$protected64"
  526. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  527. _debug2 sig "$sig"
  528. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  529. _debug2 body "$body"
  530. response="$(_post "$body" $url "$needbase64" )"
  531. responseHeaders="$(cat $HTTP_HEADER)"
  532. _debug2 responseHeaders "$responseHeaders"
  533. _debug2 response "$response"
  534. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  535. _debug code $code
  536. }
  537. #setopt "file" "opt" "=" "value" [";"]
  538. _setopt() {
  539. __conf="$1"
  540. __opt="$2"
  541. __sep="$3"
  542. __val="$4"
  543. __end="$5"
  544. if [ -z "$__opt" ] ; then
  545. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  546. return
  547. fi
  548. if [ ! -f "$__conf" ] ; then
  549. touch "$__conf"
  550. fi
  551. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  552. _debug2 OK
  553. if _contains "$__val" "&" ; then
  554. __val="$(echo $__val | sed 's/&/\\&/g')"
  555. fi
  556. text="$(cat $__conf)"
  557. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  558. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  559. if _contains "$__val" "&" ; then
  560. __val="$(echo $__val | sed 's/&/\\&/g')"
  561. fi
  562. text="$(cat $__conf)"
  563. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  564. else
  565. _debug2 APP
  566. echo "$__opt$__sep$__val$__end" >> "$__conf"
  567. fi
  568. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  569. }
  570. #_savedomainconf key value
  571. #save to domain.conf
  572. _savedomainconf() {
  573. key="$1"
  574. value="$2"
  575. if [ "$DOMAIN_CONF" ] ; then
  576. _setopt "$DOMAIN_CONF" "$key" "=" "\"$value\""
  577. else
  578. _err "DOMAIN_CONF is empty, can not save $key=$value"
  579. fi
  580. }
  581. #_cleardomainconf key
  582. _cleardomainconf() {
  583. key="$1"
  584. if [ "$DOMAIN_CONF" ] ; then
  585. _sed_i "s/^$key.*$//" "$DOMAIN_CONF"
  586. else
  587. _err "DOMAIN_CONF is empty, can not save $key=$value"
  588. fi
  589. }
  590. #_saveaccountconf key value
  591. _saveaccountconf() {
  592. key="$1"
  593. value="$2"
  594. if [ "$ACCOUNT_CONF_PATH" ] ; then
  595. _setopt "$ACCOUNT_CONF_PATH" "$key" "=" "\"$value\""
  596. else
  597. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  598. fi
  599. }
  600. _startserver() {
  601. content="$1"
  602. _debug "startserver: $$"
  603. nchelp="$(nc -h 2>&1)"
  604. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  605. _NC="nc -q 1 -l"
  606. else
  607. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  608. _NC="nc -c -l"
  609. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  610. _NC="nc -N -l"
  611. else
  612. _NC="nc -l"
  613. fi
  614. fi
  615. _debug "_NC" "$_NC"
  616. # while true ; do
  617. if [ "$DEBUG" ] ; then
  618. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ; then
  619. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ;
  620. fi
  621. else
  622. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  623. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  624. fi
  625. fi
  626. if [ "$?" != "0" ] ; then
  627. _err "nc listen error."
  628. exit 1
  629. fi
  630. # done
  631. }
  632. _stopserver(){
  633. pid="$1"
  634. _debug "pid" "$pid"
  635. if [ -z "$pid" ] ; then
  636. return
  637. fi
  638. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  639. }
  640. _initpath() {
  641. if [ -z "$LE_WORKING_DIR" ] ; then
  642. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  643. fi
  644. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  645. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  646. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  647. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  648. fi
  649. fi
  650. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  651. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  652. fi
  653. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  654. . "$ACCOUNT_CONF_PATH"
  655. fi
  656. if [ "$IN_CRON" ] ; then
  657. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  658. _USER_PATH_EXPORTED=1
  659. export PATH="$USER_PATH:$PATH"
  660. fi
  661. fi
  662. if [ -z "$API" ] ; then
  663. if [ -z "$STAGE" ] ; then
  664. API="$DEFAULT_CA"
  665. else
  666. API="$STAGE_CA"
  667. _info "Using stage api:$API"
  668. fi
  669. fi
  670. if [ -z "$ACME_DIR" ] ; then
  671. ACME_DIR="/home/.acme"
  672. fi
  673. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  674. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  675. fi
  676. if [ -z "$USER_AGENT" ] ; then
  677. USER_AGENT="$DEFAULT_USER_AGENT"
  678. fi
  679. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  680. WGET="wget -q"
  681. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  682. WGET="$WGET -d "
  683. fi
  684. dp="$LE_WORKING_DIR/curl.dump"
  685. CURL="curl -L --silent"
  686. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  687. CURL="$CURL -L --trace-ascii $dp "
  688. fi
  689. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  690. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  691. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  692. fi
  693. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  694. if [ -z "$CERT_HOME" ] ; then
  695. CERT_HOME="$_DEFAULT_CERT_HOME"
  696. fi
  697. domain="$1"
  698. if [ -z "$domain" ] ; then
  699. return 0
  700. fi
  701. domainhome="$CERT_HOME/$domain"
  702. mkdir -p "$domainhome"
  703. if [ -z "$DOMAIN_PATH" ] ; then
  704. DOMAIN_PATH="$domainhome"
  705. fi
  706. if [ -z "$DOMAIN_CONF" ] ; then
  707. DOMAIN_CONF="$domainhome/$domain.conf"
  708. fi
  709. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  710. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  711. fi
  712. if [ -z "$CSR_PATH" ] ; then
  713. CSR_PATH="$domainhome/$domain.csr"
  714. fi
  715. if [ -z "$CERT_KEY_PATH" ] ; then
  716. CERT_KEY_PATH="$domainhome/$domain.key"
  717. fi
  718. if [ -z "$CERT_PATH" ] ; then
  719. CERT_PATH="$domainhome/$domain.cer"
  720. fi
  721. if [ -z "$CA_CERT_PATH" ] ; then
  722. CA_CERT_PATH="$domainhome/ca.cer"
  723. fi
  724. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  725. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  726. fi
  727. if [ -z "$CERT_PFX_PATH" ] ; then
  728. CERT_PFX_PATH="$domainhome/$domain.pfx"
  729. fi
  730. }
  731. _apachePath() {
  732. if ! _exists apachectl ; then
  733. _err "'apachecrl not found. It seems that apache is not installed, or you are not root user.'"
  734. _err "Please use webroot mode to try again."
  735. return 1
  736. fi
  737. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  738. if _startswith "$httpdconfname" '/' ; then
  739. httpdconf="$httpdconfname"
  740. httpdconfname="$(basename $httpdconfname)"
  741. else
  742. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  743. httpdconf="$httpdroot/$httpdconfname"
  744. fi
  745. if [ ! -f $httpdconf ] ; then
  746. _err "Apache Config file not found" $httpdconf
  747. return 1
  748. fi
  749. return 0
  750. }
  751. _restoreApache() {
  752. if [ -z "$usingApache" ] ; then
  753. return 0
  754. fi
  755. _initpath
  756. if ! _apachePath ; then
  757. return 1
  758. fi
  759. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  760. _debug "No config file to restore."
  761. return 0
  762. fi
  763. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  764. _debug "Restored: $httpdconf."
  765. if ! apachectl -t ; then
  766. _err "Sorry, restore apache config error, please contact me."
  767. return 1;
  768. fi
  769. _debug "Restored successfully."
  770. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  771. return 0
  772. }
  773. _setApache() {
  774. _initpath
  775. if ! _apachePath ; then
  776. return 1
  777. fi
  778. #backup the conf
  779. _debug "Backup apache config file" $httpdconf
  780. cp $httpdconf $APACHE_CONF_BACKUP_DIR/
  781. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  782. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  783. _info "The backup file will be deleted on sucess, just forget it."
  784. #add alias
  785. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  786. _debug "apacheVer" "$apacheVer"
  787. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  788. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  789. if [ "$apacheVer" ] && [ "$apacheMajer" -ge "2" ] && [ "$apacheMinor" -ge "4" ] ; then
  790. echo "
  791. Alias /.well-known/acme-challenge $ACME_DIR
  792. <Directory $ACME_DIR >
  793. Require all granted
  794. </Directory>
  795. " >> $httpdconf
  796. else
  797. echo "
  798. Alias /.well-known/acme-challenge $ACME_DIR
  799. <Directory $ACME_DIR >
  800. Order allow,deny
  801. Allow from all
  802. </Directory>
  803. " >> $httpdconf
  804. fi
  805. if ! apachectl -t ; then
  806. _err "Sorry, apache config error, please contact me."
  807. _restoreApache
  808. return 1;
  809. fi
  810. if [ ! -d "$ACME_DIR" ] ; then
  811. mkdir -p "$ACME_DIR"
  812. chmod 755 "$ACME_DIR"
  813. fi
  814. if ! apachectl graceful ; then
  815. _err "Sorry, apachectl graceful error, please contact me."
  816. _restoreApache
  817. return 1;
  818. fi
  819. usingApache="1"
  820. return 0
  821. }
  822. _clearup() {
  823. _stopserver $serverproc
  824. serverproc=""
  825. _restoreApache
  826. }
  827. # webroot removelevel tokenfile
  828. _clearupwebbroot() {
  829. __webroot="$1"
  830. if [ -z "$__webroot" ] ; then
  831. _debug "no webroot specified, skip"
  832. return 0
  833. fi
  834. if [ "$2" = '1' ] ; then
  835. _debug "remove $__webroot/.well-known"
  836. rm -rf "$__webroot/.well-known"
  837. elif [ "$2" = '2' ] ; then
  838. _debug "remove $__webroot/.well-known/acme-challenge"
  839. rm -rf "$__webroot/.well-known/acme-challenge"
  840. elif [ "$2" = '3' ] ; then
  841. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  842. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  843. else
  844. _info "Skip for removelevel:$2"
  845. fi
  846. return 0
  847. }
  848. issue() {
  849. if [ -z "$2" ] ; then
  850. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  851. return 1
  852. fi
  853. Le_Webroot="$1"
  854. Le_Domain="$2"
  855. Le_Alt="$3"
  856. Le_Keylength="$4"
  857. Le_RealCertPath="$5"
  858. Le_RealKeyPath="$6"
  859. Le_RealCACertPath="$7"
  860. Le_ReloadCmd="$8"
  861. Le_RealFullChainPath="$9"
  862. #remove these later.
  863. if [ "$Le_Webroot" = "dns-cf" ] ; then
  864. Le_Webroot="dns_cf"
  865. fi
  866. if [ "$Le_Webroot" = "dns-dp" ] ; then
  867. Le_Webroot="dns_dp"
  868. fi
  869. if [ "$Le_Webroot" = "dns-cx" ] ; then
  870. Le_Webroot="dns_cx"
  871. fi
  872. _initpath $Le_Domain
  873. if [ -f "$DOMAIN_CONF" ] ; then
  874. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  875. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  876. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  877. return 2
  878. fi
  879. fi
  880. _savedomainconf "Le_Domain" "$Le_Domain"
  881. _savedomainconf "Le_Alt" "$Le_Alt"
  882. _savedomainconf "Le_Webroot" "$Le_Webroot"
  883. _savedomainconf "Le_Keylength" "$Le_Keylength"
  884. if [ "$Le_Alt" = "no" ] ; then
  885. Le_Alt=""
  886. fi
  887. if [ "$Le_Keylength" = "no" ] ; then
  888. Le_Keylength=""
  889. fi
  890. if _contains "$Le_Webroot" "no" ; then
  891. _info "Standalone mode."
  892. if ! _exists "nc" ; then
  893. _err "Please install netcat(nc) tools first."
  894. return 1
  895. fi
  896. if [ -z "$Le_HTTPPort" ] ; then
  897. Le_HTTPPort=80
  898. fi
  899. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  900. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  901. if [ "$netprc" ] ; then
  902. _err "$netprc"
  903. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  904. _err "Please stop it first"
  905. return 1
  906. fi
  907. fi
  908. if _contains "$Le_Webroot" "apache" ; then
  909. if ! _setApache ; then
  910. _err "set up apache error. Report error to me."
  911. return 1
  912. fi
  913. else
  914. usingApache=""
  915. fi
  916. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  917. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  918. _err "Create account key error."
  919. if [ "$usingApache" ] ; then
  920. _restoreApache
  921. fi
  922. return 1
  923. fi
  924. fi
  925. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  926. if [ "$usingApache" ] ; then
  927. _restoreApache
  928. fi
  929. return 1
  930. fi
  931. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  932. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  933. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  934. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  935. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  936. _info "Registering account"
  937. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  938. if [ "$ACCOUNT_EMAIL" ] ; then
  939. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  940. fi
  941. _send_signed_request "$API/acme/new-reg" "$regjson"
  942. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  943. _info "Registered"
  944. echo $response > $LE_WORKING_DIR/account.json
  945. elif [ "$code" = '409' ] ; then
  946. _info "Already registered"
  947. else
  948. _err "Register account Error: $response"
  949. _clearup
  950. return 1
  951. fi
  952. ACCOUNT_KEY_HASH="$accountkeyhash"
  953. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  954. else
  955. _info "Skip register account key"
  956. fi
  957. if [ ! -f "$CERT_KEY_PATH" ] ; then
  958. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  959. _err "Create domain key error."
  960. _clearup
  961. return 1
  962. fi
  963. fi
  964. if ! createCSR $Le_Domain $Le_Alt ; then
  965. _err "Create CSR error."
  966. _clearup
  967. return 1
  968. fi
  969. vlist="$Le_Vlist"
  970. # verify each domain
  971. _info "Verify each domain"
  972. sep='#'
  973. if [ -z "$vlist" ] ; then
  974. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  975. _index=1
  976. _currentRoot=""
  977. for d in $alldomains
  978. do
  979. _info "Getting webroot for domain" $d
  980. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  981. _debug _w "$_w"
  982. if [ "$_w" ] ; then
  983. _currentRoot="$_w"
  984. fi
  985. _debug "_currentRoot" "$_currentRoot"
  986. _index=$(_math $_index + 1)
  987. vtype="$VTYPE_HTTP"
  988. if _startswith "$_currentRoot" "dns" ; then
  989. vtype="$VTYPE_DNS"
  990. fi
  991. _info "Getting token for domain" $d
  992. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  993. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  994. _err "new-authz error: $response"
  995. _clearup
  996. return 1
  997. fi
  998. entry="$(printf "$response" | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  999. _debug entry "$entry"
  1000. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1001. _debug token $token
  1002. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1003. _debug uri $uri
  1004. keyauthorization="$token.$thumbprint"
  1005. _debug keyauthorization "$keyauthorization"
  1006. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1007. _debug dvlist "$dvlist"
  1008. vlist="$vlist$dvlist,"
  1009. done
  1010. #add entry
  1011. dnsadded=""
  1012. ventries=$(echo "$vlist" | tr ',' ' ' )
  1013. for ventry in $ventries
  1014. do
  1015. d=$(echo $ventry | cut -d $sep -f 1)
  1016. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1017. vtype=$(echo $ventry | cut -d $sep -f 4)
  1018. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1019. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1020. dnsadded='0'
  1021. txtdomain="_acme-challenge.$d"
  1022. _debug txtdomain "$txtdomain"
  1023. txt="$(echo -n $keyauthorization | _digest "sha256" | _urlencode)"
  1024. _debug txt "$txt"
  1025. #dns
  1026. #1. check use api
  1027. d_api=""
  1028. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1029. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1030. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1031. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1032. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1033. d_api="$LE_WORKING_DIR/$_currentRoot"
  1034. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1035. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1036. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1037. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1038. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1039. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1040. fi
  1041. _debug d_api "$d_api"
  1042. if [ "$d_api" ] ; then
  1043. _info "Found domain api file: $d_api"
  1044. else
  1045. _err "Add the following TXT record:"
  1046. _err "Domain: $txtdomain"
  1047. _err "TXT value: $txt"
  1048. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1049. _err "so the resulting subdomain will be: $txtdomain"
  1050. continue
  1051. fi
  1052. (
  1053. if ! . $d_api ; then
  1054. _err "Load file $d_api error. Please check your api file and try again."
  1055. return 1
  1056. fi
  1057. addcommand="${_currentRoot}_add"
  1058. if ! _exists $addcommand ; then
  1059. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1060. return 1
  1061. fi
  1062. if ! $addcommand $txtdomain $txt ; then
  1063. _err "Error add txt for domain:$txtdomain"
  1064. return 1
  1065. fi
  1066. )
  1067. if [ "$?" != "0" ] ; then
  1068. _clearup
  1069. return 1
  1070. fi
  1071. dnsadded='1'
  1072. fi
  1073. done
  1074. if [ "$dnsadded" = '0' ] ; then
  1075. _savedomainconf "Le_Vlist" "$vlist"
  1076. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1077. _err "Please add the TXT records to the domains, and retry again."
  1078. _clearup
  1079. return 1
  1080. fi
  1081. fi
  1082. if [ "$dnsadded" = '1' ] ; then
  1083. _info "Sleep 60 seconds for the txt records to take effect"
  1084. sleep 60
  1085. fi
  1086. _debug "ok, let's start to verify"
  1087. ventries=$(echo "$vlist" | tr ',' ' ' )
  1088. for ventry in $ventries
  1089. do
  1090. d=$(echo $ventry | cut -d $sep -f 1)
  1091. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1092. uri=$(echo $ventry | cut -d $sep -f 3)
  1093. vtype=$(echo $ventry | cut -d $sep -f 4)
  1094. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1095. _info "Verifying:$d"
  1096. _debug "d" "$d"
  1097. _debug "keyauthorization" "$keyauthorization"
  1098. _debug "uri" "$uri"
  1099. removelevel=""
  1100. token=""
  1101. _debug "_currentRoot" "$_currentRoot"
  1102. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1103. if [ "$_currentRoot" = "no" ] ; then
  1104. _info "Standalone mode server"
  1105. _startserver "$keyauthorization" &
  1106. if [ "$?" != "0" ] ; then
  1107. _clearup
  1108. return 1
  1109. fi
  1110. serverproc="$!"
  1111. sleep 2
  1112. _debug serverproc $serverproc
  1113. else
  1114. if [ "$_currentRoot" = "apache" ] ; then
  1115. wellknown_path="$ACME_DIR"
  1116. else
  1117. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1118. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1119. removelevel='1'
  1120. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1121. removelevel='2'
  1122. else
  1123. removelevel='3'
  1124. fi
  1125. fi
  1126. _debug wellknown_path "$wellknown_path"
  1127. token="$(printf "$keyauthorization" | cut -d '.' -f 1)"
  1128. _debug "writing token:$token to $wellknown_path/$token"
  1129. mkdir -p "$wellknown_path"
  1130. printf "$keyauthorization" > "$wellknown_path/$token"
  1131. if [ ! "$usingApache" ] ; then
  1132. webroot_owner=$(_stat $_currentRoot)
  1133. _debug "Changing owner/group of .well-known to $webroot_owner"
  1134. chown -R $webroot_owner "$_currentRoot/.well-known"
  1135. fi
  1136. fi
  1137. fi
  1138. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  1139. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  1140. _err "$d:Challenge error: $response"
  1141. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1142. _clearup
  1143. return 1
  1144. fi
  1145. waittimes=0
  1146. if [ -z "$MAX_RETRY_TIMES" ] ; then
  1147. MAX_RETRY_TIMES=30
  1148. fi
  1149. while [ "1" ] ; do
  1150. waittimes=$(_math $waittimes + 1)
  1151. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  1152. _err "$d:Timeout"
  1153. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1154. _clearup
  1155. return 1
  1156. fi
  1157. _debug "sleep 5 secs to verify"
  1158. sleep 5
  1159. _debug "checking"
  1160. response="$(_get $uri)"
  1161. if [ "$?" != "0" ] ; then
  1162. _err "$d:Verify error:$response"
  1163. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1164. _clearup
  1165. return 1
  1166. fi
  1167. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1168. if [ "$status" = "valid" ] ; then
  1169. _info "Success"
  1170. _stopserver $serverproc
  1171. serverproc=""
  1172. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1173. break;
  1174. fi
  1175. if [ "$status" = "invalid" ] ; then
  1176. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1177. _err "$d:Verify error:$error"
  1178. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1179. _clearup
  1180. return 1;
  1181. fi
  1182. if [ "$status" = "pending" ] ; then
  1183. _info "Pending"
  1184. else
  1185. _err "$d:Verify error:$response"
  1186. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1187. _clearup
  1188. return 1
  1189. fi
  1190. done
  1191. done
  1192. _clearup
  1193. _info "Verify finished, start to sign."
  1194. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1195. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1196. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1197. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  1198. if [ "$Le_LinkCert" ] ; then
  1199. echo "$BEGIN_CERT" > "$CERT_PATH"
  1200. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1201. echo "$END_CERT" >> "$CERT_PATH"
  1202. _info "Cert success."
  1203. cat "$CERT_PATH"
  1204. _info "Your cert is in $CERT_PATH"
  1205. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1206. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  1207. USER_PATH="$PATH"
  1208. _saveaccountconf "USER_PATH" "$USER_PATH"
  1209. fi
  1210. fi
  1211. if [ -z "$Le_LinkCert" ] ; then
  1212. response="$(echo $response | _dbase64 "multiline" )"
  1213. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1214. return 1
  1215. fi
  1216. _cleardomainconf "Le_Vlist"
  1217. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1218. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  1219. if [ "$Le_LinkIssuer" ] ; then
  1220. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1221. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1222. echo "$END_CERT" >> "$CA_CERT_PATH"
  1223. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1224. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1225. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1226. fi
  1227. Le_CertCreateTime=$(date -u "+%s")
  1228. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  1229. Le_CertCreateTimeStr=$(date -u )
  1230. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  1231. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "80" ] ; then
  1232. Le_RenewalDays=80
  1233. fi
  1234. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  1235. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  1236. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  1237. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1238. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  1239. _output="$(installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" 2>&1)"
  1240. _ret="$?"
  1241. if [ "$_ret" = "9" ] ; then
  1242. #ignore the empty install error.
  1243. return 0
  1244. fi
  1245. if [ "$_ret" != "0" ] ; then
  1246. _err "$_output"
  1247. return 1
  1248. fi
  1249. }
  1250. renew() {
  1251. Le_Domain="$1"
  1252. if [ -z "$Le_Domain" ] ; then
  1253. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1254. return 1
  1255. fi
  1256. _initpath $Le_Domain
  1257. if [ ! -f "$DOMAIN_CONF" ] ; then
  1258. _info "$Le_Domain is not a issued domain, skip."
  1259. return 0;
  1260. fi
  1261. . "$DOMAIN_CONF"
  1262. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1263. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1264. return 2
  1265. fi
  1266. IS_RENEW="1"
  1267. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1268. local res=$?
  1269. IS_RENEW=""
  1270. return $res
  1271. }
  1272. renewAll() {
  1273. _initpath
  1274. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1275. d=$(echo $d | cut -d '/' -f 1)
  1276. (
  1277. _info "Renew: $d"
  1278. renew "$d"
  1279. )
  1280. done
  1281. }
  1282. installcert() {
  1283. Le_Domain="$1"
  1284. if [ -z "$Le_Domain" ] ; then
  1285. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1286. return 1
  1287. fi
  1288. Le_RealCertPath="$2"
  1289. Le_RealKeyPath="$3"
  1290. Le_RealCACertPath="$4"
  1291. Le_ReloadCmd="$5"
  1292. Le_RealFullChainPath="$6"
  1293. _initpath $Le_Domain
  1294. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  1295. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  1296. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  1297. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  1298. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  1299. if [ "$Le_RealCertPath" = "no" ] ; then
  1300. Le_RealCertPath=""
  1301. fi
  1302. if [ "$Le_RealKeyPath" = "no" ] ; then
  1303. Le_RealKeyPath=""
  1304. fi
  1305. if [ "$Le_RealCACertPath" = "no" ] ; then
  1306. Le_RealCACertPath=""
  1307. fi
  1308. if [ "$Le_ReloadCmd" = "no" ] ; then
  1309. Le_ReloadCmd=""
  1310. fi
  1311. if [ "$Le_RealFullChainPath" = "no" ] ; then
  1312. Le_RealFullChainPath=""
  1313. fi
  1314. _installed="0"
  1315. if [ "$Le_RealCertPath" ] ; then
  1316. _installed=1
  1317. _info "Installing cert to:$Le_RealCertPath"
  1318. if [ -f "$Le_RealCertPath" ] ; then
  1319. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  1320. fi
  1321. cat "$CERT_PATH" > "$Le_RealCertPath"
  1322. fi
  1323. if [ "$Le_RealCACertPath" ] ; then
  1324. _installed=1
  1325. _info "Installing CA to:$Le_RealCACertPath"
  1326. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  1327. echo "" >> "$Le_RealCACertPath"
  1328. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1329. else
  1330. if [ -f "$Le_RealCACertPath" ] ; then
  1331. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1332. fi
  1333. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1334. fi
  1335. fi
  1336. if [ "$Le_RealKeyPath" ] ; then
  1337. _installed=1
  1338. _info "Installing key to:$Le_RealKeyPath"
  1339. if [ -f "$Le_RealKeyPath" ] ; then
  1340. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1341. fi
  1342. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1343. fi
  1344. if [ "$Le_RealFullChainPath" ] ; then
  1345. _installed=1
  1346. _info "Installing full chain to:$Le_RealFullChainPath"
  1347. if [ -f "$Le_RealFullChainPath" ] ; then
  1348. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1349. fi
  1350. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1351. fi
  1352. if [ "$Le_ReloadCmd" ] ; then
  1353. _installed=1
  1354. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1355. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  1356. _info "Reload success."
  1357. else
  1358. _err "Reload error for :$Le_Domain"
  1359. fi
  1360. fi
  1361. if [ "$_installed" = "0" ] ; then
  1362. _err "Nothing to install. You don't specify any parameter."
  1363. return 9
  1364. fi
  1365. }
  1366. installcronjob() {
  1367. _initpath
  1368. if ! _exists "crontab" ; then
  1369. _err "crontab doesn't exist, so, we can not install cron jobs."
  1370. _err "All your certs will not be renewed automatically."
  1371. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1372. return 1
  1373. fi
  1374. _info "Installing cron job"
  1375. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1376. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  1377. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1378. else
  1379. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1380. return 1
  1381. fi
  1382. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1383. fi
  1384. if [ "$?" != "0" ] ; then
  1385. _err "Install cron job failed. You need to manually renew your certs."
  1386. _err "Or you can add cronjob by yourself:"
  1387. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1388. return 1
  1389. fi
  1390. }
  1391. uninstallcronjob() {
  1392. if ! _exists "crontab" ; then
  1393. return
  1394. fi
  1395. _info "Removing cron job"
  1396. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1397. if [ "$cr" ] ; then
  1398. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1399. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1400. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1401. fi
  1402. _initpath
  1403. }
  1404. revoke() {
  1405. Le_Domain="$1"
  1406. if [ -z "$Le_Domain" ] ; then
  1407. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1408. return 1
  1409. fi
  1410. _initpath $Le_Domain
  1411. if [ ! -f "$DOMAIN_CONF" ] ; then
  1412. _err "$Le_Domain is not a issued domain, skip."
  1413. return 1;
  1414. fi
  1415. if [ ! -f "$CERT_PATH" ] ; then
  1416. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1417. return 1
  1418. fi
  1419. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1420. if [ -z "$cert" ] ; then
  1421. _err "Cert for $Le_Domain is empty found, skip."
  1422. return 1
  1423. fi
  1424. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1425. uri="$API/acme/revoke-cert"
  1426. _info "Try domain key first."
  1427. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1428. if [ -z "$response" ] ; then
  1429. _info "Revoke success."
  1430. rm -f $CERT_PATH
  1431. return 0
  1432. else
  1433. _err "Revoke error by domain key."
  1434. _err "$resource"
  1435. fi
  1436. fi
  1437. _info "Then try account key."
  1438. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1439. if [ -z "$response" ] ; then
  1440. _info "Revoke success."
  1441. rm -f $CERT_PATH
  1442. return 0
  1443. else
  1444. _err "Revoke error."
  1445. _debug "$resource"
  1446. fi
  1447. fi
  1448. return 1
  1449. }
  1450. # Detect profile file if not specified as environment variable
  1451. _detect_profile() {
  1452. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1453. echo "$PROFILE"
  1454. return
  1455. fi
  1456. local DETECTED_PROFILE
  1457. DETECTED_PROFILE=''
  1458. local SHELLTYPE
  1459. SHELLTYPE="$(basename "/$SHELL")"
  1460. if [ "$SHELLTYPE" = "bash" ] ; then
  1461. if [ -f "$HOME/.bashrc" ] ; then
  1462. DETECTED_PROFILE="$HOME/.bashrc"
  1463. elif [ -f "$HOME/.bash_profile" ] ; then
  1464. DETECTED_PROFILE="$HOME/.bash_profile"
  1465. fi
  1466. elif [ "$SHELLTYPE" = "zsh" ] ; then
  1467. DETECTED_PROFILE="$HOME/.zshrc"
  1468. fi
  1469. if [ -z "$DETECTED_PROFILE" ] ; then
  1470. if [ -f "$HOME/.profile" ] ; then
  1471. DETECTED_PROFILE="$HOME/.profile"
  1472. elif [ -f "$HOME/.bashrc" ] ; then
  1473. DETECTED_PROFILE="$HOME/.bashrc"
  1474. elif [ -f "$HOME/.bash_profile" ] ; then
  1475. DETECTED_PROFILE="$HOME/.bash_profile"
  1476. elif [ -f "$HOME/.zshrc" ] ; then
  1477. DETECTED_PROFILE="$HOME/.zshrc"
  1478. fi
  1479. fi
  1480. if [ ! -z "$DETECTED_PROFILE" ] ; then
  1481. echo "$DETECTED_PROFILE"
  1482. fi
  1483. }
  1484. _initconf() {
  1485. _initpath
  1486. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1487. echo "#ACCOUNT_CONF_PATH=xxxx
  1488. #Account configurations:
  1489. #Here are the supported macros, uncomment them to make them take effect.
  1490. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1491. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1492. #CERT_HOME=\"/path/to/cert/home\"
  1493. #STAGE=1 # Use the staging api
  1494. #FORCE=1 # Force to issue cert
  1495. #DEBUG=1 # Debug mode
  1496. #ACCOUNT_KEY_HASH=account key hash
  1497. USER_AGENT=\"$USER_AGENT\"
  1498. #USER_PATH=""
  1499. #dns api
  1500. #######################
  1501. #Cloudflare:
  1502. #api key
  1503. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1504. #account email
  1505. #CF_Email=\"xxxx@sss.com\"
  1506. #######################
  1507. #Dnspod.cn:
  1508. #api key id
  1509. #DP_Id=\"1234\"
  1510. #api key
  1511. #DP_Key=\"sADDsdasdgdsf\"
  1512. #######################
  1513. #Cloudxns.com:
  1514. #CX_Key=\"1234\"
  1515. #
  1516. #CX_Secret=\"sADDsdasdgdsf\"
  1517. " > $ACCOUNT_CONF_PATH
  1518. fi
  1519. }
  1520. _precheck() {
  1521. if ! _exists "curl" && ! _exists "wget"; then
  1522. _err "Please install curl or wget first, we need to access http resources."
  1523. return 1
  1524. fi
  1525. if ! _exists "crontab" ; then
  1526. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1527. _err "We need to set cron job to renew the certs automatically."
  1528. _err "Otherwise, your certs will not be able to be renewed automatically."
  1529. if [ -z "$FORCE" ] ; then
  1530. _err "Please add '--force' and try install again to go without crontab."
  1531. _err "./$PROJECT_ENTRY --install --force"
  1532. return 1
  1533. fi
  1534. fi
  1535. if ! _exists "openssl" ; then
  1536. _err "Please install openssl first."
  1537. _err "We need openssl to generate keys."
  1538. return 1
  1539. fi
  1540. if ! _exists "nc" ; then
  1541. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1542. _err "We use nc for standalone server if you use standalone mode."
  1543. _err "If you don't use standalone mode, just ignore this warning."
  1544. fi
  1545. return 0
  1546. }
  1547. _setShebang() {
  1548. _file="$1"
  1549. _shebang="$2"
  1550. if [ -z "$_shebang" ] ; then
  1551. _err "Usage: file shebang"
  1552. return 1
  1553. fi
  1554. cp "$_file" "$_file.tmp"
  1555. echo "$_shebang" > "$_file"
  1556. sed -n 2,99999p "$_file.tmp" >> "$_file"
  1557. rm -f "$_file.tmp"
  1558. }
  1559. install() {
  1560. if ! _initpath ; then
  1561. _err "Install failed."
  1562. return 1
  1563. fi
  1564. if ! _precheck ; then
  1565. _err "Pre-check failed, can not install."
  1566. return 1
  1567. fi
  1568. #convert from le
  1569. if [ -d "$HOME/.le" ] ; then
  1570. for envfile in "le.env" "le.sh.env"
  1571. do
  1572. if [ -f "$HOME/.le/$envfile" ] ; then
  1573. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1574. _upgrading="1"
  1575. _info "You are upgrading from le.sh"
  1576. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1577. mv "$HOME/.le" "$LE_WORKING_DIR"
  1578. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1579. break;
  1580. fi
  1581. fi
  1582. done
  1583. fi
  1584. _info "Installing to $LE_WORKING_DIR"
  1585. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1586. _err "Can not craete working dir: $LE_WORKING_DIR"
  1587. return 1
  1588. fi
  1589. chmod 700 "$LE_WORKING_DIR"
  1590. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1591. if [ "$?" != "0" ] ; then
  1592. _err "Install failed, can not copy $PROJECT_ENTRY"
  1593. return 1
  1594. fi
  1595. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1596. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1597. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  1598. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1599. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1600. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1601. fi
  1602. _setopt "$_envfile" "LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1603. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1604. _profile="$(_detect_profile)"
  1605. if [ "$_profile" ] ; then
  1606. _debug "Found profile: $_profile"
  1607. _setopt "$_profile" ". \"$LE_WORKING_DIR/$PROJECT_NAME.env\""
  1608. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1609. else
  1610. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1611. fi
  1612. if [ -d "dnsapi" ] ; then
  1613. mkdir -p $LE_WORKING_DIR/dnsapi
  1614. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1615. fi
  1616. #to keep compatible mv the .acc file to .key file
  1617. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1618. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1619. fi
  1620. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1621. _initconf
  1622. fi
  1623. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  1624. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1625. fi
  1626. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  1627. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1628. fi
  1629. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  1630. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1631. fi
  1632. installcronjob
  1633. if [ -z "$NO_DETECT_SH" ] ; then
  1634. #Modify shebang
  1635. if _exists bash ; then
  1636. _info "Good, bash is installed, change the shebang to use bash as prefered."
  1637. _shebang='#!/usr/bin/env bash'
  1638. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  1639. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  1640. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  1641. _setShebang "$_apifile" "$_shebang"
  1642. done
  1643. fi
  1644. fi
  1645. fi
  1646. _info OK
  1647. }
  1648. uninstall() {
  1649. uninstallcronjob
  1650. _initpath
  1651. _profile="$(_detect_profile)"
  1652. if [ "$_profile" ] ; then
  1653. text="$(cat $_profile)"
  1654. echo "$text" | sed "s|^[.] \"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  1655. fi
  1656. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  1657. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1658. }
  1659. cron() {
  1660. IN_CRON=1
  1661. renewAll
  1662. IN_CRON=""
  1663. }
  1664. version() {
  1665. echo "$PROJECT"
  1666. echo "v$VER"
  1667. }
  1668. showhelp() {
  1669. version
  1670. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  1671. Commands:
  1672. --help, -h Show this help message.
  1673. --version, -v Show version info.
  1674. --install Install $PROJECT_NAME to your system.
  1675. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  1676. --issue Issue a cert.
  1677. --installcert Install the issued cert to apache/nginx or any other server.
  1678. --renew, -r Renew a cert.
  1679. --renewAll Renew all the certs
  1680. --revoke Revoke a cert.
  1681. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1682. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  1683. --cron Run cron job to renew all the certs.
  1684. --toPkcs Export the certificate and key to a pfx file.
  1685. --createAccountKey, -cak Create an account private key, professional use.
  1686. --createDomainKey, -cdk Create an domain private key, professional use.
  1687. --createCSR, -ccsr Create CSR , professional use.
  1688. Parameters:
  1689. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  1690. --force, -f Used to force to install or force to renew a cert immediately.
  1691. --staging, --test Use staging server, just for test.
  1692. --debug Output debug info.
  1693. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  1694. --standalone Use standalone mode.
  1695. --apache Use apache mode.
  1696. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  1697. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  1698. --accountkeylength, -ak [2048] Specifies the account key length.
  1699. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  1700. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  1701. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  1702. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  1703. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  1704. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  1705. --accountconf Specifies a customized account config file.
  1706. --home Specifies the home dir for $PROJECT_NAME .
  1707. --certhome Specifies the home dir to save all the certs.
  1708. --useragent Specifies the user agent string. it will be saved for future use too.
  1709. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  1710. --accountkey Specifies the account key path, Only valid for the '--install' command.
  1711. --days Specifies the days to renew the cert when using '--issue' command. The max value is 80 days.
  1712. "
  1713. }
  1714. _installOnline() {
  1715. _info "Installing from online archive."
  1716. if [ ! "$BRANCH" ] ; then
  1717. BRANCH="master"
  1718. fi
  1719. _initpath
  1720. target="$PROJECT/archive/$BRANCH.tar.gz"
  1721. _info "Downloading $target"
  1722. localname="$BRANCH.tar.gz"
  1723. if ! _get "$target" > $localname ; then
  1724. _debug "Download error."
  1725. return 1
  1726. fi
  1727. _info "Extracting $localname"
  1728. tar xzf $localname
  1729. cd "$PROJECT_NAME-$BRANCH"
  1730. chmod +x $PROJECT_ENTRY
  1731. if ./$PROJECT_ENTRY install ; then
  1732. _info "Install success!"
  1733. fi
  1734. cd ..
  1735. rm -rf "$PROJECT_NAME-$BRANCH"
  1736. rm -f "$localname"
  1737. }
  1738. _process() {
  1739. _CMD=""
  1740. _domain=""
  1741. _altdomains="no"
  1742. _webroot=""
  1743. _keylength="no"
  1744. _accountkeylength="no"
  1745. _certpath="no"
  1746. _keypath="no"
  1747. _capath="no"
  1748. _fullchainpath="no"
  1749. _reloadcmd=""
  1750. _password=""
  1751. _accountconf=""
  1752. _useragent=""
  1753. _accountemail=""
  1754. _accountkey=""
  1755. _certhome=""
  1756. while [ ${#} -gt 0 ] ; do
  1757. case "${1}" in
  1758. --help|-h)
  1759. showhelp
  1760. return
  1761. ;;
  1762. --version|-v)
  1763. version
  1764. return
  1765. ;;
  1766. --install)
  1767. _CMD="install"
  1768. ;;
  1769. --uninstall)
  1770. _CMD="uninstall"
  1771. ;;
  1772. --issue)
  1773. _CMD="issue"
  1774. ;;
  1775. --installcert|-i)
  1776. _CMD="installcert"
  1777. ;;
  1778. --renew|-r)
  1779. _CMD="renew"
  1780. ;;
  1781. --renewAll|--renewall)
  1782. _CMD="renewAll"
  1783. ;;
  1784. --revoke)
  1785. _CMD="revoke"
  1786. ;;
  1787. --installcronjob)
  1788. _CMD="installcronjob"
  1789. ;;
  1790. --uninstallcronjob)
  1791. _CMD="uninstallcronjob"
  1792. ;;
  1793. --cron)
  1794. _CMD="cron"
  1795. ;;
  1796. --toPkcs)
  1797. _CMD="toPkcs"
  1798. ;;
  1799. --createAccountKey|--createaccountkey|-cak)
  1800. _CMD="createAccountKey"
  1801. ;;
  1802. --createDomainKey|--createdomainkey|-cdk)
  1803. _CMD="createDomainKey"
  1804. ;;
  1805. --createCSR|--createcsr|-ccr)
  1806. _CMD="createCSR"
  1807. ;;
  1808. --domain|-d)
  1809. _dvalue="$2"
  1810. if [ -z "$_dvalue" ] || _startswith "$_dvalue" "-" ; then
  1811. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  1812. return 1
  1813. fi
  1814. if [ -z "$_domain" ] ; then
  1815. _domain="$_dvalue"
  1816. else
  1817. if [ "$_altdomains" = "no" ] ; then
  1818. _altdomains="$_dvalue"
  1819. else
  1820. _altdomains="$_altdomains,$_dvalue"
  1821. fi
  1822. fi
  1823. shift
  1824. ;;
  1825. --force|-f)
  1826. FORCE="1"
  1827. ;;
  1828. --staging|--test)
  1829. STAGE="1"
  1830. ;;
  1831. --debug)
  1832. if [ -z "$2" ] || _startswith "$2" "-" ; then
  1833. DEBUG="1"
  1834. else
  1835. DEBUG="$2"
  1836. shift
  1837. fi
  1838. ;;
  1839. --webroot|-w)
  1840. wvalue="$2"
  1841. if [ -z "$_webroot" ] ; then
  1842. _webroot="$wvalue"
  1843. else
  1844. _webroot="$_webroot,$wvalue"
  1845. fi
  1846. shift
  1847. ;;
  1848. --standalone)
  1849. wvalue="no"
  1850. if [ -z "$_webroot" ] ; then
  1851. _webroot="$wvalue"
  1852. else
  1853. _webroot="$_webroot,$wvalue"
  1854. fi
  1855. ;;
  1856. --apache)
  1857. wvalue="apache"
  1858. if [ -z "$_webroot" ] ; then
  1859. _webroot="$wvalue"
  1860. else
  1861. _webroot="$_webroot,$wvalue"
  1862. fi
  1863. ;;
  1864. --dns)
  1865. wvalue="dns"
  1866. if ! _startswith "$2" "-" ; then
  1867. wvalue="$2"
  1868. shift
  1869. fi
  1870. if [ -z "$_webroot" ] ; then
  1871. _webroot="$wvalue"
  1872. else
  1873. _webroot="$_webroot,$wvalue"
  1874. fi
  1875. ;;
  1876. --keylength|-k)
  1877. _keylength="$2"
  1878. accountkeylength="$2"
  1879. shift
  1880. ;;
  1881. --accountkeylength|-ak)
  1882. accountkeylength="$2"
  1883. shift
  1884. ;;
  1885. --certpath)
  1886. _certpath="$2"
  1887. shift
  1888. ;;
  1889. --keypath)
  1890. _keypath="$2"
  1891. shift
  1892. ;;
  1893. --capath)
  1894. _capath="$2"
  1895. shift
  1896. ;;
  1897. --fullchainpath)
  1898. _fullchainpath="$2"
  1899. shift
  1900. ;;
  1901. --reloadcmd|--reloadCmd)
  1902. _reloadcmd="$2"
  1903. shift
  1904. ;;
  1905. --password)
  1906. _password="$2"
  1907. shift
  1908. ;;
  1909. --accountconf)
  1910. _accountconf="$2"
  1911. ACCOUNT_CONF_PATH="$_accountconf"
  1912. shift
  1913. ;;
  1914. --home)
  1915. LE_WORKING_DIR="$2"
  1916. shift
  1917. ;;
  1918. --certhome)
  1919. _certhome="$2"
  1920. CERT_HOME="$_certhome"
  1921. shift
  1922. ;;
  1923. --useragent)
  1924. _useragent="$2"
  1925. USER_AGENT="$_useragent"
  1926. shift
  1927. ;;
  1928. --accountemail )
  1929. _accountemail="$2"
  1930. ACCOUNT_EMAIL="$_accountemail"
  1931. shift
  1932. ;;
  1933. --accountkey )
  1934. _accountkey="$2"
  1935. ACCOUNT_KEY_PATH="$_accountkey"
  1936. shift
  1937. ;;
  1938. --days )
  1939. _days="$2"
  1940. Le_RenewalDays="$_days"
  1941. shift
  1942. ;;
  1943. *)
  1944. _err "Unknown parameter : $1"
  1945. return 1
  1946. ;;
  1947. esac
  1948. shift 1
  1949. done
  1950. case "${_CMD}" in
  1951. install) install ;;
  1952. uninstall) uninstall ;;
  1953. issue)
  1954. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1955. ;;
  1956. installcert)
  1957. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1958. ;;
  1959. renew)
  1960. renew "$_domain"
  1961. ;;
  1962. renewAll)
  1963. renewAll
  1964. ;;
  1965. revoke)
  1966. revoke "$_domain"
  1967. ;;
  1968. installcronjob) installcronjob ;;
  1969. uninstallcronjob) uninstallcronjob ;;
  1970. cron) cron ;;
  1971. toPkcs)
  1972. toPkcs "$_domain" "$_password"
  1973. ;;
  1974. createAccountKey)
  1975. createAccountKey "$_domain" "$_accountkeylength"
  1976. ;;
  1977. createDomainKey)
  1978. createDomainKey "$_domain" "$_keylength"
  1979. ;;
  1980. createCSR)
  1981. createCSR "$_domain" "$_altdomains"
  1982. ;;
  1983. *)
  1984. _err "Invalid command: $_CMD"
  1985. showhelp;
  1986. return 1
  1987. ;;
  1988. esac
  1989. if [ "$_useragent" ] ; then
  1990. _saveaccountconf "USER_AGENT" "$_useragent"
  1991. fi
  1992. if [ "$_accountemail" ] ; then
  1993. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  1994. fi
  1995. }
  1996. if [ "$INSTALLONLINE" ] ; then
  1997. INSTALLONLINE=""
  1998. _installOnline $BRANCH
  1999. exit
  2000. fi
  2001. if [ -z "$1" ] ; then
  2002. showhelp
  2003. else
  2004. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  2005. _process "$@"
  2006. else
  2007. "$@"
  2008. fi
  2009. fi