acme.sh 73 KB

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